时间:2011-08-14 15:46:41

标签: android arraylist sharedpreferences

我有ArrayList个自定义对象。每个自定义对象都包含各种字符串和数字。即使用户离开活动然后想要稍后返回,我也需要数组保持不变,但是在应用程序完全关闭后我不需要数组可用。我使用SharedPreferences以这种方式保存了很多其他对象,但我无法弄清楚如何以这种方式保存整个数组。这可能吗?也许SharedPreferences不是解决这个问题的方法吗?有更简单的方法吗?

37 个答案:

答案 0 :(得分:394)

在API 11之后,SharedPreferences Editor接受Sets。您可以将列表转换为HashSet或类似的内容并将其存储起来。回读后,将其转换为ArrayList,如果需要可以对其进行排序,你就可以了。

//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();

您还可以序列化ArrayList,然后将其保存/读取到SharedPreferences。以下是解决方案:

修改
好的,下面的解决方案是将ArrayList保存为序列化对象SharedPreferences,然后从SharedPreferences中读取它。

因为API仅支持在SharedPreferences中存储和检索字符串(在API 11之后,它更简单),我们必须将具有任务列表的ArrayList对象序列化和反序列化为字符串。

在TaskManagerApplication类的addTask()方法中,我们必须获取共享首选项的实例,然后使用putString()方法存储序列化的ArrayList:

public void addTask(Task t) {
  if (null == currentTasks) {
    currentTasks = new ArrayList<task>();
  }
  currentTasks.add(t);

  // save the task list to preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
  Editor editor = prefs.edit();
  try {
    editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
  } catch (IOException e) {
    e.printStackTrace();
  }
  editor.commit();
}

同样,我们必须从onCreate()方法中的首选项中检索任务列表:

public void onCreate() {
  super.onCreate();
  if (null == currentTasks) {
    currentTasks = new ArrayList<task>();
  }

  // load tasks from preference
  SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

  try {
    currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
  } catch (IOException e) {
    e.printStackTrace();
  } catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
}

您可以从Apache Pig项目ObjectSerializer.java

获得ObjectSerializer课程

答案 1 :(得分:98)

使用此对象 - &gt; TinyDB--Android-Shared-Preferences-Turbo非常简单。

TinyDB tinydb = new TinyDB(context);

tinydb.putList("MyUsers", mUsersArray);

获取

tinydb.getList("MyUsers");

<强>更新

可以在此处找到一些有用的示例和问题排查:Android Shared Preference TinyDB putListObject frunction

答案 2 :(得分:92)

Array中保存SharedPreferences

public static boolean saveArray()
{
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor mEdit1 = sp.edit();
    /* sKey is an array */
    mEdit1.putInt("Status_size", sKey.size());  

    for(int i=0;i<sKey.size();i++)  
    {
        mEdit1.remove("Status_" + i);
        mEdit1.putString("Status_" + i, sKey.get(i));  
    }

    return mEdit1.commit();     
}

Array

加载SharedPreferences数据
public static void loadArray(Context mContext)
{  
    SharedPreferences mSharedPreference1 =   PreferenceManager.getDefaultSharedPreferences(mContext);
    sKey.clear();
    int size = mSharedPreference1.getInt("Status_size", 0);  

    for(int i=0;i<size;i++) 
    {
     sKey.add(mSharedPreference1.getString("Status_" + i, null));
    }

}

答案 3 :(得分:58)

您可以将其转换为JSON String并将字符串存储在SharedPreferences

答案 4 :(得分:42)

正如@nirav所说,最好的解决方案是使用Gson实用程序类将它作为json文本存储在sharedPrefernces中。下面的示例代码:

//Retrieve the values
Gson gson = new Gson();
String jsonText = Prefs.getString("key", null);
String[] text = gson.fromJson(jsonText, String[].class);  //EDIT: gso to gson


//Set the values
Gson gson = new Gson();
List<String> textList = new ArrayList<String>();
textList.addAll(data);
String jsonText = gson.toJson(textList);
prefsEditor.putString("key", jsonText);
prefsEditor.apply();

答案 5 :(得分:21)

嘿朋友我在不使用Gson库的情况下得到了上述问题的解决方案。在这里,我发布了源代码。

1.变量声明即

  SharedPreferences shared;
  ArrayList<String> arrPackage;

2.可变初始化即

 shared = getSharedPreferences("App_settings", MODE_PRIVATE);
 // add values for your ArrayList any where...
 arrPackage = new ArrayList<>();

