Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - SharedPreferences with serializable object

I know that SharedPreferences has putString(), putFloat(), putLong(), putInt() and putBoolean(). But I need to store an object that is of type Serializable in SharedPreferences. How can I achieve this?

like image 601
Carnal Avatar asked Apr 28 '11 09:04

Carnal


People also ask

Can we store objects in SharedPreferences?

We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference.

How do I save an Arraylist of custom objects to SharedPreferences?

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

How do you save the object of the model class in preferences?

In Android, SharedPreferences class can save only these: We use the GSON library to convert the model class to JSON String and we save that JSON String into the SharedPreferences. We read back that JSON String and convert it back to the object when we want to read it.


2 Answers

In short you cant, try serializing your object to a private file, it amounts to the same thing. sample class below:

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;  import android.app.Activity; import android.content.Context;  /**  *  * Writes/reads an object to/from a private local file  *   *  */ public class LocalPersistence {       /**      *       * @param context      * @param object      * @param filename      */     public static void witeObjectToFile(Context context, Object object, String filename) {          ObjectOutputStream objectOut = null;         try {              FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);             objectOut = new ObjectOutputStream(fileOut);             objectOut.writeObject(object);             fileOut.getFD().sync();          } catch (IOException e) {             e.printStackTrace();         } finally {             if (objectOut != null) {                 try {                     objectOut.close();                 } catch (IOException e) {                     // do nowt                 }             }         }     }       /**      *       * @param context      * @param filename      * @return      */     public static Object readObjectFromFile(Context context, String filename) {          ObjectInputStream objectIn = null;         Object object = null;         try {              FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);             objectIn = new ObjectInputStream(fileIn);             object = objectIn.readObject();          } catch (FileNotFoundException e) {             // Do nothing         } catch (IOException e) {             e.printStackTrace();         } catch (ClassNotFoundException e) {             e.printStackTrace();         } finally {             if (objectIn != null) {                 try {                     objectIn.close();                 } catch (IOException e) {                     // do nowt                 }             }         }          return object;     }  } 
like image 173
Chris.D Avatar answered Oct 01 '22 15:10

Chris.D


The accepted answer is misleading, we can store serializable object into SharedPreferences by using GSON. Read more about it at google-gson.

you can add GSON dependency in Gradle file with:

compile 'com.google.code.gson:gson:2.7' 

Here the snippet:

First, create your usual sharedPreferences:

//Creating a shared preference SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE); 

Saving from serializable object to preference:

 Editor prefsEditor = mPrefs.edit();  Gson gson = new Gson();  String json = gson.toJson(YourSerializableObject);  prefsEditor.putString("SerializableObject", json);  prefsEditor.commit(); 

Get serializable object from preference:

Gson gson = new Gson(); String json = mPrefs.getString("SerializableObject", ""); yourSerializableObject = gson.fromJson(json, YourSerializableObject.class); 
like image 24
ישו אוהב אותך Avatar answered Oct 01 '22 14:10

ישו אוהב אותך