0

I made class Employee and I also made List<Employee> which accept object from the the class.

I put three objects in that list and I want to save them after close the app. I try to use SharedPreferences to put the list but it seem that SharedPreferences does not accept to put list in it. How can I do it?

    @Override
protected void onPause() {
    super.onPause();

    SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
    SharedPreferences.Editor editor = data.edit();
    // I cant use editor to put list<Employee>



}
5

3 Answers 3

1
Shared Preferences takes only string so you can't keep an object into shared preferences. This problem comes if you want to send Employee object from one activity to another activity

This is how i solved it: Add the following library to your project(take the latest one):

'com.google.code.gson:gson:1.7.2'

You convert the Employee object to string and store in shared preferences:

Gson gson = new Gson();
String jsonString = gson.toJson(employeeObject);
//store this string in shared preferences and next time when you come back
//get string from shared preferences and convert this back to object
Gson gson = new Gson();
Employee example = gson.fromJson(jsonString, Employee.class);

Comment below if you have doubts

1

This isn't exactly the answer using shared preferences but thought it may help

Serialize an object and pass it around :

I use the code below and then write a class that will have any variables rather than shared preferences that is not dependable.

public class SharedVariables {

public static <S extends Serializable> void writeObject(
        final Context context, String key, S serializableObject) {

    ObjectOutputStream objectOut = null;
    try {
        FileOutputStream fileOut = context.getApplicationContext().openFileOutput(key, Activity.MODE_PRIVATE);
        objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(serializableObject);
        fileOut.getFD().sync();
    } catch (IOException e) {
        Log.e("SharedVariable", e.getMessage(), e);
    } finally {
        if (objectOut != null) {
            try {
                objectOut.close();
            } catch (IOException e) {
                Log.e("SharedVariable", e.getMessage(), e);
            }
        }
    }
}

public static <S extends Serializable> S readObject(
        final Context context, String key, Class<S> serializableClass) {

    ObjectInputStream objectIn = null;
    try {
        FileInputStream fileIn = context.getApplicationContext().openFileInput(key);
        objectIn = new ObjectInputStream(fileIn);
        final Object object = objectIn.readObject();
        return serializableClass.cast(object);
    } catch (IOException e) {
        Log.e("SharedVariable", e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        Log.e("SharedVariable", e.getMessage(), e);
    } finally {
        if (objectIn != null) {
            try {
                objectIn.close();
            } catch (IOException e) {
                Log.e("SharedVariable", e.getMessage(), e);
            }
        }
    }
    return null;
}}

Then example class:

public class Timestamps implements Serializable {

private float timestampServer;

public float getTimestampServer() {
    return timestampServer;
}

public void setTimestampServer(float timestampServer) {
    this.timestampServer = timestampServer;
}

}

Then in activity:

SharedVariables.writeObject(getApplicationContext(), "Timestamps", timestampsData);
1

You can't store a list of objects in sharedPrefs, but you can store a Set of String:

@Override
protected void onPause() {
    super.onPause();

    // Your list of epmloyees
    List<Employee> someList;
    // The Set to store the converted objects
    Set<String> objects = new HashSet<String>();

    // Convert each Object into a JSON-String
    for (Employee e : someList) {
        objects.add(new Gson().toJson(e));
    }

    SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);
    SharedPreferences.Editor editor = data.edit();

    // Store the Set of JSON-String into the sharedPrefs
    editor.putStringSet("key", objects);
}

@Override
protected void onResume() {
    super.onResume();

    SharedPreferences data = this.getSharedPreferences("data",MODE_PRIVATE);

    // Empty list of employees
    List<Employee> someList = new ArrayList<>();
    // Set of JSON-Strings from the sharedPrefs
    Set<String> objects = data.getStringSet("key", null);

    // Convert each JSON-String into an Object of Employee
    for (String s : objects) {
        objects.add(new Gson().fromJson(s, Employee.class);
    }         

}

In order to store your custom objects as a string, you need to serialize them (for example as json) and save this string. On loading the value you need to deserialize them.

You can read this guide for advanced help on how to serialize Objects into JSON.

2
  • my aim is to save the list of object after close the programm
    – maysara
    Dec 11, 2015 at 7:35
  • yeah thats how you do it, just use this in your onPause() method. Dec 11, 2015 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.