以共享首选项存储和检索类对象
在Android中,我们可以将共享首选项中的类的对象存储起来,然后再检索对象?
如果有可能怎么做呢? 如果不可能的话,还有其他的可能性吗?
我知道序列化是一种选择,但我正在寻找使用共享偏好的可能性。
不可能。
您只能在SharedPrefences SharePreferences.Editor中存储简单的值
你需要保存什么课程?
是的,我们可以使用Gson来做到这一点
从GitHub下载工作代码
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
保存
Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson(); String json = gson.toJson(myObject); // myObject - instance of MyObject prefsEditor.putString("MyObject", json); prefsEditor.commit();
得到
Gson gson = new Gson(); String json = mPrefs.getString("MyObject", ""); MyObject obj = gson.fromJson(json, MyObject.class);
UPDATE1
GSON的最新版本可以从github.com/google/gson下载。
UPDATE2
如果您正在使用Gradle / Android Studio,只需在build.gradle
依赖项部分放入以下内容 –
compile 'com.google.code.gson:gson:2.6.2'
我们可以使用Outputstream将我们的Object输出到内部存储器。 并转换为字符串,然后优先保存。 例如:
mPrefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor ed = mPrefs.edit(); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutput; try { objectOutput = new ObjectOutputStream(arrayOutputStream); objectOutput.writeObject(object); byte[] data = arrayOutputStream.toByteArray(); objectOutput.close(); arrayOutputStream.close(); ByteArrayOutputStream out = new ByteArrayOutputStream(); Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT); b64.write(data); b64.close(); out.close(); ed.putString(key, new String(out.toByteArray())); ed.commit(); } catch (IOException e) { e.printStackTrace(); }
当我们需要从首选项中提取对象。 使用下面的代码
byte[] bytes = mPrefs.getString(indexName, "{}").getBytes(); if (bytes.length == 0) { return null; } ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes); Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT); ObjectInputStream in; in = new ObjectInputStream(base64InputStream); MyObject myObject = (MyObject) in.readObject();
我有同样的问题,这是我的解决方案:
我有类MyClass和ArrayList
public JSONObject getJSONObject() { JSONObject obj = new JSONObject(); try { obj.put("id", this.id); obj.put("name", this.name); } catch (JSONException e) { e.printStackTrace(); } return obj; }
那么这里是保存对象“ArrayList
SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0); SharedPreferences.Editor editor = mPrefs.edit(); Set set= new HashSet (); for (int i = 0; i < items.size(); i++) { set.add(items.get(i).getJSONObject().toString()); } editor.putStringSet("some_name", set); editor.commit();
这里是检索对象的方法:
public static ArrayList loadFromStorage() { SharedPreferences mPrefs = context.getSharedPreferences("some_name", 0); ArrayList items = new ArrayList (); Set set = mPrefs.getStringSet("some_name", null); if (set != null) { for (String s : set) { try { JSONObject jsonObject = new JSONObject(s); Long id = jsonObject.getLong("id")); String name = jsonObject.getString("name"); MyClass myclass = new MyClass(id, name); items.add(myclass); } catch (JSONException e) { e.printStackTrace(); } } return items; }
请注意,共享首选项中的StringSet从API 11开始可用。
使用Gson库:
dependencies { compile 'com.google.code.gson:gson:2.8.2' }
商店:
Gson gson = new Gson; //Your json response object value store in json object JSONObject jsonObject = response.getJSONObject(); //Convert json object to string String json = gson.toJson(jsonObject); //Store in the sharedpreference getPrefs().setUserJson(json);
检索:
String json = getPrefs().getUserJson();
即使在应用程序关闭donw之后或者在运行之后,是否还需要检索对象?
您可以将其存储到数据库中。
或者简单地创建一个自定义应用程序类
public class MyApplication extends Application { private static Object mMyObject; // static getter & setter ... } ... ...
然后从每一个活动做到:
((MyApplication) getApplication).getMyObject();
不是最好的方法,但它的工作原理。
使用这个对象 – > TinyDB – Android-Shared-Preferences-Turbo非常简单。 你可以像数组,整数,字符串列表等一样保存大部分常用对象
您可以使用复杂首选项Android – 通过Felipe Silvestre库来存储您的自定义对象。 基本上,它使用GSON机制来存储对象。
要将对象保存到prefs中:
User user = new User(); user.setName("Felipe"); user.setAge(22); user.setActive(true); ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences( this, "mypref", MODE_PRIVATE); complexPreferences.putObject("user", user); complexPreferences.commit();
并找回它:
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(this, "mypref", MODE_PRIVATE); User user = complexPreferences.getObject("user", User.class);
你可以使用GSON,使用Gradle Build.gradle:
implementation 'com.google.code.gson:gson:2.8.0'
然后在你的代码中,例如与Kotlin配对的字符串/布尔值:
val nestedData = HashMap() for (i in 0..29) { nestedData.put(i.toString(), true) } val gson = Gson() val jsonFromMap = gson.toJson(nestedData)
添加到SharedPrefs:
val sharedPrefEditor = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE).edit() sharedPrefEditor.putString("sig_types", jsonFromMap) sharedPrefEditor.apply()
现在检索数据:
val gson = Gson() val sharedPref: SharedPreferences = context.getSharedPreferences(_prefName, Context.MODE_PRIVATE) val json = sharedPref.getString("sig_types", "false") val type = object : TypeToken
没有办法在SharedPreferences中存储对象,我做的是创建一个公共类,把我需要的所有参数,创建setters和getters,我能够访问我的对象,
是的。您可以使用Sharedpreference存储和检索对象
- Kotlin:找不到符号类的片段或其他Android类
- 任务之间的Gradle依赖关系
- 如何安排频繁的后台工作,支持牛轧糖以上的支持?
- 使用getItemPosition(Object对象)在FragmentStatePagerAdapter中重新排序页面
- Android – Kotlin:异步乐趣中的返回值
- 经常调用回调方法来将事件转发到Observable?
- 使用Kotlin将图像从ImageView传递给Android中的另一个Activity
- 强制使用API 21和22中的AnimatedVectorDrawableCompat来使用registerAnimationCallback
- Android ProgessBar在加载WebView时