【发布时间】:2015-06-07 01:17:07
【问题描述】:
在我的应用程序中,我有一个自定义的 User 类,其中包含一些常规数据(名称等)。我需要保存该对象并随时随地在应用程序的其他页面中获取它。我用许多我经常使用的方法(当然是静态的)创建了一个辅助类public final class GeneralMethods。
为了保存数据,我使用Gson 库。我做了这个方法:
public static void saveData(Context con, String variable, String data)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
prefs.edit().putString(variable, data).apply();
}
为了保存一个对象,我使用这个方法如下:
Gson gson = new Gson();
String stringUser = gson.toJson(newUser);
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);
为了加载数据,我使用了这个静态方法:
public static String getData(Context con, String variable, String defaultValue)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
String data = prefs.getString(variable, defaultValue);
return data;
}
我真的不知道如何取回数据,这是我到目前为止所做的:
Gson gson = new Gson();
String user="";
String value="";
user = GeneralMethods.getData(SplashScreenActivity.this,value,"userObject");
我正在努力使用getData 方法,如何将数据从String 解析回User 类型?
编辑
我尝试了下面的建议,我总是得到NULL。也许我没有以正确的方式保存对象?
EDIT2
似乎我没有正确生成对象,因此没有保存任何内容。这是用户“Singleton”类:
public class User implements Serializable {
private static User userInstance=null; //the only instance of the class
private static String userName; //userName = the short phone number
private User(){}
public static User getInstance(){
if(userInstance ==null){
userInstance = new User();
}
return userInstance;
}
public static User getUserInstance() {
return userInstance;
}
public String getUserName(){
return this.userName;
}
public static void setUserName(String userName) {
User.userName = userName;
}
public static void init(String _userName) {
User.setUserName(_userName);
}
}
这就是我使用相关数据设置对象的方式(用户名作为构造函数参数):
User.init(name);
这就是我将对象转换为String 的方式:
Gson gson = new Gson();
String stringUser = gson.toJson(User.getInstance());
GeneralMethods.saveData(VerificationActivity.this,"userObject",stringUser);
【问题讨论】:
-
使用序列化进行数据存储是个坏主意。使用一些东西来存储数据。以领域为例。
标签: java android sharedpreferences gson