是否可以在Android上向SharedPreferences添加数组或对象

zsn*_*erx 79 android android-preferences sharedpreferences

我有一个ArrayList具有名称和图标指针的对象,我想将其保存SharedPreferences.我能怎么做?

注意:我不想使用数据库

She*_*tib 72

无论API级别如何,在SharedPreferences中检查字符串数组和对象数组


保存阵列

public boolean saveArray(String[] array, String arrayName, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i=0;i<array.length;i++)  
        editor.putString(arrayName + "_" + i, array[i]);  
    return editor.commit();  
} 
Run Code Online (Sandbox Code Playgroud)

负载阵列

public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}  
Run Code Online (Sandbox Code Playgroud)

  • 这是一种可怕的技术.在该博客上查看[评论](http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html?showComment=1344601931230#c7323949469112498436):"这种方法的问题是你会污染你的偏好.比如,你保存一个包含100个条目的数组,然后将它缩小到2.你的首选项中仍然会有100个条目,除非你先清理它." (9认同)
  • 这是一个错误的方法!你尝试添加100个变量,这太可怕了!! 相反,您可以将此方法与jsonarray和jsonbj一起使用:http://stackoverflow.com/a/8287418/2652368 (3认同)
  • 清理是一个很容易的补充 (2认同)

Noe*_*oel 59

所以从Android开发者网站上的数据存储:

用户首选项

共享偏好不严格用于保存"用户偏好",例如用户选择的铃声.如果您对为应用程序创建用户首选项感兴趣,请参阅PreferenceActivity,它为您提供了一个Activity框架,供您创建用户首选项,这些首选项将自动保留(使用共享首选项).

所以我认为这是可以的,因为它只是持久存在的键值对.

对于原始海报,这并不难.您只需遍历数组列表并添加项目即可.在这个例子中,为了简单起见,我使用了一个map,但你可以使用一个数组列表并适当地改变它:

// my list of names, icon locations
Map<String, String> nameIcons = new HashMap<String, String>();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");

SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();

for (String s : nameIcons.keySet()) {
    // use the name as the key, and the icon as the value
    keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()
Run Code Online (Sandbox Code Playgroud)

你会做类似的事情再次读取键值对.让我知道这个是否奏效.

更新:如果您使用的是API级别11或更高版本,则可以使用一种方法来写出字符串集


Roh*_*hit 58

来写,

SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();
Run Code Online (Sandbox Code Playgroud)

阅读,

try {
    JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
    for (int i = 0; i < jsonArray2.length(); i++) {
         Log.d("your JSON Array", jsonArray2.getInt(i)+"");
    }
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)


Mos*_*afa 31

共享首选项在API级别11中引入了一个getStringSetputStringSet方法,但是它与旧版本的Android(仍然很受欢迎)不兼容,并且仅限于字符串集.

Android没有提供更好的方法,并且循环地图和数组以保存和加载它们并不是非常简单和干净,特别是对于数组.但更好的实现并不难:

package com.example.utils;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;

public class JSONSharedPreferences {
    private static final String PREFIX = "json";

    public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
        editor.commit();
    }

    public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
        editor.commit();
    }

    public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
    }

    public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
    }

    public static void remove(Context c, String prefName, String key) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
            SharedPreferences.Editor editor = settings.edit();
            editor.remove(JSONSharedPreferences.PREFIX+key);
            editor.commit();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用这五种方法将任何集合保存在共享首选项中.使用JSONObject并且JSONArray非常容易.您可以使用JSONArray (Collection copyFrom)公共的构造做出JSONArray任何Java集合的并用JSONArrayget方法来访问的元素.

共享首选项没有大小限制(除了设备的存储限制),因此这些方法适用于大多数常见情况,您希望在应用程序中快速轻松地存储某些集合.但是JSON解析在这里发生,并且Android中的首选项在内部存储为XML,因此我建议在处理兆字节数据时使用其他持久数据存储机制.

  • 如果您使用JSON,可以查看gson:http://code.google.com/p/google-gson/ - 它将Java对象转换为JSON和从JSON转换. (7认同)

Hps*_*urn 17

使用Gson谷歌库轻松模式进行复杂的对象存储[1]

public static void setComplexObject(Context ctx, ComplexObject obj){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj)); 
    editor.commit();
}

public static ComplexObject getComplexObject (Context ctx){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    String sobj = preferences.getString("COMPLEX_OBJECT", "");
    if(sobj.equals(""))return null;
    else return new Gson().fromJson(sobj, ComplexObject.class);
}
Run Code Online (Sandbox Code Playgroud)

[1] http://code.google.com/p/google-gson/