简体   繁体   English

如何将抽象对象保存到共享首选项 Android

[英]How to save Abstract object to Shared Preferences Android

I want to save abstract object to shared preferences.I get data with String from Shared preferences and when bind it to an Abstract class, I get some errors like that "Caused by: java.lang.InstantiationException: Can't instantiate abstract class"我想将抽象对象保存到共享首选项。我从共享首选项中获取带有字符串的数据,并将其绑定到抽象类时,出现类似"Caused by: java.lang.InstantiationException: Can't instantiate abstract class"

How to get abstract object from shared preferences?如何从共享首选项中获取抽象对象?

Thanks谢谢

First of all, you cannot create an intance from an abstract class in java.首先,您不能从 java 中的抽象类创建实例。 You need to make something like this你需要做这样的事情

public MyRealClass extends MyAbstractClass{

}

Your IDE should now tell you that you need to implement the needed methods from the abstract class.您的 IDE 现在应该告诉您需要从抽象类中实现所需的方法。

You can now save the instance of MyRealClass to the SharedPreferences but only if you make it serializable or make the object to a JSON String.您现在可以将MyRealClass的实例保存到SharedPreferences,前提是您将其设置为可序列化或将对象设置为JSON字符串。 This can be done using libraries like GSON .这可以使用像GSON这样的库来完成。 It is not possible to save an object to the SharedPrefs directly.无法将对象直接保存到 SharedPrefs。

GSON will take your instance and transforms it into a string. GSON将获取您的实例并将其转换为字符串。 This string can be saved and later if you need the object again you can give the string to GSON and it will transform it back into the object.可以保存这个字符串,以后如果您再次需要该对象,您可以将该字符串提供给 GSON,它会将其转换回对象。 The used representation is called JSON, which is a standard format ( https://en.wikipedia.org/wiki/JSON )使用的表示形式称为 JSON,这是一种标准格式 ( https://en.wikipedia.org/wiki/JSON )

To save保存

Gson gson = new Gson();
String json = gson.toJson(myRealClassInstance);
prefsEditor.putString("myobj", json);
prefsEditor.commit();

for later loading稍后加载

Gson gson = new Gson();
String json = mPrefs.getString("myobj", "");
MyRealClass obj = gson.fromJson(json, MyRealClass.class);

For your Error: You can't create object of abstract class, you have to inherit abstract class to some class then only you can make an object to it.对于您的错误:您无法创建抽象类的对象,您必须将抽象类继承到某个类,然后才能为其创建对象。

Another one is, You can't store the object in shared preference.另一个是,您不能将对象存储在共享首选项中。 You can only store String, Integer, Boolean, Float, Long, and StringSet.您只能存储 String、Integer、Boolean、Float、Long 和 StringSet。

More info here.更多信息在这里。 https://developer.android.com/reference/android/content/SharedPreferences.html https://developer.android.com/reference/android/content/SharedPreferences.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM