存储在共享preferences一个String数组数组、preferences、String

2023-09-04 23:14:42 作者:蓝汐.

我在想,如果它可能是可以保存在共享preferences字符串数组,在某种程度上,我们节省了一定的字符串,每次,我们将其存储在数组中。

I was wondering if it could be possible to save in the shared preferences an array of Strings, in a way that, every time we save a certain String, we store it in that array.

例如我有,我想标记为收藏具有一定的ID地址列表。 理想的情况是,有一个数组,该数组保存一定的位置ID(我们称之为LOCATION1),所以下一次我要标记一个新的位置,最喜欢的(姑且称之为LOCATION2),我检索数组(到目前为止包含LOCATION1),并添加这个新的位置,我想补充(LOCATION2)的标识。

For example I have a list of locations with a certain ID that I want to mark as favorite. The ideal situation would be, having an array and saving a certain location ID (let's call it Location1) in that array, so next time I want to mark a new location as favorite (let's call it Location2), I retrieve that array (which so far contains Location1) and add the ID of this new location I want to add (Location2).

Android有方法来存储原始的物体,但不为阵列。 任何想法,为了做到这一点,好吗?

Android has methods to store primitive objects, but not for arrays. Any idea in order to do this, please?

推荐答案

这是可行的:的我只是写博客吧:

保存您的数组的

SAVE YOUR ARRAY

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

检索您的ARRAY 的

RETRIEVE YOUR ARRAY

int size = prefs.getInt("array_size", 0);
array = new String[size];
for(int i=0; i<size; i++)
    prefs.getString("array_" + i, null);

只是写道,所以有可能是拼写错误。

Just wrote that so there might be typos.