Usage of SharedPreferences in Android

sharedpreferences

SharedPreferences is a way to persist data in key-value pair in Android. This is basically used to store a small set of data, though the exact maximum size is nowhere mentioned in documentations it is better to use this for data set less than 1 mb.

Note: This class does not support use across multiple processes.

Storage details

SharedPreferences are stored in xml file in app data folder i.e.,

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

or the default preferences at:

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

Datatype restriction

To store in SharedPreferences, there is a misunderstanding that it can only store primitive datatypes like, int, byte, boolean, String etc. We can even store any objects data using java serialization but it is not appropriate to use.

Sample code to write data from serializable object

static public String objectToString(Serializable object) {
        String encoded = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            objectOutputStream.close();
            encoded = new String(Base64.encodeToString(byteArrayOutputStream.toByteArray(),0));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return encoded;
    }

Once this method convert the object to base64 encoded string then save it like a string.

Sample code to read data from serializable object

@SuppressWarnings("unchecked")
   static public Serializable stringToObject(String string){
       byte[] bytes = Base64.decode(string,0);
       Serializable object = null;
       try {
           ObjectInputStream objectInputStream = new ObjectInputStream( new ByteArrayInputStream(bytes) );
           object = (Serializable)objectInputStream.readObject();
       } catch (IOException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (ClassCastException e) {
           e.printStackTrace();
       }
       return object;
   }

Using this above method we can fetch the respective string and convert it back to the object.

Can Parcelables  be used to store ?

From documentation from Parcel

Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.

So according to the official document, using parcelables are inappropriate but still it can be used to store in SharedPreferences by converting their underline members to json string during saving and again converting back to the respective object from json string at the time of fetching.

 

Hopefully this article will be insightful for all of you who have doubts about SharedPreferences in Android.

Happy coding!!!

Leave a Reply

Your email address will not be published. Required fields are marked *