在使用应用程序对象遇到困难之后,我有了一个(新的?)想法使用 GSON 库和 Sharedpreferences 在 Activity 之间交换数据。这有一个很大的好处,即如果应用程序关闭,对象不会被破坏。
我想知道你是怎么想的
- 安全
- 表现
- 应用稳定性
这是我的工作。首先创建一个MyExchanger类
public class MyExchanger {
//store your variables here
String name;
List<Vokabel> vokabeliste;
//put your GETTERS und SETTERS HERE (or make them public)
}
然后是魔法发生的助手类
public class ExchangerUtils {
Context context;
SharedPreferences prefs;
SharedPreferences.Editor editor;
Resources res;
Gson gson;
Type type ;
public ExchangerUtils(Context context) {
this.context = context;
prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
res = context.getResources();
type = new TypeToken<MyExchanger>() {
}.getType();
}
public void updateExchanger(MyExchanger exchanger) {
gson = new Gson();
String exchangerjson = gson.toJson(exchanger, type);
editor = prefs.edit();
editor.putString(res.getString(R.string.key_exchanger), exchangerjson);
editor.commit();
}
public Exchanger getExchanger(){
String exchangerjson = prefs.getString(res.getString(R.string.key_exchanger), null);
Gson gson = new Gson();
if(exchangerjson!=null){
My Exchanger exchanger = gson.fromJson(exchangerjson, type);
return exchanger;
}
return new MyExchanger();
}
}
实现可能看起来像这样
//Somewhere in the activity
ExchangerUtils utils = new ExchangerUtils(this);
MyExchanger exchanger = utils.getExchanger();
exchanger.setName("a name");
utils.update(exchanger);
我已经在我的两个应用程序中对其进行了测试,它运行良好,也适用于旧手机和大量对象(>100)。
实现中唯一的麻烦是我必须更新对象。知道如何在没有这种方法的情况下做到这一点吗?
我有任何改进建议,请随时发布。
最佳答案
我创建了一个库,它可以按照您描述的方式很容易地保存数据: DroidPrefs
您可以很容易地保存和加载值,但您不必担心带有 TypeTokens 的辅助类等等。
来自这个 POJO
public class Animal
{
private String mName;
private String mBreed;
private int mLegs;
public Animal() {
mName = "";
mBreed = "";
mLegs = 0;
}
public Animal(String name, String breed, int legs)
{
mName = name;
mBreed = breed;
mLegs = legs;
}
}
保存对象
Animal newAnimal = new Animal("Gitty", "Octocat", 8);
DroidPrefs.instance(context).put("animal", newAnimal).apply();
加载对象
Animal newAnimal = DroidPrefs.instance(context).get("animal", Animal.class);
如果对象之前没有序列化,将使用默认构造函数创建一个新对象。
关于android - 在 Sharedpreferences 中使用 GSON 存储对象。你怎么认为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15840772/