我有一个包含listview的活动,活动(MainActivity
)启动另一个活动(HomeworkAddActivity
),这将从用户检索一个字符串并将其添加到listview(以上所有内容)作品)。
然而,为了让listview在其他活动启动时'记住'其内容,我尝试将列表保存到文件中,代码:
public void saveHomework() {
try {
@SuppressWarnings("resource")
FileOutputStream fos = new FileOutputStream(homeworkFileName);
fos = openFileOutput(homeworkFileName,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(homeworkItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void populateHomework() {
try {
@SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(homeworkFileName);
fis = getParent().openFileInput(homeworkFileName);
ObjectInputStream is = new ObjectInputStream(fis);
homeworkItems = (ArrayList<String>) is.readObject();
is.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
然后我从文件中读到它。
saveHomework
被称为onPause
和populateHomework
:
@Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
populateHomework();
homeworkListAdapter.notifyDataSetChanged();
}
然而,它只显示addHomeworkActivity
添加的项目,而不是“已保存”和“已恢复”的项目(它们未成功保存/恢复),为什么会这样?
答案 0 :(得分:0)
它有2个问题
您的列表视图仍与旧适配器连接
notifyDataSetChanged在您的情况下可能不起作用,它与此答案有关
您需要在onResume()
中重新排序命令@Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
populateHomework(); // I move this line up
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
//homeworkListAdapter.notifyDataSetChanged(); // this line might not work
yourListView.setAdapter(homeworkListAdapter); // because your listview still connect with your old ArrayAdapter
}