Reputation: 67
So i have a recyclerview in my MainActivity and want to open a window (new activity?) and add items to my recyclerview from that window. Right now i'm trying to do it like this. The problem is that when i add the item to the list, my recyclerview does not show it (i guess it's because i don't update my adapter?) what is the best way of doing this? I don't mind changing the structure of my program.
MainActivity.java
static ArrayList<filterItem> filters = new ArrayList<>();
filters.add(new filterItem("1", R.mipmap.ic_launcher));
filters.add(new filterItem("2", R.mipmap.ic_launcher));
filters.add(new filterItem("3", R.mipmap.ic_launcher));
filters.add(new filterItem("4", R.mipmap.ic_launcher));
filters.add(new filterItem("5", R.mipmap.ic_launcher));
filters.add(new filterItem("6", R.mipmap.ic_launcher));
filters.add(new filterItem("7", R.mipmap.ic_launcher));
filters.add(new filterItem("8", R.mipmap.ic_launcher));
filters.add(new filterItem("9", R.mipmap.ic_launcher));
filters.add(new filterItem("10", R.mipmap.ic_launcher));
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(layoutManager);
adapter = new MyAdapter(this, filters);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
BrowseFilters.java
MainActivity.filters.add(filterToAdd);
I know there are already posts answering the question of how to do this, and the answers says just to make the list static as I have done. But is this the best way to do it or are there better ways of doing this? If making a static list is the best way, then how doi show my updated list in MainActivity?
Upvotes: 0
Views: 98
Reputation: 1018
your need to call adapter.notifyDataSetChanged()
after add an item into adapter
Best practice in this case is startActivityForResult()
from MainActivity
In the SecondActivity, pass the extra item you want to add in MainActivity back to MainActivity
In the MainActivity, override onActivityResult()
and handle adding the extra item into the adapter and call adapter.notifyDataSetChanged()
Upvotes: 1