Items in RecyclerView not retaining the changed stated when backed

Viewed 34

I'm basically working on incrementing, decrementing and removing items from cart in the Recyclerview. I have a general class called CategoryItem.java whose objects I'm passing through to the Main Recyclerview in the mainactivity which show my items (without the quantity) which starts the Cart Activity on a button click and I have passed the same list of CategoryItem objects to the cart on button click. Everything else is working fine except the Cart.java and CartItemRecyclerAdapter, I'm utilizing the quantity attribute of CategoryItem objects here only, now the issue is the item quantity does get incremented/decremented/removed when I click my imageviews but does not retain the values in the textviews (Quantity goes back to 1 and the price gets to original of each item in the cart) and if I had removed the item it appears back when I return from the MainActivity. Also, help me with the carttotal, it does not update when I try to from the CartItemRecyclerAdapter.

public class MainActivity extends AppCompatActivity {
RecyclerView mainrecyclerview;
MainRecyclerAdapter mainRecyclerAdapter;
RecyclerView categoryrecyclerview;
CategoryItemRecyclerAdapter categoryItemRecyclerAdapter;
TextView menu ;
DrawerLayout drawerLayout;
NavigationView navigationView;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    menu = findViewById(R.id.textView);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawerLayout = findViewById(R.id.drawer_layout);
    navigationView = findViewById(R.id.drawer);
    ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
    drawerToggle.setDrawerIndicatorEnabled(false);
    drawerToggle.setHomeAsUpIndicator(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_baseline_account_circle_24,getTheme()));
    drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                drawerLayout.closeDrawer(GravityCompat.START);
            } else {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        }
    });
    drawerToggle.syncState();



    ImageView cartViewButton = toolbar.findViewById(R.id.viewCartButton);
    cartViewButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),Cart.class);
            startActivity(intent);
        }
    });


    List<CategoryItem> soupItemList = new ArrayList<>();
    soupItemList.add(new CategoryItem("Chicken Corn",30,R.drawable.soup1));
    soupItemList.add(new CategoryItem("Hot & Sour",100,R.drawable.hotnsour));
    soupItemList.add(new CategoryItem("Chinese Rice",500,R.drawable.soup3));
    soupItemList.add(new CategoryItem("Chicken Noodle",800,R.drawable.soup4));

    List<CategoryItem> seafoodItemList = new ArrayList<>();
    seafoodItemList.add(new CategoryItem("Chilli Prawns",750,R.drawable.chilliprawn));
    seafoodItemList.add(new CategoryItem("Dragon Prawns",750,R.drawable.dragonprawn));
    seafoodItemList.add(new CategoryItem("Red Roast Prawns",750,R.drawable.redroastprawn));
    seafoodItemList.add(new CategoryItem("Hot & Spicy Fish",750,R.drawable.hotnspicyfish));



    List<CategoryItem> poultryItemList = new ArrayList<>();



    List<AllCategory> allCategoryList = new ArrayList<>();
    allCategoryList.add(new AllCategory("SOUPS",soupItemList));
    allCategoryList.add(new AllCategory("SEAFOOD",seafoodItemList));
    //allCategoryList.add(new AllCategory("Sizzlers"));
    setMainrecyclerview(allCategoryList);








}
 private void closeDrawer(){
    drawerLayout.closeDrawer(GravityCompat.START);}
private void openDrawer(){
    drawerLayout.openDrawer(GravityCompat.START);
}

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)){
        closeDrawer();
    }
    super.onBackPressed();
}




private void setMainrecyclerview(List<AllCategory> allCategoryList){
    mainrecyclerview = findViewById(R.id.mainCatRecycler);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
    mainrecyclerview.setLayoutManager(layoutManager);
    mainRecyclerAdapter = new MainRecyclerAdapter(MainActivity.this,allCategoryList);
    mainrecyclerview.setAdapter(mainRecyclerAdapter);
}

}

public class Cart extends AppCompatActivity {

Toolbar toolbar;
RecyclerView cartRecyclerview;
CartItemRecyclerAdapter cartItemRecyclerAdapter;
static TextView bill;
int billtotal;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    toolbar = findViewById(R.id.carttoolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Cart");
    bill = findViewById(R.id.bill);

    setCartRecyclerview(getArrayList("key"));
    cartItemRecyclerAdapter.updatecarttotal();
    bill.setText(""+cartItemRecyclerAdapter.cartTotal);





}

public List<CategoryItem> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<List<CategoryItem>>() {}.getType();
    return gson.fromJson(json, type);
}

