nol*_*man 9 storage android sharedpreferences
我想知道是否可以在共享首选项中保存一个字符串数组,每次我们保存某个字符串时,我们将它存储在该数组中.
例如,我有一个具有特定ID的位置列表,我想将其标记为收藏夹.理想的情况是,有一个数组,数组中保存了一定的位置ID(我们称之为LOCATION1),所以下一次我要标记的新位置为最喜欢的(姑且称之为LOCATION2),我检索数组(到目前为止包含Location1)并添加我要添加的新位置的ID(Location2).
Android有存储基本对象的方法,但不存在数组.有什么想法,为了做到这一点,拜托?
She*_*tib 23
这是可行的:我只是写博客:
保存您的阵列
//String array[]
//SharedPreferences prefs
Editor edit = prefs.edit();
edit.putInt("array_size", array.length);
for(int i=0;i<array.length; i++)
edit.putString("array_" + i, array[i]);
edit.commit();
Run Code Online (Sandbox Code Playgroud)
检索你的阵列
int size = prefs.getInt("array_size", 0);
array = new String[size];
for(int i=0; i<size; i++)
prefs.getString("array_" + i, null);
Run Code Online (Sandbox Code Playgroud)
刚写过,所以可能会有拼写错误.
bee*_*nnn 15
您可以将数组设为JSON数组,然后将其存储为:
SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
SharedPreferences.Editor editor = settings.edit();
JSONArray jArray = new JSONArray();
try {
jArray.put(id);
} catch (JSONException e) {
e.printStackTrace();
}
editor.putString("jArray", jArray.toString());
editor.commit();
Run Code Online (Sandbox Code Playgroud)
然后你可以得到这样的数组:
SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
try {
JSONArray jArray = new JSONArray(settings.getString("jArray", ""));
} catch (JSONException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
只是我过去使用的替代解决方案
编写方法来读取和写入序列化数组。这应该不会太难。只需将字符串数组展平为存储在首选项中的单个字符串即可。另一种选择是将数组转换为 XML 结构,然后将其存储在首选项中,但这可能有点过头了。
| 归档时间: |
|
| 查看次数: |
20168 次 |
| 最近记录: |