3.使用packagesharedPreferences()存储sharedPreference的值:

 private void packagesharedPreferences() {
   SharedPreferences.Editor editor = shared.edit();
   Set<String> set = new HashSet<String>();
   set.addAll(arrPackage);
   editor.putStringSet("DATE_LIST", set);
   editor.apply();
   Log.d("storesharedPreferences",""+set);
 }

4.使用retriveSharedValue()

传递sharedPreference的值
 private void retriveSharedValue() {
   Set<String> set = shared.getStringSet("DATE_LIST", null);
   arrPackage.addAll(set);
   Log.d("retrivesharedPreferences",""+set);
 }

我希望它对你有帮助......

答案 6 :(得分:13)

Android SharedPreferances允许您将内存类型(自API11以来可用的布尔,Float,Int,Long,String和StringSet)保存为内存中的xml文件。

任何解决方案的关键思想都是将数据转换为其中一种原始类型。

我个人喜欢将我的列表转换为json格式,然后将其保存为SharedPreferences值中的String。

要使用我的解决方案,您必须添加Google Gson lib。

在gradle中只需添加以下依赖项(请使用google的最新版本):

compile 'com.google.code.gson:gson:2.6.2'

保存数据(HttpParam是您的对象):

List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);

editor.apply();

检索数据(HttpParam是你的对象):

SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, ""); 

List<HttpParam> httpParamList =  
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
            }.getType());

答案 7 :(得分:8)

您还可以将arraylist转换为String并将其保存在首选项

private String convertToString(ArrayList<String> list) {

            StringBuilder sb = new StringBuilder();
            String delim = "";
            for (String s : list)
            {
                sb.append(delim);
                sb.append(s);;
                delim = ",";
            }
            return sb.toString();
        }

private ArrayList<String> convertToArray(String string) {

            ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
            return list;
        }

您可以使用convertToString方法将Arraylist转换为字符串后保存它,并检索字符串并使用convertToArray将其转换为数组

在API 11之后,你可以直接将集合保存到SharedPreferences! :)

答案 8 :(得分:6)

这是您的理想解决方案。尝试一下,

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();     // This line is IMPORTANT !!!
}

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);
}

答案 9 :(得分:5)

我已阅读上述所有答案。这一切都是正确的,但我找到了一个更简单的解决方案如下:

  1. 在共享首选项&gt;&gt;

    中保存字符串列表
    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();
    }
    

    }

  2. 以及从共享首选项&gt;&gt;

    获取字符串列表
    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;
    }
    
  3. 此处Constants.APP_PREFS是要打开的文件的名称;不能包含路径分隔符。

答案 10 :(得分:4)

最好的方法是使用GSON转换为JSOn字符串并将此字符串保存到SharedPreference。 我也用这种方式缓存响应。

答案 11 :(得分:3)

您可以从FacebookSDK的SharedPreferencesTokenCache类中引用serializeKey()和deserializeKey()函数。 它将supportedType转换为JSON对象,并将JSON字符串存储到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);
    }
}

答案 12 :(得分:2)

我能找到的最好方法是制作一个2D数组键,并将数组的自定义项放入二维数组键中,然后在启动时通过2D arra检索它。 我不喜欢使用字符串集的想法,因为大多数Android用户仍然使用姜饼,使用字符串集需要蜂窝。

示例代码: 这里的ditor是共享的pref编辑器,rowitem是我的自定义对象。

editor.putString(genrealfeedkey[j][1], Rowitemslist.get(j).getname());
        editor.putString(genrealfeedkey[j][2], Rowitemslist.get(j).getdescription());
        editor.putString(genrealfeedkey[j][3], Rowitemslist.get(j).getlink());
        editor.putString(genrealfeedkey[j][4], Rowitemslist.get(j).getid());
        editor.putString(genrealfeedkey[j][5], Rowitemslist.get(j).getmessage());

答案 13 :(得分:2)

此方法用于存储/保存数组列表:-

 public static void saveSharedPreferencesLogList(Context context, List<String> collageList) {
            SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = mPrefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(collageList);
            prefsEditor.putString("myJson", json);
            prefsEditor.commit();
        }

此方法用于检索数组列表:-

public static List<String> loadSharedPreferencesLogList(Context context) {
        List<String> savedCollage = new ArrayList<String>();
        SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = mPrefs.getString("myJson", "");
        if (json.isEmpty()) {
            savedCollage = new ArrayList<String>();
        } else {
            Type type = new TypeToken<List<String>>() {
            }.getType();
            savedCollage = gson.fromJson(json, type);
        }

        return savedCollage;
    }

