如何将自定义对象的Arraylist放在SharedPreference中

时间:2015-12-23 10:13:39

标签: android arraylist sharedpreferences

我想在 sharedPreference 中保存自定义类型对象的 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;
    }
}

1 个答案:

答案 0 :(得分:1)

{{1}}