M.ArslanKhan
M.ArslanKhan

Reputation: 3898

How to put Arraylist of Custom Object in a SharedPreference

I want to save Arraylist of Custom type Object in sharedPreference. For that purpose I passed Arraylist to Gson, there is no compile error but after running this code device wait for long time and got stuck. Kindly suggest me other way if I am on wrong way.

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 Class

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;
    }
}

Upvotes: 0

Views: 66

Answers (1)

Rohit Heera
Rohit Heera

Reputation: 2727

class Mydata 

{

ArrayList<AppInfo> data;

    public Mydata (List<AppInfo> data) {

        this.data= data;

    }

    public List<AppInfo> getContactSyn() {
        return data;
    }

    public void setContactSyn(List<AppInfo> data) {
        this.data= data;
    }


}

 Gson gson = new Gson();
MyData datalist = new MyData(data);

    String jsonData = gson.toJson(datalist);

Upvotes: 1

Related Questions