将列表放在sharedPreferences中

时间:2015-12-11 07:30:06

标签: java android android-sharedpreferences

我创建了课程Employee,我也让List<Employee>接受了该课程中的对象。

我在该列表中放了三个对象,我想在关闭应用程序后保存它们。我尝试使用SharedPreferences来放置列表,但似乎SharedPreferences不接受将列表放入其中。我该怎么办?

    @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>



}

3 个答案:

答案 0 :(得分:1)

您不能在sharedPrefs中存储对象列表,但可以存储一组字符串:

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

}

为了将自定义对象存储为字符串,您需要序列化它们(例如作为json)并保存此字符串。在加载值时,需要对它们进行反序列化。

您可以阅读此guide以获取有关如何将对象序列化为JSON的高级帮助。

答案 1 :(得分:1)

这不是使用共享偏好的答案,但认为它可能会有所帮助

序列化一个对象并传递它:

我使用下面的代码,然后编写一个具有任何变量的类,而不是不可靠的共享首选项。

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

然后是示例类:

public class Timestamps implements Serializable {

private float timestampServer;

public float getTimestampServer() {
    return timestampServer;
}

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

}

然后在活动中:

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

答案 2 :(得分: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

这是我解决它的方式: 将以下库添加到项目中(采用最新的库):

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

您将Employee对象转换为字符串并存储在共享首选项中:

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

如果您有疑问,请在下方评论