我有ListView Activity,它显示来自Sqlite的已保存记录列表。通过按下每个索引,它会导航到下一个Activity,该Activity根据已按下的ListView索引显示值。
一切都按预期工作,但每当我按下第二个活动中的删除按钮时,它会导航回ListView活动,但它不会更新ListView
。所以我必须再次向后退一个Activity并重新打开它,以便它最终开始更新ListView
。
这是我的ListView活动代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_artist);
artistList = (ListView) findViewById(R.id.artistList);
databasehandler = new SqliteHandler(ViewArtistActivity.this);
allArtists = databasehandler.getAllArtists();
artistName = new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (allArtists.size() > 0) {
for (int i=0; i < allArtists.size(); i++) {
ArtistModel artistModel = allArtists.get(i);
artistName.add(artistModel.getArtistName());
}
}
adapter = new ArrayAdapter(ViewArtistActivity.this, android.R.layout.simple_list_item_1, artistName);
artistList.setAdapter(adapter);
artistList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
singleArtistDetails = new ArrayList<>();
ArtistModel artistModel = allArtists.get(position);
singleArtistDetails.add(artistModel.getArtistName());
singleArtistDetails.add(artistModel.getArtistDOB());
singleArtistDetails.add(artistModel.getArtistBiography());
Intent intent = new Intent(ViewArtistActivity.this, SavedArtistDetailsActivity.class);
intent.putExtra("NAME", singleArtistDetails.get(0));
intent.putExtra("DOB", singleArtistDetails.get(1));
intent.putExtra("BIOGRAPHY", singleArtistDetails.get(2));
startActivity(intent);
}
});
}
答案 0 :(得分:1)
您需要覆盖onResume
中的ListViewActivity
功能。重新填充artistName
阵列,然后在适配器上调用notifyDataSetChanged
。
@Override
protected void onResume() {
super.onResume();
allArtists = databasehandler.getAllArtists();
// Clear the list
artistName.clear();
if (allArtists.size() > 0) {
for (int i = 0; i < allArtists.size(); i++) {
ArtistModel artistModel = allArtists.get(i);
artistName.add(artistModel.getArtistName());
}
}
adapter.notifyDataSetChanged();
}
要详细了解活动生命周期,请参阅documentation here。