I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. 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. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?
当前回答
对于String, int, boolean,最好的选择是sharedPreferences。
如果你想存储数组列表或任何复杂的数据。最好的选择是Paper library。
添加依赖关系
implementation 'io.paperdb:paperdb:2.6'
初始化文件
应该在Application.onCreate()中初始化一次:
Paper.init(context);
Save
List<Person> contacts = ...
Paper.book().write("contacts", contacts);
加载数据
如果对象在存储中不存在,请使用默认值。
List<Person> contacts = Paper.book().read("contacts", new ArrayList<>());
给你。
https://github.com/pilgr/Paper
其他回答
这应该可以工作:
public void setSections (Context c, List<Section> sectionList){
this.sectionList = sectionList;
Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
String sectionListString = new Gson().toJson(sectionList,sectionListType);
SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
editor.apply();
}
他们,要抓住它才:
public List<Section> getSections(Context c){
if(this.sectionList == null){
String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);
if(sSections == null){
return new ArrayList<>();
}
Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
try {
this.sectionList = new Gson().fromJson(sSections, sectionListType);
if(this.sectionList == null){
return new ArrayList<>();
}
}catch (JsonSyntaxException ex){
return new ArrayList<>();
}catch (JsonParseException exc){
return new ArrayList<>();
}
}
return this.sectionList;
}
这对我很管用。
您可以将其转换为JSON字符串,并将字符串存储在SharedPreferences中。
为什么不把数组列表放在应用程序类上呢?它只有在应用被杀死时才会被销毁,所以,只要应用可用,它就会一直存在。
你可以从FacebookSDK的SharedPreferencesTokenCache类中引用serializeKey()和deserializeKey()函数。它将supportedType转换为JSON对象,并将JSON字符串存储为SharedPreferences。你可以从这里下载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);
}
}
/**
* Save and get ArrayList in SharedPreference
*/
JAVA:
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply();
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
科特林
fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val editor: Editor = prefs.edit()
val gson = Gson()
val json: String = gson.toJson(list)
editor.putString(key, json)
editor.apply()
}
fun getArrayList(key: String?): java.util.ArrayList<String?>? {
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
val gson = Gson()
val json: String = prefs.getString(key, null)
val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
return gson.fromJson(json, type)
}
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?