代码如下。
将对象存储到共享首选项中
public void saveObject()
{
AccountVO accountVO1 = new AccountVO("1", "scott", "password", "scott@mail.com", "Scott", "Stanford");
accountsSharedPreference = context.getSharedPreferences("AccountsPrefsFile",Context.MODE_WORLD_PRIVATE);
accountsPreferenceEdit = accountsSharedPreference.edit();
accountsPreferenceEdit.putString("accountObject", accountVO1.toString());
accountsPreferenceEdit.commit();
}
从相同的共享首选项中检索对象
public AccountVO loadObject()
{
AccountVO accountVO1 = null;
accountsSharedPreference = context.getSharedPreferences("AccountsPrefsFile",context.MODE_PRIVATE);
String accounntsObjectString = accountsSharedPreference.getString("accountObject", "");
//My issue ? --- How to retreive the AccountVO object from "accountObject" String here????
return accountVO1;
}
我的AccountVO类代码如下:
public class AccountVO
{
private String id;
private String username;
private String password;
private String email;
private String firstName;
private String lastName;
public AccountVO(String tempID, String tempUserName, String tempPassword, String tempEmail, String tempFirstName, String tempLastName)
{
this.id = tempID;
this.username = tempUserName;
this.password = tempPassword;
this.email = tempEmail;
this.firstName = tempFirstName;
this.lastName = tempLastName;
}
public String getId()
{
return id;
}
public String getUserName()
{
return username;
}
public String getEmail()
{
return email;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
}
谁能告诉我如何在 loadObject 方法中从 accountObject 字符串中检索 AccountVO 对象。
最佳答案
您不能使用 toString()
属性构造对象。 Object.toString()
只返回对象的哈希值表示,而不是内存地址或其他任何东西。这意味着多个对象可以从 toString()
返回相同的结果。例如:
new Byte(10).toString()
和 "10".toString()
要将您的对象存储在 SharedPreferences 中,我建议您将它们存储为键值对,前提是您知道 AccountVO 对象的确切格式。 (在该类中添加一个助手可能会为您返回一个键值对映射)
或
重写您的 AccountVO 类中的 toString 方法以返回一个字符串,稍后您可以在稍后从 SharedPreferences 检索时轻松破译该字符串。像这样:
@Override
public String toString() {
return id+"<delim>"+username+"<delim>"+password+"<delim>"+email+"<delim>"+firstName+"<delim>"+lastName;
}
然后在您的 loadObject()
方法中,使用以下方法重建对象:
public AccountVO loadObject()
{
AccountVO accountVO1 = null;
accountsSharedPreference = context.getSharedPreferences("AccountsPrefsFile",context.MODE_PRIVATE);
String accounntsObjectString = accountsSharedPreference.getString("accountObject", "");
String[] parts = accounntsObjectString.split("<delim>");
return new accountVO1(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);
}
关于android - 保存和加载对象 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14127860/