How to refresh an Activity from an Adapter in java

1.8k views Asked by At

I have to update total price of the items selected in the cart activity by refreshing the activity when user updates the quantity of the items selected

Total price method is in the MainActivity while the cart items selected is in the RecyclerView

Just want to refresh an activity from adapter

public class Cart extends AppCompatActivity {

......

public void refreshActivtiy(){
            recreate();
    }
}

//Adapter

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {

    public void onBindViewHolder(@NonNull final CartAdapter.CartViewHolder holder, final int position) {

Cart cart = new Cart();
cart.refreshActivity();
}
}

Not working!!!

2

There are 2 answers

0
Zain On BEST ANSWER

Solution

((Cart)context).refreshActivtiy();
2
milancodes On

You can create an interface in the adapter, which you'll need to implement in the Activity.

Try this in your adapter:

public class CartAdapter(AdapterInteractions listener) extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {

    interface AdapterInteractions {
        public void refreshActivity();
    }

    public void onBindViewHolder(@NonNull final CartAdapter.CartViewHolder holder, final int position) {
        ...
        listener.refreshActivity();
    }
}

Implementing the interface in your activity:

public class Cart extends AppCompatActivity implements AdapterInteractions {

     ....
     @Override   
     public void refreshActivity(){  
         recreate();
     } 
}