1

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!!!

Zain
  • 21
  • 5
  • 3
    attach a listener callback to the adapter, and implement it on the activity – Zain Jun 20 '20 at 15:23
  • Welcome to StackOverflow! You should add the code to the question. See how to create a Minimal, Reproducible Example https://stackoverflow.com/help/minimal-reproducible-example. – EraftYps Jun 20 '20 at 15:24
  • use activity context or getActivity().refreshActivity(); no need to create the new Object of Cart activity. – Zahoor Saleem Jun 20 '20 at 18:16
  • This really works! Thanks @ZahoorSaleem – Zain Jun 24 '20 at 14:21

2 Answers2

1

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();
     } 
}
milancodes
  • 173
  • 1
  • 7
  • Could you be more specific, @Zain ? I use this approach in my applications and I haven't faced any errors yet. – milancodes Jun 24 '20 at 14:03
  • I got so many errors in adapter class while applying your code, but anyways i got the solution Thank you very much – Zain Jun 24 '20 at 14:18
1

Solution

((Cart)context).refreshActivtiy();
Zain
  • 21
  • 5