Search code examples
javaandroidandroid-recyclerviewandroidx

How to notify recyclerview adapter changes when navigating from other app


Initialized RecyclerView on my activity

private RecyclerView listView;

private ListCardAdapter listCardAdapter;

private Subscription subscription;

@Override
protected void onCreate(Bundle savedInstanceState) {

    listView = findViewById(R.id.subscription_list);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this);

    layoutManager.setOrientation(RecyclerView.VERTICAL);

    listView.setLayoutManager(layoutManager);

    listCardAdapter= new ListCardAdapter(getApplicationContext());

    listCardAdapter.setOnItemClickListener(this);

    listCardAdapter.setAdapter(subscriptionListCardAdapter);

    getPurchases(); //runs a service and sets subscription value and calls back onSkuDetails

}

@Override
public void onSkuDetails(List<SkuDetails> skuDetails) {

    removeProgressDialog();

    listCardAdapter.setData(subscription, skuDetails);

}

//ListCardAdapter 
public void setData(Subscription subscription, List<SkuDetails> skuDetailsList) {

    this.subscription = subscription;

    this.skuDetailsList = skuDetailsList;

    notifyDataSetChanged();
}

When the user selects a button on my activity, it will call a method and calls back onSkuDetails, then it will update the adapter's data then you will see the changes on the items list.

One of the button will start the google play store app and navigate to user's subscription page,user cancels subscription, when the user clicks back button until he gets back to the app it will call onSkuDetails, after that the recyclerview adapter doesn't trigger the onBindViewHolder that causing the item from not updating, this only occurs when navigating from other app(play store), but when I try to pull down from the screen(refresh), it will call the onBindViewHolder then the item list gets updated.


Solution

  • Run the notifyDataSetChanged() onUIthread.

    private void notifyAdapterDataSetChanged() {
    
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
    
                    subscriptionListCardAdapter.notifyDataSetChanged();
                }
            });
        }