我想保存多选listview复选框的状态。我有以下布局。多选ListView和SharedPreferences
我想要做的是保存的状态,例如,“测试1和TEST3”当我回到这个活动这个checkboxs进行检查。我正在使用共享首选项。我有以下代码。
这会将我的名单:
mList = (ListView) findViewById(R.id.ListViewTarefas);
final TarefaDbAdapter db = new TarefaDbAdapter(this);
db.open();
data = db.getAllTarefas(getIntent().getExtras().get("nomeUtilizadorTarefa").toString());
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,data);
mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mList.setAdapter(adapter);
LoadSelections();
,这是下面的代码加载和保存的checkboxs(据说)的状态。
@Override
protected void onPause() {
// always handle the onPause to make sure selections are saved if user clicks back button
SaveSelections();
super.onPause();
}
private void ClearSelections() {
// user has clicked clear button so uncheck all the items
int count = this.mList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mList.setItemChecked(i, false);
}
// also clear the saved selections
SaveSelections();
}
private void LoadSelections() {
// if the selections were previously saved load them
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
if (settingsActivity.contains(data.toString())) {
String savedItems = settingsActivity.getString(data.toString(), "");
this.data.addAll(Arrays.asList(savedItems.split(",")));
int count = this.mList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) this.mList.getAdapter().getItem(i);
if (this.data.contains(currentItem)) {
this.mList.setItemChecked(i, true);
}
}
}
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the user
SharedPreferences settingsActivity = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settingsActivity.edit();
String savedItems = getSavedItems();
prefEditor.putString(data.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.mList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.mList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.mList.getItemAtPosition(i);
} else {
savedItems += this.mList.getItemAtPosition(i);
}
}
}
return savedItems;
}
比我加载按钮中的SaveSelections和清除选择方法。
问题是这不起作用。有人可以帮我吗?
我的问候。
您是否尝试在代码中放置一些日志?例如,settingsActivity.contains(data.toString())返回true吗?你通过getString()方法得到什么字符串? – Egor
嗨。问题是,当我再次进入这个活动时,我添加了比那些存在的更多的值,并且它将所有复选框设置为真。 – unnamed
然后你应该覆盖现有的值,意味着你应该将它们存储在现有的密钥下。 – Egor