【发布时间】:2015-12-23 10:13:38
【问题描述】:
我想在 sharedPreference 中保存自定义类型 Object 的 Arraylist。为此,我将 Arraylist 传递给 Gson,没有编译错误,但运行此代码设备后等待很长时间并卡住了。如果我走错了路,请给我其他建议。
public void storeApps(Context context, List<AppInfo> apps) {
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonData = gson.toJson(apps);// this line wait for long time at compile time.
editor.putString(Fav, jsonData);
editor.commit();
}
AppInfo 类
public class AppInfo {
public String appname = "";
public String pname = "";
public String versionName = "";
public int versionCode = 0;
public Drawable icon;
public int color = 0;
public String getAppname() {
return appname;
}
public String getVersionName() {
return versionName;
}
public String getPname() {
return pname;
}
public Drawable getIcon() {
return icon;
}
public int getVersionCode() {
return versionCode;
}
public int getColor() {
return color;
}
public void setAppname(String appname) {
this.appname = appname;
}
public void setPname(String pname) {
this.pname = pname;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public void setVersionCode(int versionCode) {
this.versionCode = versionCode;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public void setColor(int color) {
this.color = color;
}
public AppInfo() { }
public AppInfo(String appname, String pname, String versionName, int versionCode, Drawable icon, int color) {
this.appname = appname;
this.pname = pname;
this.versionName = versionName;
this.versionCode = versionCode;
this.icon = icon;
this.color = color;
}
}
【问题讨论】:
-
实际上应用程序信息是预定义的类,这就是 Gson 无法转换它的原因。您需要创建自己的类,仅在您想要的字段中存储所需的数据。
-
@Rohit Heera AppInfo 是我创建的一个类。它不是预定义的类
-
好的,列表的大小是多少
-
@RohitHeera apps.size() 是 29
-
当我可以转换联系人列表时,我可以发布一个在我的情况下工作正常的代码..
标签: android arraylist sharedpreferences