public void setCartRecyclerview(List<CategoryItem> cartitem){
    cartRecyclerview = findViewById(R.id.recyclerView);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(Cart.this);
    cartRecyclerview.setLayoutManager(layoutManager);
    cartItemRecyclerAdapter = new CartItemRecyclerAdapter(Cart.this,cartitem);

    cartRecyclerview.setAdapter(cartItemRecyclerAdapter);


}

}

public class CartItemRecyclerAdapter extends RecyclerView.Adapter<CartItemRecyclerAdapter.CartItemViewHolder> {
Context context;
List<CategoryItem> cartitems;
CartItem quantity;
int cartTotal=0;


public CartItemRecyclerAdapter(Context context, List<CategoryItem> cartitems) {
    this.context = context;
    this.cartitems = cartitems;
    this.quantity = new CartItem(1);
}

@NonNull
@Override
public CartItemRecyclerAdapter.CartItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    return new CartItemRecyclerAdapter.CartItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cartitem, parent, false));
}

@Override
public void onBindViewHolder(@NonNull CartItemViewHolder holder, int position) {

    holder.cartitem.setActivated(true);
    holder.cartItemname.setText(cartitems.get(position).getName());
    holder.cartItemimage.setImageResource(cartitems.get(position).getImageURI());
    holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice() * cartitems.get(position).getQuantity());
    holder.cartItemquantity.setText("" + cartitems.get(position).getQuantity());

    updatecarttotal();
    holder.plusimage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cartitems.get(position).quantity++;
            holder.cartItemquantity.setText(""+cartitems.get(position).getQuantity());
            holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice()*cartitems.get(position).getQuantity());
            updatecarttotal();






        }
    });
    holder.minusimagem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cartitems.get(position).quantity--;
            holder.cartItemquantity.setText(""+cartitems.get(position).getQuantity());
            holder.cartItemprice.setText("Rs. " + cartitems.get(position).getPrice()*cartitems.get(position).quantity);
            updatecarttotal();
            if (cartitems.get(position).getQuantity() == 0) {
                cartitems.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, cartitems.size());
                updatecarttotal();



            } else {
                updatecarttotal();
            }

        }
    });
    holder.crossimage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cartitems.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, cartitems.size());
            updatecarttotal();
        }
    });


}

public void updatecarttotal() {
    for (int i = 0; i < cartitems.size(); i++) {
        cartTotal += cartitems.get(i).getPrice()*quantity.quantity;
    }}







@Override
public int getItemCount() {
    return cartitems.size();
}

public static final  class CartItemViewHolder extends RecyclerView.ViewHolder{

    ImageView cartItemimage , plusimage, minusimagem, crossimage;
    TextView cartItemname, cartItemprice,cartItemquantity, billtotal;
    CardView cartitem;



    public CartItemViewHolder(@NonNull View itemView) {
        super(itemView);
        cartitem = itemView.findViewById(R.id.cartitemcardview);
        cartItemimage = itemView.findViewById(R.id.cart_itemimage);
        plusimage = itemView.findViewById(R.id.plus);
        minusimagem =itemView.findViewById(R.id.minus);
        crossimage = itemView.findViewById(R.id.remove);
        cartItemname = itemView.findViewById(R.id.cartitemname);
        cartItemprice = itemView.findViewById(R.id.cartitemprice);
        cartItemquantity = itemView.findViewById(R.id.quantity);
    }
}

}'''

public class CategoryItem {
String name;
int imageURI,price;
int quantity;

public CategoryItem(String name, int price, int imageURI) {
    this.name = name;
    this.price = price;
    this.imageURI = imageURI;
    this.quantity = 1;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

public int getImageURI() {
    return imageURI;
}

public void setImageURI(int imageURI) {
    this.imageURI = imageURI;
}}`
1 Answers

Consider storing your state in a viewmodel class using a live data, then you can observe for changes in your data and update your ui accordingly.

Related