您可以从FacebookSDK的SharedPreferencesTokenCache类中引用serializeKey()和deserializeKey()函数 . It converts the supportedType into the JSON object and store the JSON string into SharedPreferences . 你可以从here下载SDK
private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor)
throws JSONException {
Object value = bundle.get(key);
if (value == null) {
// Cannot serialize null values.
return;
}
String supportedType = null;
JSONArray jsonArray = null;
JSONObject json = new JSONObject();
if (value instanceof Byte) {
supportedType = TYPE_BYTE;
json.put(JSON_VALUE, ((Byte)value).intValue());
} else if (value instanceof Short) {
supportedType = TYPE_SHORT;
json.put(JSON_VALUE, ((Short)value).intValue());
} else if (value instanceof Integer) {
supportedType = TYPE_INTEGER;
json.put(JSON_VALUE, ((Integer)value).intValue());
} else if (value instanceof Long) {
supportedType = TYPE_LONG;
json.put(JSON_VALUE, ((Long)value).longValue());
} else if (value instanceof Float) {
supportedType = TYPE_FLOAT;
json.put(JSON_VALUE, ((Float)value).doubleValue());
} else if (value instanceof Double) {
supportedType = TYPE_DOUBLE;
json.put(JSON_VALUE, ((Double)value).doubleValue());
} else if (value instanceof Boolean) {
supportedType = TYPE_BOOLEAN;
json.put(JSON_VALUE, ((Boolean)value).booleanValue());
} else if (value instanceof Character) {
supportedType = TYPE_CHAR;
json.put(JSON_VALUE, value.toString());
} else if (value instanceof String) {
supportedType = TYPE_STRING;
json.put(JSON_VALUE, (String)value);
} else {
// Optimistically create a JSONArray. If not an array type, we can null
// it out later
jsonArray = new JSONArray();
if (value instanceof byte[]) {
supportedType = TYPE_BYTE_ARRAY;
for (byte v : (byte[])value) {
jsonArray.put((int)v);
}
} else if (value instanceof short[]) {
supportedType = TYPE_SHORT_ARRAY;
for (short v : (short[])value) {
jsonArray.put((int)v);
}
} else if (value instanceof int[]) {
supportedType = TYPE_INTEGER_ARRAY;
for (int v : (int[])value) {
jsonArray.put(v);
}
} else if (value instanceof long[]) {
supportedType = TYPE_LONG_ARRAY;
for (long v : (long[])value) {
jsonArray.put(v);
}
} else if (value instanceof float[]) {
supportedType = TYPE_FLOAT_ARRAY;
for (float v : (float[])value) {
jsonArray.put((double)v);
}
} else if (value instanceof double[]) {
supportedType = TYPE_DOUBLE_ARRAY;
for (double v : (double[])value) {
jsonArray.put(v);
}
} else if (value instanceof boolean[]) {
supportedType = TYPE_BOOLEAN_ARRAY;
for (boolean v : (boolean[])value) {
jsonArray.put(v);
}
} else if (value instanceof char[]) {
supportedType = TYPE_CHAR_ARRAY;
for (char v : (char[])value) {
jsonArray.put(String.valueOf(v));
}
} else if (value instanceof List<?>) {
supportedType = TYPE_STRING_LIST;
@SuppressWarnings("unchecked")
List<String> stringList = (List<String>)value;
for (String v : stringList) {
jsonArray.put((v == null) ? JSONObject.NULL : v);
}
} else {
// Unsupported type. Clear out the array as a precaution even though
// it is redundant with the null supportedType.
jsonArray = null;
}
}
if (supportedType != null) {
json.put(JSON_VALUE_TYPE, supportedType);
if (jsonArray != null) {
// If we have an array, it has already been converted to JSON. So use
// that instead.
json.putOpt(JSON_VALUE, jsonArray);
}
String jsonString = json.toString();
editor.putString(key, jsonString);
}
}
private void deserializeKey(String key, Bundle bundle)
throws JSONException {
String jsonString = cache.getString(key, "{}");
JSONObject json = new JSONObject(jsonString);
String valueType = json.getString(JSON_VALUE_TYPE);
if (valueType.equals(TYPE_BOOLEAN)) {
bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
} else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
boolean[] array = new boolean[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getBoolean(i);
}
bundle.putBooleanArray(key, array);
} else if (valueType.equals(TYPE_BYTE)) {
bundle.putByte(key, (byte)json.getInt(JSON_VALUE));
} else if (valueType.equals(TYPE_BYTE_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
byte[] array = new byte[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = (byte)jsonArray.getInt(i);
}
bundle.putByteArray(key, array);
} else if (valueType.equals(TYPE_SHORT)) {
bundle.putShort(key, (short)json.getInt(JSON_VALUE));
} else if (valueType.equals(TYPE_SHORT_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
short[] array = new short[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = (short)jsonArray.getInt(i);
}
bundle.putShortArray(key, array);
} else if (valueType.equals(TYPE_INTEGER)) {
bundle.putInt(key, json.getInt(JSON_VALUE));
} else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
int[] array = new int[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getInt(i);
}
bundle.putIntArray(key, array);
} else if (valueType.equals(TYPE_LONG)) {
bundle.putLong(key, json.getLong(JSON_VALUE));
} else if (valueType.equals(TYPE_LONG_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
long[] array = new long[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getLong(i);
}
bundle.putLongArray(key, array);
} else if (valueType.equals(TYPE_FLOAT)) {
bundle.putFloat(key, (float)json.getDouble(JSON_VALUE));
} else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
float[] array = new float[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = (float)jsonArray.getDouble(i);
}
bundle.putFloatArray(key, array);
} else if (valueType.equals(TYPE_DOUBLE)) {
bundle.putDouble(key, json.getDouble(JSON_VALUE));
} else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
double[] array = new double[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
array[i] = jsonArray.getDouble(i);
}
bundle.putDoubleArray(key, array);
} else if (valueType.equals(TYPE_CHAR)) {
String charString = json.getString(JSON_VALUE);
if (charString != null && charString.length() == 1) {
bundle.putChar(key, charString.charAt(0));
}
} else if (valueType.equals(TYPE_CHAR_ARRAY)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
char[] array = new char[jsonArray.length()];
for (int i = 0; i < array.length; i++) {
String charString = jsonArray.getString(i);
if (charString != null && charString.length() == 1) {
array[i] = charString.charAt(0);
}
}
bundle.putCharArray(key, array);
} else if (valueType.equals(TYPE_STRING)) {
bundle.putString(key, json.getString(JSON_VALUE));
} else if (valueType.equals(TYPE_STRING_LIST)) {
JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
int numStrings = jsonArray.length();
ArrayList<String> stringList = new ArrayList<String>(numStrings);
for (int i = 0; i < numStrings; i++) {
Object jsonStringValue = jsonArray.get(i);
stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String)jsonStringValue);
}
bundle.putStringArrayList(key, stringList);
}
}
2
当应用程序被真正杀死时,为什么要销毁't you stick your arraylist on an Application class? It only get',因此,只要应用程序可用,它就会一直存在 .
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) {
SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
editor.putInt(pKey + "size", pData.size());
editor.commit();
for (int i = 0; i < pData.size(); i++) {
SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
editor1.putString(pKey + i, (pData.get(i)));
editor1.commit();
}
}
以及从共享首选项>>获取字符串列表
public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) {
int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
List<String> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, ""));
}
return list;
}
// shared preferences
private SharedPreferences preferences;
private SharedPreferences.Editor nsuserdefaults;
// setup persistent data
preferences = this.getSharedPreferences("MyPreferences", MainActivity.MODE_PRIVATE);
nsuserdefaults = preferences.edit();
arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
//Retrieve followers from sharedPreferences
Set<String> set = preferences.getStringSet("following", null);
if (set == null) {
// lazy instantiate array
arrayOfMemberUrlsUserIsFollowing = new ArrayList<String>();
} else {
// there is data from previous run
arrayOfMemberUrlsUserIsFollowing = new ArrayList<>(set);
}
// convert arraylist to set, and save arrayOfMemberUrlsUserIsFollowing to nsuserdefaults
Set<String> set = new HashSet<String>();
set.addAll(arrayOfMemberUrlsUserIsFollowing);
nsuserdefaults.putStringSet("following", set);
nsuserdefaults.commit();
0
//Set the values
intent.putParcelableArrayListExtra("key",collection);
//Retrieve the values
ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");
381
别忘了实施序列化:
Class dataBean implements Serializable{
public String name;
}
ArrayList<dataBean> dataBeanArrayList = new ArrayList();
fun SharedPreferences.Editor.putIntegerArrayList(key: String, list: ArrayList<Int>?): SharedPreferences.Editor {
putString(key, list?.joinToString(",") ?: "")
return this
}
fun SharedPreferences.getIntegerArrayList(key: String, defValue: ArrayList<Int>?): ArrayList<Int>? {
val value = getString(key, null)
if (value.isNullOrBlank())
return defValue
return value.split(",").map { it.toInt() }.toArrayList()
}
57
我的utils类保存列表为 SharedPreferences
public class SharedPrefApi {
private SharedPreferences sharedPreferences;
private Gson gson;
public SharedPrefApi(Context context, Gson gson) {
this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.gson = gson;
}
...
public <T> void putList(String key, List<T> list) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, gson.toJson(list));
editor.apply();
}
public <T> List<T> getList(String key, Class<T> clazz) {
Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
return gson.fromJson(getString(key, null), typeOfT);
}
}
运用
// for save
sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);
// for retrieve
List<User> userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);
public class MyApp extends Application {
//Pardon me for using global ;)
private ArrayList<CustomObject> globalArray;
public void setGlobalArrayOfCustomObjects(ArrayList<CustomObject> newArray){
globalArray = newArray;
}
public ArrayList<CustomObject> getGlobalArrayOfCustomObjects(){
return globalArray;
}
}
30 回答
您可以从FacebookSDK的SharedPreferencesTokenCache类中引用serializeKey()和deserializeKey()函数 . It converts the supportedType into the JSON object and store the JSON string into SharedPreferences . 你可以从here下载SDK
当应用程序被真正杀死时,为什么要销毁't you stick your arraylist on an Application class? It only get',因此,只要应用程序可用,它就会一直存在 .
在API 11之后
SharedPreferences Editor
接受Sets
. 您可以将列表转换为HashSet
或类似的东西并将其存储 . 当你回读它时,把它转换成ArrayList
,如果需要你可以对它进行排序,你就可以了 .您也可以序列化
ArrayList
,然后将其保存/读取到SharedPreferences
. 以下是解决方案:EDIT:
好的,下面是将
ArrayList
作为序列化对象保存到SharedPreferences
的解决方案,然后从SharedPreferences中读取它 .因为API仅支持在SharedPreferences中存储和检索字符串(在API 11之后,它更简单),我们必须将具有任务列表的ArrayList对象序列化和反序列化为字符串 .
在TaskManagerApplication类的
addTask()
方法中,我们必须获取共享首选项的实例,然后使用putString()
方法存储序列化的ArrayList:同样,我们必须从
onCreate()
方法中的首选项中检索任务列表:你可以从Apache Pig项目获得
ObjectSerializer
类ObjectSerializer.java使用这个对象 - > TinyDB--Android-Shared-Preferences-Turbo很简单 .
放在
要得到
在_849778中保存
Array
:从
SharedPreferences
加载Array
数据您可以将其转换为
JSON String
并将字符串存储在SharedPreferences
中 .正如@nirav所说,最好的解决方案是使用Gson实用程序类将它作为json文本存储在sharedPrefernces中 . 下面的示例代码:
嘿朋友我没有使用
Gson
库就得到了上述问题的解决方案 . 在这里我发布源代码 .1.变量声明,即
2.可变初始化即
3.使用
packagesharedPreferences()
将值存储到sharedPreference:4.使用
retriveSharedValue()
传递sharedPreference的值:我希望它对你有帮助...
Android SharedPreferances允许您将内存类型(自API11以来可用的布尔,浮点数,整数,长整数,字符串和字符串集)保存为内存中的xml文件 .
任何解决方案的关键思想是将数据转换为其中一种原始类型 .
我个人喜欢将我的列表转换为json格式,然后将其保存为SharedPreferences值中的String .
要使用我的解决方案,您必须添加Google Gson lib .
在gradle中只需添加以下依赖项(请使用google的最新版本):
保存数据(HttpParam是你的对象):
检索数据(HttpParam是你的对象):
您还可以将arraylist转换为String并优先保存
您可以使用
convertToString
方法将Arraylist转换为字符串后保存它并检索字符串并使用convertToArray
将其转换为数组在API 11之后,您可以将set直接保存到SharedPreferences尽管!!! :)
最好的方法是使用GSON转换为JSOn字符串并将此字符串保存到SharedPreference . 我也用这种方式缓存响应 .
我已经阅读了上面的所有答案 . 这一切都是正确的,但我找到了一个更简单的解决方案如下:
}
这里
Constants.APP_PREFS
是要打开的文件的名称;不能包含路径分隔符 .我能找到的最好的方法是制作一个2D数组键,并将数组的自定义项放在二维数组键中,然后在启动时通过2D arra检索它 . 我不喜欢使用字符串集的想法,因为大多数Android用户仍然使用Gingerbread并且使用字符串集需要使用蜂窝 .
示例代码:这里ditor是共享的pref编辑器,rowitem是我的自定义对象 .
下面的代码是接受的答案,还有一些新人(我)的行,例如 . 展示了如何将set类型对象转换回arrayList,以及有关'.putStringSet'和'.getStringSet'之前的内容的其他指导 . (谢谢你)
别忘了实施序列化:
https://stackoverflow.com/a/7635154/4639974
此方法用于存储/保存数组列表: -
此方法用于检索数组列表: -
您可以将其转换为
Map
对象来存储它,然后在检索SharedPreferences
时将值更改回ArrayList .您可以使用序列化或Gson库将列表转换为字符串,反之亦然,然后在首选项中保存字符串 .
使用谷歌的Gson库:
使用Java序列化:
使用此自定义类:
如何使用:
You can save String and custom array list using Gson library.
=>First you need to create function to save array list to SharedPreferences.
=> You need to create function to get array list from SharedPreferences.
=> How to call save and retrieve array list function.
=>不要忘记在app level build.gradle中添加gson库 .
实现'com.google.code.gson:gson:2.8.2'
还有Kotlin:
我的utils类保存列表为
SharedPreferences
运用
.
Full code of my utils //使用活动代码中的示例进行检查
所有上述答案都是正确的 . :)我自己在我的情况中使用其中一个 . 然而,当我读到这个问题时,我发现OP实际上是在讨论与本文 Headers 不同的场景,如果我没有弄错的话 .
"I need the array to stick around even if the user leaves the activity and then wants to come back at a later time"
他实际上希望存储数据直到应用程序打开,而不管用户在应用程序中更改屏幕 .
"however I don't need the array available after the application has been closed completely"
但是一旦关闭应用程序,就不应该保留数据 . 因此我觉得使用
SharedPreferences
并不是最佳方法 .可以为此要求做的是创建一个扩展
Application
类的类 .使用setter和getter,可以使用Application从任何地方访问ArrayList . 最好的部分是应用程序关闭后,我们不必担心存储的数据 . :)
在SharedPreferences中使用getStringSet和putStringSet非常简单,但在我的情况下,我必须复制Set对象才能向Set中添加任何内容 . 否则,如果我的应用程序强制关闭,则不会保存该设置 . 可能是因为以下API中的注释 . (如果应用程序被后退按钮关闭,它保存了) .
使用Kotlin,对于简单的数组和列表,您可以执行以下操作:
然后轻松访问首选项:
我使用相同的方式保存和检索字符串,但在这里使用arrayList我使用HashSet作为中介
要将arrayList保存到SharedPreferences,我们使用HashSet:
1-我们创建SharedPreferences变量(在数组发生更改的位置)
2 - 我们将arrayList转换为HashSet
3 - 然后我们把stringSet和apply
4 - 在HashSet中使用getStringSet并重新创建ArrayList以设置HashSet .
公共类MainActivity扩展AppCompatActivity {ArrayList arrayList = new ArrayList <>();
这应该工作:
他们,只是 grab 它:
这个对我有用 .