0

我做了课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>



}
4

3 回答 3

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);
于 2015-12-11T07:37:59.427 回答
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)并保存此字符串。在加载值时,您需要反序列化它们。

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

于 2015-12-11T07:33:54.510 回答
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);

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

于 2015-12-11T07:41:05.543 回答