【发布时间】:2014-12-12 08:59:16
【问题描述】:
我正在尝试使用自定义适配器填充 listview 并使用 shared preferences 保存它,如下所示。
保存列表:
Set<String> mycategory = new HashSet<String>(MyCategory);
PreferenceManager.getDefaultSharedPreferences(CategoryList.this)
.edit()
.putStringSet("MyCategory", mycategory)
.commit();
检索列表:
Set<String> mycategory = PreferenceManager.getDefaultSharedPreferences(AddItems.this)
.getStringSet("MyCategory", new HashSet<String>());
ArrayList<String> CategoryList = new ArrayList<String>(mycategory);
MyAddedList.addAll(CategoryList);
adp.notifyDataSetChanged();
我的场景:首先单击MainActivity 中的一个按钮,该按钮转到second activity,在第二个活动中我有一个button,它可以将一些项目添加到我的列表视图中,效果很好,现在如果我使用向上导航启用home button 到 MainActivity,如果我回到第二个活动,列表是 empty。
如果我回到same 活动,现在我该如何retain 数据......
我不想使用任何数据库,但想知道如何使用 sharedpreferences。
编辑:
单击按钮时我在对话框中调用它:
lv = (ListView) findViewById(R.id.itemscategoryView);
adp = new MyCategoryAdapter(CategoryList.this, MyCategory);
/*
* adp = new ArrayAdapter<String>( MainActivity.this, R.layout.list,
* R.id.textView, MyList);
*/
lv.setAdapter(adp);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String NewListname = editText.getText().toString();
if (TextUtils.isEmpty(NewListname)) {
return;
} else {
//mylistitem = NewListname;
MyCategory.add(NewListname);
adp.notifyDataSetChanged();
}
Set<String> mycategory = new HashSet<String>(MyCategory);
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name),MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("MyCategory", mycategory);
editor.commit();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
OnResume:
@Override
public void onResume(){
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.app_name),MODE_PRIVATE);
Set<String> mycategory = sharedPreferences.getStringSet("MyCategory", new HashSet<String>());
MyCategory.addAll(mycategory);
}
【问题讨论】:
-
这可能是因为第二个活动仍然存在。在 onResume() 中再次加载你的列表怎么样?或者当你回到主目录时,在第二个活动中调用 finish()...
-
@Opiatefuchs-试过但没有再次加载列表
-
我确定您粘贴了错误的代码。但是这里你只是保存列表,你的检索和保存是一样的。
-
除非您的代码块中有错字,否则您在检索时使用的是
putStringSet(...)。 -
@Squonk-ah srry.. 这是一个拼写错误。
标签: android listview android-listview sharedpreferences