在SharedPreferences中存储数组列表对象

usr*_*und 19 android sharedpreferences

此方法将新对象添加到 ArrayList

//get text from textview
time = date.getText().toString();
entry_d = entry.getText().toString();
dayName = day.getText().toString();

arrayList.add( new ArrayObject( dayName, entry_d ,time));
Run Code Online (Sandbox Code Playgroud)

我正在尝试添加这3个字符串SharedPrefrences.这是我的代码:

private void savePreferences(String key, String value) {

    SharedPreferences sharedPreferences = PreferenceManager             
                                     .getDefaultSharedPreferences(this);
    Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value);
    editor.commit();
}
Run Code Online (Sandbox Code Playgroud)

此方法一次只添加一个字符串,因为我想一次添加3个字符串.有什么方法我可以实现.

Sin*_*zak 71

使用Gson库将数组或对象转换为Json,并以json格式将数据存储为String.

保存;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();

String json = gson.toJson(arrayList);

editor.putString(TAG, json);
editor.commit();
Run Code Online (Sandbox Code Playgroud)

读;

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, "");
Type type = new TypeToken<List<ArrayObject>>() {}.getType();
List<ArrayObject> arrayList = gson.fromJson(json, type);
Run Code Online (Sandbox Code Playgroud)

  • 使用import java.lang.reflect.Type; (12认同)

Har*_*esh 21

使用共享首选项存储Arraylist

SharedPreferences prefs=this.getSharedPreferences("yourPrefsKey",Context.MODE_PRIVATE);
Editor edit=prefs.edit();

Set<String> set = new HashSet<String>();
set.addAll(your Arraylist Name);
edit.putStringSet("yourKey", set);
edit.commit();
Run Code Online (Sandbox Code Playgroud)

从共享首选项中检索Arraylist

Set<String> set = prefs.getStringSet("yourKey", null);
List<String> sample=new ArrayList<String>(set);
Run Code Online (Sandbox Code Playgroud)

  • 抱歉 它仅支持Set &lt;String&gt;,不支持其他。 (2认同)