Search code examples
androidonclicklistenerandroid-recyclerview

How to inform recyclerview adapter of new item inserted into data


I know that notifyItemInserted(position) is used, but in most of the examples I have seen it gets triggered with help of Click Listeners.

But in my case I want adapter to know the change and update its view when a button in another activity is pressed.

How can I achieve this?

Consider below example scenario: 1) App starts with Activity A

2) Activity A contains recyclerview

3) As Currently data is empty no items is shown in recyclerview

4) Somehow I got into Activity B

4) I updated the data and pressed Button

5) As new data is there, recyclerview is now having a single view with updated data


Solution

  • If it suits you, make a global instance of List of data model you want to update RecyclerView from.

    List<DataModel> dataModelList = new ArrayList<>();
    

    You can do this in a class extending Application class or somewhere else where you want.

    Now in ActivityA

    public class ActivityA extends AppCompatActivity {
        YourAdapter adapter;
        RecyclerView recyclerView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    
        adapter = new YourAdapter(YourClassWhereYouPutDataModelList.dataModelList)
        recyclerView.setAdapter(adapter);
    
    
        @Override
        protected void onResume() {
            super.onResume();
            adapter.notifyDataSetChanged();
        }
    }
    

    Now in your ActivityB

    public class ActivityA extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //your code to get value
                    YourClassWhereYouPutDataModelList.dataModelList.add(YourValue);
                    //Now it's up to you, either finish it using finish() or continue working
                    //Whenever you go to ActivityA, RecyclerView will be updated
                }
            });
        }
    }