We need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?
I can't store it like this:
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);
See here, this can help you:
https://github.com/AltasT/PreferenceVObjectFile/blob/master/PreferenceVObjectFile/src/com/altas/lib/PreferenceUtils.java
Step 1: Copy paste these two functions in your java file.
Step 2: to save use:
to retrieve use:
You can set different shared preferences by using different key names like:
You can save object in preferences without using any library, first of all your object class must implement Serializable:
}
Then you can easily use these two method to convert object to string and string to object:
To save:
To read
there are two file solved your all problem about sharedpreferences
1)AppPersistence.java
2)AppPreference.java
now you can save,remove or get like,
-save
-remove
-get
You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson
Or add the GSON dependency in your Gradle file:
Creating a shared preference:
To save:
To retrieve:
If your Object is complex I'd suggest to Serialize/XML/JSON it and save those contents to the SD card. You can find additional info on how to save to external storage here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal