Android Activity onResume() and onActivityResult() conflict
-
27-10-2019 - |
Question
Have a problem. In my main Activity I have a ListView. And I need to refresh it any time I returned to this Activity. I use onResume() method for this:
@Override
protected void onResume() {
super.onResume();
refreshCategoriesList();
}
private void refreshCategoriesList() {
// ...
categoriesListAdapter = new CategoryListItemAdapter(
this, R.layout.category_item,
categories
);
categoriesListView.setAdapter(categoriesListAdapter);
}
As you can see I use refreshing adapter extended from ArrayAdapter for changing data in ListView.
But in some cases I need scroll this list to the end, for ex. when I add new item to it. And I use onActivityResult(...) method for this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// ...
refreshCategoriesList();
categoriesListView.setSelection(categoriesListAdapter.getCount() - 1);
}
But I have one problem. When I add new item to my list both this methods executed in order onActivityResult(...) and after that onResume(). And I have:
- List data refreshed to times with refreshCategoriesList() (But it's not main problem);
- After executing of onResume() scrolled to end list restored to first item position :( It's a problem. Because when I add new item I want scroll list to the end.
How can I resolve this problem. Can I in some cases call only onActivityResult(...) method (when I need to scroll list) and in other onResume() method (when I simply want to refresh list data)?
Solution
You can use notifyDataSetChanged() method from ArrayAdapter instead of recreating adapter every time.
private void refreshCategoriesList() {
categoriesListAdapter.notifyDataSetChanged();
}