Android - Sharedpreferences with Serializable Object

Android - SharedPreferences with serializable object

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;
}

}

Saving Serializable Objects List into sharedPreferences

You can use the JSON format to serialize your ArrayList and the objects it contains, and then store the String result into the SharedPreferences.

When you want to get the data back, retrieve the String and use a JSONArray to retrieve each object and add it to a new ArrayList.

Otherwise you can simply use Object(Input/Output)Stream classes and write it into a differente file using (for writing)

FileOutputStream fos = this.openFileOutput(fileName, MODE_PRIVATE);
final OutputStreamWriter osw = new OutputStreamWriter(fos);
JSONArray array = new JSONArray();

// Add your objects to the array

osw.write(array.toString());
osw.flush();
osw.close();

How do you save/store objects in SharedPreferences on Android?

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:

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

you can find latest version here

Creating a shared preference:

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

To save:

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.

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

To retrieve:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

SharedPreferences for serialization?

Shared prefs is a good way to save that kind of data. I don't know what would be better about using a file in internal storage. (If it was a lot of data, I'd consider using a file on the sdcard.)

Android ArrayList of custom objects - Save to SharedPreferences - Serializable?

Yes, you can save your composite object in shared preferences. Let's say..

 Student mStudentObject = new Student();
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(mStudentObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

..and now you can retrieve your object as:

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

For more information, click here.

If you want to get back an ArrayList of any type object e.g. Student, then use:

Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students = gson.fromJson(json, type);

store and retrieve a class object in shared preference

Not possible.

You can only store, simple values in SharedPrefences SharePreferences.Editor

What particularly about the class do you need to save?

Android - save Object to SharedPreferences and get it anywhere in the app

Replace your existing User class with below

public class User implements Serializable
{

private static User userInstance = null; // the only instance of the class
private String userName; // userName = the short phone number
private User(){}
public static User getInstance()
{
if (userInstance == null)
{
userInstance = new User();
}
return userInstance;
}

public String getUserName()
{
return userName;
}

public void setUserName(String p_userName)
{
userName = p_userName;
}

@Override
public String toString()
{
return "User [userName=" + getUserName() + "]";
}
}

Initialize User Name

User m_user = User.getInstance();
m_user.setUserName(name);

Convert the object to a String

Gson gson = new Gson();
String stringUser = gson.toJson(m_user);
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);

How to save ListObject to SharedPreferences?

It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:

private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);

private static SharedPreferences.Editor editor = sharedPreferences.edit();

public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);

set(key, json);
}

public static void set(String key, String value) {
editor.putString(key, value);
editor.commit();
}

Extra Shot from below comment by @StevenTB

To Retrive

 public List<YourModel> getList(){
List<YourModel> arrayItems;
String serializedObject = sharedPreferences.getString(KEY_PREFS, null);
if (serializedObject != null) {
Gson gson = new Gson();
Type type = new TypeToken<List<YourModel>>(){}.getType();
arrayItems = gson.fromJson(serializedObject, type);
}
}


Related Topics



Leave a reply



Submit