gpt4 book ai didi

android - Array Shared Preferences 重构 TableLayout OnDestroy

转载 作者:行者123 更新时间:2023-11-29 21:59:53 25 4
gpt4 key购买 nike

我有一个应该用作日记的应用程序,用户可以在其中输入一些文本并将其存储以供将来阅读。每个条目都存储在一个 tableLayout 中。

我将这些文本放在一个数组中,我希望 tableLayout 是永久的,我的意思是即使调用了 destroy,所以我需要使用共享首选项。

例如,如果用户在重启后打开我的应用程序,我该如何恢复所有行?

谢谢

最佳答案

如果您使用的是 API 级别 11 或更高级别,则可以使用 getStringSet()putStringSet()功能。这是一个例子:

SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

String yourArray = new String [] {"Hello", "World", "How", "Are", "You"};
editor.putStringSet(new HashSet(Arrays.asList(yourArray)), "test");

然后取回:

Set<String> data = prefs.getStringSet("test", null);

如果您使用的是较低级别的 API:

写下来:

//context - a context to access sharedpreferences
//data[] - the array you want to write
//prefix - a prefix String, helping to get the String array back.

public static void writeList(Context context, String [] data, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

int size = data.length;

// write the current list
for(int i=0; i<size; i++)
editor.putString(prefix+"_"+i, data[i]);

editor.putInt(prefix+"_size", size);
editor.commit();
}

获取它:

public static String[] readList (Context context, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);

int size = prefs.getInt(prefix+"_size", 0);

String [] data = new String[size];
for(int i=0; i<size; i++)
data[i] = prefs.getString(prefix+"_"+i, null);

return data;
}

删除整个列表:

public static int removeList (Context context, String prefix)
{
SharedPreferences prefs = context.getSharedPreferences("YourApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

int size = prefs.getInt(prefix+"_size", 0);

for(int i=0; i<size; i++)
editor.remove(prefix+"_"+i);

editor.commit();
return size;
}

使用它:

(这应该在您的 Activity 中)

//write it:
String yourArray = new String [] {"Hello", "World", "How", "Are", "You"};
writeList(this, yourArray, "test");

//get it back:
String yourArray = readList(this, "test");

//delete it:
removeList(this, "test");

关于android - Array Shared Preferences 重构 TableLayout OnDestroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com