如何在SharedPreferences中保存类对象引用值并在android中检索它?

时间:2015-03-05 17:53:51

标签: android sharedpreferences gson

现在我正在尝试将类对象值存储在SharedPreferences中并检索它。我还提到了许多链接,我无法将对象值存储在其中。

以下是我的代码:

SharedPreferences  mPrefs = getContext().getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = null;
prefsEditor.putString(json, gson.toJson(object));
prefsEditor.commit();

例外:

 java.lang.StackOverflowError
            at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)

1 个答案:

答案 0 :(得分:0)

对象需要实现 Serializable ,以便Gson可以将您的Object转换为字符串。像这样:

public class User implement Serializable {

  private static final long serialVersionUID = 1234567891234567891L;

  private String name;
  private int age;

  // constructor
  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // setter and getter.
}

然后你可以用Gson保存对象:

User user = new User("Terminator", 50);

SharedPreferences  mPrefs = getContext().getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(user);
prefsEditor.putString("User", json);
prefsEditor.commit();