80

I have an ArrayList of an object. The object contains the types 'Bitmap' and 'String' and then just getters and setters for both. First of all is Bitmap serializable?

How would I go about serializing this to store it in SharedPreferences? I have seen many people ask a similar question but none seem to give a good answer. I would prefer some code examples if at all possible.

If bitmap is not serializable then how do I go about storing this ArrayList?

3
  • the drawback of SharedPreferences is that you cannot store objects in it so its not possible to store object :( Commented Feb 20, 2013 at 13:41
  • To serialize it, you can use this answer. I don't know how that helps with SharedPreferences, though, since you can't just store serialized objects there. Maybe you're thinking of a Bundle? Commented Feb 20, 2013 at 13:44
  • 1
    yes you can save. Check my answer. Commented Feb 21, 2013 at 20:49

8 Answers 8

150

Yes, you can save your composite object in shared preferences. Let's say..

 Student mStudentObject = new Student();
 SharedPreferences appSharedPrefs = PreferenceManager
             .getDefaultSharedPreferences(this.getApplicationContext());
 Editor prefsEditor = appSharedPrefs.edit();
 Gson gson = new Gson();
 String json = gson.toJson(mStudentObject);
 prefsEditor.putString("MyObject", json);
 prefsEditor.commit(); 

..and now you can retrieve your object as:

 SharedPreferences appSharedPrefs = PreferenceManager
             .getDefaultSharedPreferences(this.getApplicationContext());
 Gson gson = new Gson();
 String json = appSharedPrefs.getString("MyObject", "");
 Student mStudentObject = gson.fromJson(json, Student.class);

For more information, click here.

If you want to get back an ArrayList of any type object e.g. Student, then use:

Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students = gson.fromJson(json, type);
Sign up to request clarification or add additional context in comments.

5 Comments

How to put JSON array name when storing it into prefs?
What did you mean? please elaborate your question.?
This code does not work if you want to save an ARRAYLIST
@Bhavik Metha , Above written code is not for Arraylists, above code is just example. If you want to get back Array List of type any any object e.d student, then us: Type type = new TypeToken<List<Student>>(){}.getType(); List<Student> students= gson.fromJson(json, type);
How can I update this list? Is there any way that can I update this list?
124

The answer above works, but not for list:

For saving list of objects do like this:

List<Cars> cars= new ArrayList<Cars>();
    cars.add(a);
    cars.add(b);
    cars.add(c);
    cars.add(d);

    gson = new Gson();
    String jsonCars = gson.toJson(cars);
    Log.d("TAG","jsonCars = " + jsonCars);

Read the json object:

Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(jsonCars, type);

3 Comments

What is the package of Type here?
import java.lang.reflect.Type;
What if I use wildcards something like: Type type = new TypeToken<List<?>>(){}.getType(); As a result I am getting a LinkedTreeMap and this is the definition of my method: public static List<?> getList(String json) {
25

For me it worked like this :

Put values in SharedPreferances :

String key = "Key";
ArrayList<ModelClass> ModelArrayList=new ArrayList();

SharedPreferences shref;
SharedPreferences.Editor editor;
shref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

Gson gson = new Gson();
String json = gson.toJson(ModelArrayList);

editor = shref.edit();
editor.remove(key).commit();
editor.putString(key, json);
editor.commit();

To get values from SharedPreferances :

Gson gson = new Gson();
String response=shref.getString(key , "");
ArrayList<ModelClass> lstArrayList = gson.fromJson(response, 
    new TypeToken<List<ModelClass>>(){}.getType());

Comments

16

For Save:

public static void saveSharedPreferencesLogList(Context context, List<PhoneCallLog> callLog) {
    SharedPreferences mPrefs = context.getSharedPreferences(Constant.CALL_HISTORY_RC, context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(callLog);
    prefsEditor.putString("myJson", json);
    prefsEditor.commit();
}

For load:

public static List<PhoneCallLog> loadSharedPreferencesLogList(Context context) {
    List<PhoneCallLog> callLog = new ArrayList<PhoneCallLog>();
    SharedPreferences mPrefs = context.getSharedPreferences(Constant.CALL_HISTORY_RC, context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = mPrefs.getString("myJson", "");
    if (json.isEmpty()) {
        callLog = new ArrayList<PhoneCallLog>();
    } else {
        Type type = new TypeToken<List<PhoneCallLog>>() {
        }.getType();
        callLog = gson.fromJson(json, type);
    }
    return callLog;
}

PhoneCallLog is my custom object's name. (Contains String, long and boolean values)

2 Comments

Shouldn't we use apply instead of commit ?
Where we need to place those method calls?
3

Mete' example above worked like a charm.
Here is a Kotlin example

private var prefs: SharedPreferences = context?.getSharedPreferences("sharedPrefs", MODE_PRIVATE)
    ?: error("err")
private val gson = Gson()

save

fun saveObjectToArrayList(yourObject: YourObject) {
    val bookmarks = fetchArrayList()
    bookmarks.add(0, yourObject)
    val prefsEditor = prefs.edit()

    val json = gson.toJson(bookmarks)
    prefsEditor.putString("your_key", json)
    prefsEditor.apply()
}

read

fun fetchArrayList(): ArrayList<YourObject> {
    val yourArrayList: ArrayList<YourObject>
    val json = prefs.getString("your_key", "")

    yourArrayList = when {
        json.isNullOrEmpty() -> ArrayList()
        else -> gson.fromJson(json, object : TypeToken<List<Feed>>() {}.type)
    }

    return yourArrayList
}

Comments

1

The kotlin implementation with Gson, extending @SpyZips's answer,

Serializing to JSON

val jsonCars: String = Gson().toJson(cars);

Deserializing to back to list of objs

val type = object: TypeToken<List<Car>>(){}.type
val carsList: List<Car> = Gson().fromJson(jsonCars, type)

Comments

0

solution

Don't worry you can follow my code.I am using own custom class of sharedPreference for holding anytype of List in sharedPreference.

public class AuthPreference {
    private static final String MY_PREFERENCES = "MY_PREFERENCES";
    private static final int MODE = Context.MODE_PRIVATE;
    private static AuthPreference pref;
    private final SharedPreferences sharedPreference;
    private final SharedPreferences.Editor editor;

    @SuppressLint("CommitPrefEdits")
    public AuthPreference(Context context) {
        sharedPreference = context.getSharedPreferences(MY_PREFERENCES, MODE);
        editor = sharedPreference.edit();
    }

    public void clear() {
        editor.clear().commit();

    }

    //Here  save your api responce like YourModel arraylist

    public void saveDataResponce(ArrayList<YourModel> model_, String key) {
        SharedPreferences.Editor editor = sharedPreference.edit();
        Gson gson = new Gson();
        String json = gson.toJson(model_);
        editor.putString(key, json);
        editor.apply();
    }

//Here we get our api responce like YourModel arraylist.Using key value when you want to define.

    public ArrayList<YourModel> getDataResponce(String key) {
        Gson gson = new Gson();
        String json = sharedPreference.getString(key, null);
        Type type_ = new TypeToken<ArrayList<YourModel>>() {
        }.getType();
        return gson.fromJson(json, type_);
    }
}

Comments

0

You can Use below

public static String MyClassListToJsonString(List<MyClassEntry> myMyClassList){
    Gson myGson = new Gson();
    return myGson.toJson(myMyClassList);
}

public static List<MyClass> JsonStringToDepositList(String jsonString){
    Gson myGson = new Gson();
    Type type = new TypeToken<List<MyClassEntry>>(){}.getType();
    return myGson.fromJson(jsonString, type);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.