In Android can we store an object of a class in shared preference and retrieve the object later?
If it is possible how to do it? If it is not possible what are the other possibilities of doing it?
I know that serialization is one option, but I am looking for possibilities using shared preference.
This question is related to
android
object
sharedpreferences
There is no way to store objects in SharedPreferences, What i did is to create a public class, put all the parameters i need and create setters and getters, i was able to access my objects,
Yes we can do this using Gson
Download Working code from GitHub
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
For save
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of MyObject
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
For get
Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);
The latest version of GSON can be downloaded from github.com/google/gson.
If you are using Gradle/Android Studio just put following in build.gradle
dependencies section -
implementation 'com.google.code.gson:gson:2.6.2'
Common shared preference (CURD) SharedPreference: to Store data in the form of value-key pairs with a simple Kotlin class.
var sp = SharedPreference(this);
Storing Data:
To store String, Int and Boolean data we have three methods with the same name and different parameters (Method overloading).
save("key-name1","string value")
save("key-name2",int value)
save("key-name3",boolean)
Retrieve Data: To Retrieve the data stored in SharedPreferences use the following methods.
sp.getValueString("user_name")
sp.getValueInt("user_id")
sp.getValueBoolean("user_session",true)
Clear All Data: To clear the entire SharedPreferences use the below code.
sp.clearSharedPreference()
Remove Specific Data:
sp.removeValue("user_name")
Common Shared Preference Class
import android.content.Context
import android.content.SharedPreferences
class SharedPreference(private val context: Context) {
private val PREFS_NAME = "coredata"
private val sharedPref: SharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
//********************************************************************************************** save all
//To Store String data
fun save(KEY_NAME: String, text: String) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putString(KEY_NAME, text)
editor.apply()
}
//..............................................................................................
//To Store Int data
fun save(KEY_NAME: String, value: Int) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putInt(KEY_NAME, value)
editor.apply()
}
//..............................................................................................
//To Store Boolean data
fun save(KEY_NAME: String, status: Boolean) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putBoolean(KEY_NAME, status)
editor.apply()
}
//********************************************************************************************** retrieve selected
//To Retrieve String
fun getValueString(KEY_NAME: String): String? {
return sharedPref.getString(KEY_NAME, "")
}
//..............................................................................................
//To Retrieve Int
fun getValueInt(KEY_NAME: String): Int {
return sharedPref.getInt(KEY_NAME, 0)
}
//..............................................................................................
// To Retrieve Boolean
fun getValueBoolean(KEY_NAME: String, defaultValue: Boolean): Boolean {
return sharedPref.getBoolean(KEY_NAME, defaultValue)
}
//********************************************************************************************** delete all
// To clear all data
fun clearSharedPreference() {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.clear()
editor.apply()
}
//********************************************************************************************** delete selected
// To remove a specific data
fun removeValue(KEY_NAME: String) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.remove(KEY_NAME)
editor.apply()
}
}
Blog: https://androidkeynotes.blogspot.com/2020/02/shared-preference.html
You could use GSON, using Gradle Build.gradle :
implementation 'com.google.code.gson:gson:2.8.0'
Then in your code, for example pairs of string/boolean with Kotlin :
val nestedData = HashMap<String,Boolean>()
for (i in 0..29) {
nestedData.put(i.toString(), true)
}
val gson = Gson()
val jsonFromMap = gson.toJson(nestedData)
Adding to SharedPrefs :
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit()
sharedPrefEditor.putString("sig_types", jsonFromMap)
sharedPrefEditor.apply()
Now to retrieve data :
val gson = Gson()
val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE)
val json = sharedPref.getString("sig_types", "false")
val type = object : TypeToken<Map<String, Boolean>>() {}.type
val map = gson.fromJson(json, type) as LinkedTreeMap<String,Boolean>
for (key in map.keys) {
Log.i("myvalues", key.toString() + map.get(key).toString())
}
Using Gson Library:
dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Store:
Gson gson = new Gson();
//Your json response object value store in json object
JSONObject jsonObject = response.getJSONObject();
//Convert json object to string
String json = gson.toJson(jsonObject);
//Store in the sharedpreference
getPrefs().setUserJson(json);
Retrieve:
String json = getPrefs().getUserJson();
Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc
Yes .You can store and retrive the object using Sharedpreference
we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:
mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = mPrefs.edit();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutput;
try {
objectOutput = new ObjectOutputStream(arrayOutputStream);
objectOutput.writeObject(object);
byte[] data = arrayOutputStream.toByteArray();
objectOutput.close();
arrayOutputStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(data);
b64.close();
out.close();
ed.putString(key, new String(out.toByteArray()));
ed.commit();
} catch (IOException e) {
e.printStackTrace();
}
when we need to extract Object from Preference. Use the code as below
byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
if (bytes.length == 0) {
return null;
}
ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
ObjectInputStream in;
in = new ObjectInputStream(base64InputStream);
MyObject myObject = (MyObject) in.readObject();
Do you need to retrieve the object even after the application shutting donw or just during it's running ?
You can store it into a database.
Or Simply create a custom Application class.
public class MyApplication extends Application {
private static Object mMyObject;
// static getter & setter
...
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application ... android:name=".MyApplication">
<activity ... />
...
</application>
...
</manifest>
And then from every activities do :
((MyApplication) getApplication).getMyObject();
Not really the best way but it works.
You can use Complex Preferences Android - by Felipe Silvestre library to store your custom objects. Basically, it's using GSON mechanism to store objects.
To save object into prefs:
User user = new User();
user.setName("Felipe");
user.setAge(22);
user.setActive(true);
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(
this, "mypref", MODE_PRIVATE);
complexPreferences.putObject("user", user);
complexPreferences.commit();
And to retrieve it back:
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE);
User user = complexPreferences.getObject("user", User.class);
I had the same problem, here's my solution:
I have class MyClass and ArrayList< MyClass > that I want to save to Shared Preferences. At first I've added a method to MyClass that converts it to JSON object:
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("id", this.id);
obj.put("name", this.name);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
Then here's the method for saving object "ArrayList< MyClass > items":
SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
SharedPreferences.Editor editor = mPrefs.edit();
Set<String> set= new HashSet<String>();
for (int i = 0; i < items.size(); i++) {
set.add(items.get(i).getJSONObject().toString());
}
editor.putStringSet("some_name", set);
editor.commit();
And here's the method for retrieving the object:
public static ArrayList<MyClass> loadFromStorage() {
SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0);
ArrayList<MyClass> items = new ArrayList<MyClass>();
Set<String> set = mPrefs.getStringSet("some_name", null);
if (set != null) {
for (String s : set) {
try {
JSONObject jsonObject = new JSONObject(s);
Long id = jsonObject.getLong("id"));
String name = jsonObject.getString("name");
MyClass myclass = new MyClass(id, name);
items.add(myclass);
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
Note that StringSet in Shared Preferences is available since API 11.
Source: Stackoverflow.com