答案 14 :(得分:2)

不要忘记实现Serializable:

Class dataBean implements Serializable{
 public String name;
}
ArrayList<dataBean> dataBeanArrayList = new ArrayList();

https://stackoverflow.com/a/7635154/4639974

答案 15 :(得分:2)

//Set the values
intent.putParcelableArrayListExtra("key",collection);

//Retrieve the values
ArrayList<OnlineMember> onlineMembers = data.getParcelableArrayListExtra("key");

答案 16 :(得分:2)

以下代码是接受的答案,为新人(我)提供了更多行,例如。展示了如何将set类型对象转换回arrayList,以及有关之前的内容的更多指导&#39; .putStringSet&#39;和&#39; .getStringSet&#39;。 (谢谢evilone)

// 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();

答案 17 :(得分:2)

为什么不把你的arraylist粘贴在Application类上?当应用真的被杀时,它才会被破坏,因此,只要应用程序可用,它就会一直存在。

答案 18 :(得分:1)

/**
 *     Save and get ArrayList in SharedPreference
 */

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();     // This line is IMPORTANT !!!
}

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);
}

答案 19 :(得分:1)

对于String,int,boolean,最好的选择是sharedPreferences。

如果要存储ArrayList或任何复杂数据。最好的选择是Paper库。

添加依赖项

implementation 'io.paperdb:paperdb:2.6'

初始化纸张

应该在Application.onCreate()中初始化一次:

Paper.init(context);

保存

List<Person> contacts = ...
Paper.book().write("contacts", contacts);

加载数据

如果存储中不存在对象,请使用默认值。

List<Person> = Paper.book().read("contacts", new ArrayList<>());

你在这里。

https://github.com/pilgr/Paper

答案 20 :(得分:1)

我的utils类,用于将列表保存到val mapper = ObjectMapper() val module = SimpleModule().addDeserializer(Error::class.java, ErrorDeserializer()) mapper.registerModule(module) val error = mapper.readValue<Error>("json content", Error::class.java) when (error) { is Error.SingleError -> { // error.errorMessage } is Error.MultiError -> { // error.errorMessage } }

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);
    }
}


Full code of my utils //使用活动代码中的示例进行检查

答案 21 :(得分:1)

使用此自定义类:

public class SharedPreferencesUtil {

    public static void pushStringList(SharedPreferences sharedPref, 
                                      List<String> list, String uniqueListName) {

        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(uniqueListName + "_size", list.size());

        for (int i = 0; i < list.size(); i++) {
            editor.remove(uniqueListName + i);
            editor.putString(uniqueListName + i, list.get(i));
        }
        editor.apply();
    }

    public static List<String> pullStringList(SharedPreferences sharedPref, 
                                              String uniqueListName) {

        List<String> result = new ArrayList<>();
        int size = sharedPref.getInt(uniqueListName + "_size", 0);

        for (int i = 0; i < size; i++) {
            result.add(sharedPref.getString(uniqueListName + i, null));
        }
        return result;
    }
}

使用方法:

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferencesUtil.pushStringList(sharedPref, list, getString(R.string.list_name));
List<String> list = SharedPreferencesUtil.pullStringList(sharedPref, getString(R.string.list_name));

答案 22 :(得分:1)

我使用了相同的方式来保存和检索字符串,但在这里使用arrayList我已经使用HashSet作为调解器

要将arrayList保存到SharedPreferences,我们使用HashSet:

1-我们创建SharedPreferences变量(在数组发生更改的地方)

2 - 我们将arrayList转换为HashSet

3 - 然后我们把stringSet和apply

4 - 在HashSet中使用getStringSet并重新创建ArrayList以设置HashSet。

public class MainActivity extends AppCompatActivity {
    ArrayList<String> arrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences prefs = this.getSharedPreferences("com.example.nec.myapplication", Context.MODE_PRIVATE);

        HashSet<String> set = new HashSet(arrayList);
        prefs.edit().putStringSet("names", set).apply();


        set = (HashSet<String>) prefs.getStringSet("names", null);
        arrayList = new ArrayList(set);

        Log.i("array list", arrayList.toString());
    }
}

答案 23 :(得分:1)

还有Kotlin:

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()
}

答案 24 :(得分:1)

