我想:
在主活动中保存单词并在另一个名为ShowAll的Activity中将其显示为listView(+复选框)。
问题是:
每次我在ShowAll中移除一个项目=>按回去进入主要活动=>添加新项目:除了添加的项目外,还会显示旧的已删除项目。
// this method opens the new activity and passes the list
public void findAll(View view) {
Intent i = new Intent(this, ShowAll.class);
fh = new FileH(); // simple File read-write class
i.putStringArrayListExtra("data", fh.read("etitaa.txt", this));
startActivity(i);
}
// Deleting an item within the new activity
public void Delete(View view) {
list.remove(currentItem);
FileH fh = new FileH();
fh.write(list, "etitaa.txt", this);
adapter.notifyDataSetChanged();
}
我不知道将列表传递回MainActivity的最佳方法是什么。任何帮助将不胜感激。
答案 0 :(得分:3)
除非您想要,否则无需使用该文件。您可以使用Intent
个对象和startActivityForResult()
方法轻松完成此操作。
ActivityMain:
public void startNextActivity() {
Intent intent = new Intent(this, ActivitySecond.class);
intent.putStringArrayListExtra("data", list);
startActivityForResult(intent, 2);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 2 && resultCode == RESULT_OK) {
ArrayList<String> returnedData = data.getStringArrayListExtra("data");
//... do what you want with the updated list...
}
}
ActivitySecond:
ArrayList<String> updatedList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updatedList = getIntent().getStringArrayListExtra("data", null);
//Use this list when removing items from it in the second activity
}
@Override
public void finish() {
Intent result = new Intent();
result.putStringArrayListExtra("data", updatedList);
setResult(RESULT_OK, result); //<-- added second parameter
super.finish();
}