RNK
RNK

Reputation: 5792

store array list in shared preferences with the type of an object

I have an array list of list_beneficiaries (type: Beneficiary). In that array list I have elements like of type Beneficiary object. Something like this,

list_beneficiaries.add(new Beneficiary(Integer.parseInt(obj2.getString("id")),
                       obj2.getString("ben_firstname"), obj2.getString("ben_lastname"));

I want to add this arraylist in shared preferences and retrieve it. How can I do that? I tried with this stackoverflow answers: Save ArrayList to SharedPreferences

But, I am not getting the result I want. Because I have an array type of object.

Upvotes: 0

Views: 130

Answers (2)

Aashis Shrestha
Aashis Shrestha

Reputation: 612

Use this and instead of ArrayList<String> use List<YourObjectClass> or ArrayList<YourObjectClass>

  public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();     // This line is IMPORTANT !!!
}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Upvotes: 0

Simas
Simas

Reputation: 44118

I really like Gson. It's easy to use:

  1. Download the jar and save to app/libs/.

  2. Update gradle dependencies (build.gradle):

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.google.code.gson:gson:2.3'
    }
    
  3. Update your code:

    ArrayList<MyClass> array = new ArrayList<>();
    
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = prefs.edit();
    
    // Put
    Gson gson = new Gson();
    String json = gson.toJson(array);
    editor.putString("preference_key", json);
    editor.commit(); //every change in editor object is commited.
    // Get
    json = prefs.getString("preference_key", null);
    java.lang.reflect.Type type = new TypeToken<ArrayList<MyClass>>(){}.getType();
    array = gson.fromJson(json, type);
    

Upvotes: 3

Related Questions