您可以使用Gson库保存字符串和自定义数组列表。

=&gt;首先,您需要创建将数组列表保存到SharedPreferences的函数。

public void saveListInLocal(ArrayList<String> list, String key) {

        SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!

    }

<强> =&GT;您需要创建函数以从SharedPreferences获取数组列表。

public ArrayList<String> getListFromLocal(String key)
{
    SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);

}

<强> =&GT;如何调用保存和检索数组列表功能。

ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());

=&GT;不要忘记在app level build.gradle中添加gson库。

实施'com.google.code.gson:gson:2.8.2'

答案 25 :(得分:1)

您可以使用序列化或Gson库将列表转换为字符串,反之亦然,然后在首选项中保存字符串。

使用谷歌的Gson库:

//Converting list to string
new Gson().toJson(list);

//Converting string to list
new Gson().fromJson(listString, CustomObjectsList.class);

使用Java序列化:

//Converting list to string
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(list);
oos.flush();
String string = Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
oos.close();
bos.close();
return string;

//Converting string to list
byte[] bytesArray = Base64.decode(familiarVisitsString, Base64.DEFAULT);
ByteArrayInputStream bis = new ByteArrayInputStream(bytesArray);
ObjectInputStream ois = new ObjectInputStream(bis);
Object clone = ois.readObject();
ois.close();
bis.close();
return (CustomObjectsList) clone;

答案 26 :(得分:1)

您可以将其转换为Map对象来存储它,然后在检索SharedPreferences时将值更改回ArrayList。

答案 27 :(得分:0)

使用Kotlin,对于简单的数组和列表,您可以执行以下操作:

class MyPrefs(context: Context) {
    val prefs = context.getSharedPreferences("x.y.z.PREFS_FILENAME", 0)
    var listOfFloats: List<Float>
        get() = prefs.getString("listOfFloats", "").split(",").map { it.toFloat() }
        set(value) = prefs.edit().putString("listOfFloats", value.joinToString(",")).apply()
}

然后轻松访问首选项:

MyPrefs(context).listOfFloats = ....
val list = MyPrefs(context).listOfFloats

答案 28 :(得分:0)

Saving and retrieving the ArrayList From SharedPreference
 public static void addToPreference(String id,Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
        ArrayList<String> list = getListFromPreference(context);
        if (!list.contains(id)) {
            list.add(id);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            Set<String> set = new HashSet<>();
            set.addAll(list);
            edit.putStringSet(Constant.LIST, set);
            edit.commit();

        }
    }
    public static ArrayList<String> getListFromPreference(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet(Constant.LIST, null);
        ArrayList<String> list = new ArrayList<>();
        if (set != null) {
            list = new ArrayList<>(set);
        }
        return list;
    }

答案 29 :(得分:0)

这应该有效:

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;
}

对我有用。

答案 30 :(得分:0)

SharedPreferences中使用getStringSet和putStringSet非常简单,但在我的情况下,我必须复制Set对象才能向Set添加任何内容。否则,如果我的应用程序强行关闭,则不会保存该设置。可能是因为以下API中的注释。 (如果应用程序被后退按钮关闭,它保存了)。

  

请注意,您不得修改此调用返回的set实例。如果您这样做,则无法保证存储数据的一致性,也无法完全修改实例。   http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();

Set<String> outSet = prefs.getStringSet("key", new HashSet<String>());
Set<String> workingSet = new HashSet<String>(outSet);
workingSet.add("Another String");

editor.putStringSet("key", workingSet);
editor.commit();

答案 31 :(得分:0)

以上所有答案都是正确的。 :)我自己使用其中一个来解决我的问题。然而,当我读到这个问题时,我发现OP实际上是在讨论与本文标题不同的场景,如果我没有弄错。

&#34;即使用户离开活动,我也需要数组停留,然后想要稍后再回来#34;

他实际上希望存储数据直到应用程序打开,无论用户在应用程序中更改屏幕。

&#34;但是,在应用程序完全关闭后,我不需要可用的数组&#34;

但是一旦关闭应用程序,就不应该保留数据。因此我觉得使用SharedPreferences并不是最佳方法。

为此要求可以做的是创建一个扩展Application类的类。

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;
    }

}

使用setter和getter可以从应用程序的任何地方访问ArrayList。最好的部分是应用程序关闭后,我们不必担心存储的数据。 :)

答案 32 :(得分:0)

请使用这两种方法在kotlin的ArrayList中存储数据

