Android SharedPreferences如何保存/存储对象

Android SharedPreferences如何保存/存储对象

我们需要在许多地方获取用户对象,其中包含许多字段。登录后,我想保存/存储这些用户对象。我们如何实现这种场景?

我不能这样储存:

SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("BusinessUnit", strBusinessUnit);


呼唤远方
浏览 341回答 3
3回答

慕无忌1623718

可以使用gson.jar将类对象存储到SharedPreferences..您可以从google-gson或者在Gradle文件中添加gson依赖项:implementation 'com.google.code.gson:gson:2.8.5'创建共享偏好:SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);拯救:MyObject myObject = new MyObject;//set variables of 'myObject', etc.Editor prefsEditor = mPrefs.edit(); Gson gson = new Gson();String json = gson.toJson(myObject);prefsEditor.putString("MyObject", json);prefsEditor.commit();检索:Gson gson = new Gson();String json = mPrefs.getString("MyObject", "");MyObject obj = gson.fromJson(json, MyObject.class);

白衣非少年

要添加到@MuhammadAamirALi的答案,可以使用gson保存和检索对象列表将用户定义对象的列表保存到SharedPreferencespublic&nbsp;static&nbsp;final&nbsp;String&nbsp;KEY_CONNECTIONS&nbsp;=&nbsp;"KEY_CONNECTIONS";SharedPreferences.Editor&nbsp;editor&nbsp;=&nbsp;getPreferences(MODE_PRIVATE).edit(); User&nbsp;entity&nbsp;=&nbsp;new&nbsp;User();//&nbsp;...&nbsp;set&nbsp;entity&nbsp;fieldsList<Connection>&nbsp;connections&nbsp;=&nbsp;entity.getConnections(); //&nbsp;convert&nbsp;java&nbsp;object&nbsp;to&nbsp;JSON&nbsp;format, //&nbsp;and&nbsp;returned&nbsp;as&nbsp;JSON&nbsp;formatted&nbsp;stringString&nbsp;connectionsJSONString&nbsp;=&nbsp;new&nbsp;Gson().toJson(connections); editor.putString(KEY_CONNECTIONS,&nbsp;connectionsJSONString);editor.commit();从SharedPreferences获取用户定义对象的列表String&nbsp;connectionsJSONString&nbsp;=&nbsp;getPreferences(MODE_PRIVATE).getString(KEY_CONNECTIONS,&nbsp;null); Type&nbsp;type&nbsp;=&nbsp;new&nbsp;TypeToken&nbsp;<&nbsp;List&nbsp;<&nbsp;Connection&nbsp;>>&nbsp;()&nbsp;{}.getType(); List&nbsp;<&nbsp;Connection&nbsp;>&nbsp;connections&nbsp;=&nbsp;new&nbsp;Gson().fromJson(connectionsJSONString,&nbsp;type);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android