Saving an entire Bundle to SharedPreferences

Viewed 7000

Assuming a method of mine was passed a Bundle already filled with data to be saved, is there a way to save it to SharedPreferences without taking it apart to ints, floats, Strings, etc.?

I prefer the convenience of writing/committing it all in "one fell swoop", so if this isn't possible using SharedPreferences, what other persistent storage approach would you recommend?

3 Answers
  • Note: If you are using Gson in your project then I think this is a better solution.

I simply used Gson from Google to serialize the specified object into its equivalent JSON representation:

Use this dependency

implementation 'com.google.code.gson:gson:2.8.6'

Code:

Gson gson = new Gson();
String dataToJson = gson.toJson(modelObj);

Then I stored dataToJson as a string in SharedPreferences.Simple!

At the time of string extraction:

String myStoredVal = Value stored in SharedPreference. 
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();

Gson gson = builder.create();
MyModel modelObj = gson.fromJson(prodDataStr, MyModel.class);
Related