Search code examples
javaandroidandroid-recyclerviewgoogle-play-billing

How to set Recyclerview adapter onCallBack


On my activity's onCreate(), I initialized the recyclerview

private RecyclerView listView;

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);

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

}


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

    ListCardAdapter listCardAdapter = new ListCardAdapter(getApplicationContext(), subscription, skuDetails);

    ListCardAdapter.setOnItemClickListener(this);

    //this will return RecyclerView: No adapter attached; skipping layout
    listView.setAdapter(listCardAdapter);

    removeProgressDialog();

}

I tried setting layoutManager inside onSkuDetails but it stops going to next line after setLayoutManager , I did some research and the results says:

  1. it's because of the setting of layoutManager.
  2. Must set the adapter onCreate() or main thread.

PS: I updated google play billing library to latest(4.0) that have changes on my classes related to this activity, google play billing is working.


Solution

  • After some more research I found out that you just need to update adapter properties/data instead of setting the adapter again then just call notifyDataSetChanged()

    private ListCardAdapter listCardAdapter;
    
    @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();
    
    }
    
    @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();
    }