Android 数组共享首选项重建表布局OnDestroy
我有一个应用程序,可以作为日记使用,用户可以输入一些文本,并将其存储到将来的阅读中。每个条目都存储在一个表布局中,一个在另一个上 我把这些文本放在一个数组中,我希望tableLayout是永久的,我的意思是即使调用了on destroy,我也需要使用共享首选项 例如,如果用户在重新启动后打开我的应用程序,我如何恢复所有行Android 数组共享首选项重建表布局OnDestroy,android,arrays,android-tablelayout,ondestroy,Android,Arrays,Android Tablelayout,Ondestroy,我有一个应用程序,可以作为日记使用,用户可以输入一些文本,并将其存储到将来的阅读中。每个条目都存储在一个表布局中,一个在另一个上 我把这些文本放在一个数组中,我希望tableLayout是永久的,我的意思是即使调用了on destroy,我也需要使用共享首选项 例如,如果用户在重新启动后打开我的应用程序,我如何恢复所有行 谢谢如果您使用的是API 11级或更高级别,则可以使用和函数。以下是一个例子: SharedPreferences prefs = context.getSharedPrefe
谢谢如果您使用的是API 11级或更高级别,则可以使用和函数。以下是一个例子:
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 11级或更高级别,请查看我更新答案的开头部分!它给出了很多错误。。。我的意思是,第一种方法:写下来。列表在下一个方法中是未定义的相似问题:String[]data=String[size];对不起,我不习惯使用列表。让我们来看看
//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;
}
//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");