fun setDataInArrayList(list: ArrayList<ShopReisterRequest>, key: String, context: Context) {
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)
    val editor = prefs.edit()
    val gson = Gson()
    val json = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()     // This line is IMPORTANT !!!
}

fun getDataInArrayList(key: String, context: Context): ArrayList<ShopReisterRequest> {
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)
    val gson = Gson()
    val json = prefs.getString(key, null)
    val type = object : TypeToken<ArrayList<ShopReisterRequest>>() {

    }.type
    return gson.fromJson<ArrayList<ShopReisterRequest>>(json, type)
}  

答案 33 :(得分:0)

    public  void saveUserName(Context con,String username)
    {
        try
        {
            usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
            usernameEditor = usernameSharedPreferences.edit();
            usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1)); 
            int size=USERNAME.size();//USERNAME is arrayList
            usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
            usernameEditor.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public void loadUserName(Context con)
    {  
        try
        {
            usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
            size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
            USERNAME.clear();
            for(int i=0;i<size;i++)
            { 
                String username1="";
                username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
                USERNAME.add(username1);
            }
            usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
            username.setAdapter(usernameArrayAdapter);
            username.setThreshold(0);

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

答案 34 :(得分:0)

public static void WriteSharePrefrence1(Context context, String key, 
ArrayList<HashMap<String, String>> value)
{
    final SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(value);
    editor.putString(key, json);
    editor.commit();
}
public static ArrayList<HashMap<String, String>> ReadSharePrefrence1(Context context, 
 String key)
{
    String data;
    Gson gson = new Gson();
    ArrayList<HashMap<String, String>> items = new ArrayList<>();
    final SharedPreferences preferences = 
    PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences.Editor editor = preferences.edit();
    data = preferences.getString(key, "");

    Type type = new TypeToken<ArrayList<HashMap<String, String>>>() {}.getType();
    items = gson.fromJson(data, type);

    return items;
}

答案 35 :(得分:0)

以防有人需要保存列表列表,即 List >。我这样做了:

序列化

Gson gson = new Gson();
// Save the size of the array
sharedPreferencesEditor.putInt("ArraySize", myArray.size());

for (int i=0; i<myArray.size(); i++) {
  String key = "Array"+i;
  String json = gson.toJson(myArray.get(i));
  sharedPreferencesEditor.putString(key, json);
}

sharedPreferencesEditor.commit();

反序列化

// Get the size of the array to be deserialized. In my case, the default number should be 3
int arraySize = sharedPreferences.getInt("ArraySize",3);

myArray = new ArrayList<List<String>>();

for (int i=0; i<arraySize; i++) {
  String key = "Array"+i;
  String json = sharedPreferences.getString(key, null);
  List<String> arrayTemp= gson.fromJson(json, List.class);
  myArray.add(arrayTemp);
}

// My array may also include components with empty strings. 
// Gson makes them null values and it is not possible 
// to deserialize them as empty strings. 
// The following takes care of that:

for (int i=0; i<myArray.size();i++) {
   if (myArray.get(i) == null) {
      List<String> emptyComponent = new ArrayList<String>() {
         { add(""); }
      };
      myArray.set(i,emptyComponent);
   }
}

答案 36 :(得分:-1)

public class VcareSharedPreference {
  private static VcareSharedPreference sharePref = new VcareSharedPreference(); 
  private static SharedPreferences sharedPreferences; 
  private static SharedPreferences.Editor editor;
  private VcareSharedPreference() {
 } 
public static VcareSharedPreference getInstance(Context context) {
    if (sharedPreferences == null) {
        sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    return sharePref;
 }
public void save(String KEY, String text) {
    editor.putString(KEY, text);
    editor.commit();
}
 public String getValue(String PREFKEY) {
    String text;

    //settings = PreferenceManager.getDefaultSharedPreferences(context);
    text = sharedPreferences.getString(PREFKEY, null);
    return text;
}
public void removeValue(String KEY) {
    editor.remove(KEY);
    editor.commit();
}

public void clearAll() {
    editor.clear();
    editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
    Gson gson = new Gson();
    String json = gson.toJson(modelCourses);
    editor.putString(key, json);
    editor.apply();
}

public ArrayList<ModelWelcome> getArray(String key) {

    Gson gson = new Gson();
    String json = sharedPreferences.getString(key, null);
    Type type = new TypeToken<ArrayList<ModelWelcome>>() {
    }.getType();
 return gson.fromJson(json, type);}}