Skip to content
Advertisement

How to update the RecyclerView Adapter outside the Adapter Class

I am making an android app and it allows user to enter the keywords in a editText and when they hit submit the recyclerview down below will show the result from an API request.

I have a updateList() method inside my recyclerView adapter class

list = savedInfo.getResult(); // get updated list from a singleton class
notifyDataSetChanged(); // update the recyclerView

I call this method after making the API Request successfully. However, it is now working, the recyclerView is not updated.

mSearchBox is the editText allows users to enter keywords and here is the onEditorAction, it will make an API call and if it called successfully, it will call UpdateList(), then the adapter will get the updated list and do notifyDataSetChanged()

        mSearchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
            if (i == EditorInfo.IME_ACTION_DONE) {
                HttpRequest httpRequest = new HttpRequest();
                mHomeText.setText(textView.getText());
                try {
                    if (httpRequest.makeCall(textView.getText().toString())){
                        adapter.updateList();
                    }
                    else {
                        // showing error message
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
            return false;
        }
    });

Also, here is the steps to set my adapter

    final ResultListAdapteradapter = new ResultListAdapter();
    mResult.setAdapter(adapter);
    mResult.setLayoutManager(new LinearLayoutManager(getContext()));

Debugging Steps: I tried to set break points and found out the API Request and my Singleton class are both working, the issue is just the RecyclerView.

Thank you so much!

Advertisement

Answer

When you do

list = savedInfo.getResult();
notifyDataSetChanged();

It is every time creating new list instance and the old one is not referenced anywhere. So instead of assigning to list you should do

list.clear()
list.addAll(savedInfo.getResult());
notifyDataSetChanged();

Don’t forget to initialize list if not done before.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement