Updating cart count on pressing of back button after deletion
Asked Answered
S

1

6

I have two activities, one is UserActivity and other one is CartActivity I am showing a list of products in UserActivity. On click of a button AddtoCart I am adding the products to the cart. I am facing this problem:

When I add click the button AddtoCart there is a cart icon in the action bar and I have a custom layout of a textview showing cart counter on that cart icon. That counter updates whenever I click the button AddtoCart. Now I move on to the CartActivity and delete some of the products from the cart. When I press back button now to return to UserActivity, the counter text view doesn't update.

I have read about few ways of doing the updation on pressing of back as given in the question here Back button and refreshing previous activity. Two methods given in the answer are by overriding the OnResume() method of UserActivity or by starting activity for result.

I think I need to pass a variable called DeleteCounter from CartActivity to the UserActivity when I press the back button and subtract it from the original number of products in the Counter TextView and update the text view.

Here is the partial code of UserActivity and I have the function to update cart counter in this code only which is called when I click a button. Also the code of onActivityResult() in commented in this which I tried from the answer of above given SO question link. It's not working out:

    public class UserActivity extends AppCompatActivity{
            private int cartindex = 0;
            private TextView counterTV = null;
            
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_user);
              
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);
            }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 1) {
//
//            if(resultCode == RESULT_OK){
//                  Intent intent = getIntent();
//                  Integer deletecounter = intent.getIntExtra("DeleteCounter",0);
//                  if(deletecounter>0){
//                      UpdateCartCount(Integer.parseInt(counterTV.getText().toString())-deletecounter);
//                  }
//            }
//        }
//    }
            
        @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.user, menu);
                final View menu_list = menu.findItem(R.id.action_hawk).getActionView();
                counterTV = (TextView) menu_list.findViewById(R.id.cartcounter);
                UpdateCartCount(cartindex);
                new MyMenuItemStuffListener(menu_hotlist, "Show message") {
                    @Override
                    public void onClick(View v) {
                        Intent intent= new  Intent(UserActivity.this,CartActivity.class);
                        intent.putExtra("ProductTitle",pname);
                        intent.putExtra("ProductUrl",purl);
                        intent.putExtra("ProductPrice",pprice);
                        intent.putExtra("BargainPrice",bargainprice);
                        UserActivity.this.startActivity(intent);
                    }
                };
                return true;
    }
    //Function to update cart count
            public void UpdateCartCount(final int new_number) {
                    cartindex = new_number;
                    if (counterTV == null) return;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (new_number == 0)
                                counterTV.setVisibility(View.INVISIBLE);
                            else {
                                counterTV.setVisibility(View.VISIBLE);
                                counterTV.setText(Integer.toString(new_number));
                            }
                        }
                    });
                }

Here is the code of CartActivity:

    public class CartActivity extends AppCompatActivity {
    
        private List<Product> mCartList;
        private ProductAdapter mProductAdapter;
        private static List<Product> cart;
        private static Integer deletecounter= 0;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_cart);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            mCartList = getCart();
    
    
            Intent intent = getIntent();
            String ProductTitle = intent.getStringExtra("ProductTitle");
            String ProductUrl = intent.getStringExtra("ProductUrl");
            String ProductPrice = intent.getStringExtra("ProductPrice");
            String BargainPrice = intent.getStringExtra("BargainPrice");
            Product product = new Product(ProductTitle, ProductUrl, ProductPrice, BargainPrice);
            mCartList.add(product);
            // Make sure to clear the selections
            for (int i = 0; i < mCartList.size(); i++) {
                mCartList.get(i).selected = false;
            }
    
            // Create the list
            final ListView listViewCatalog = (ListView) findViewById(R.id.cart_list_view);
            mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(), true, CartActivity.this);
            listViewCatalog.setAdapter(mProductAdapter);
    
            listViewCatalog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                        long id) {
    
                    Product selectedProduct = mCartList.get(position);
                    if (selectedProduct.selected)
                        selectedProduct.selected = false;
                    else
                        selectedProduct.selected = true;
    
                    mProductAdapter.notifyDataSetInvalidated();
    
                }
            });
            FloatingActionButton Delete = (FloatingActionButton) findViewById(R.id.fab);
            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // Loop through and remove all the products that are selected
                    // Loop backwards so that the remove works correctly
    
                    for (int i = mCartList.size() - 1; i >= 0; i--) {
    
                        if (mCartList.get(i).selected) {
                            mCartList.remove(i);
                            deletecounter++;
                        }
                    }
// THIS IS THE CODE I USED TO RETURN DATA TO PREVIOUS ACTIVITY BUT UserActivity STARTS AUTOMATICALLY AFTER DELETION OF SELECTED PRODUCTS AS SOON AS I CLICK THE DELETE BUTTON EVEN WHEN THERE ARE PRODUCTS IN THE CART.
 //                  if(deletecounter!=0) {
//                    Intent i = new Intent(HawkActivity.this, UserActivity.class);
//                    startActivityForResult(i, 1);
//                    Intent returnIntent = new Intent();
//                    returnIntent.putExtra("DeleteCounter", deletecounter);
//                    setResult(RESULT_OK, returnIntent);
//                }
                    mProductAdapter.notifyDataSetChanged();
                    Snackbar.make(view,"Selected items deleted successfully",Snackbar.LENGTH_SHORT).show();
                }
            }
            );
        }
        public static List<Product> getCart() {
            if(cart == null) {
                cart = new Vector<Product>();
            }
    
            return cart;
        }
    }

When I use the code which is commented out in both the activities i.e use of start activity for result method, this happens: When I click on the delete button, items get deleted but the CartActivity closes automatically. The UserActivity with counter text view is shown having '0' value even when there are products in the cart.

Do tell me about any other info you need from the code. Any other ways I can implement to update the cart counter on pressing of back button after deletion of some items in CartActivity are welcome. Any help is appreciated.

Salomo answered 22/12, 2015 at 9:1 Comment(0)
B
1

Use

invalidateOptionsMenu();

in onActivityResult to populate menu again.

Your UserActivity code should be like :

public class UserActivity extends AppCompatActivity {
    private int cartindex = 0;
    private TextView counterTV = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {

            if (resultCode == RESULT_OK) {
                Intent intent = getIntent();
                Integer deletecounter = intent.getIntExtra("DeleteCounter",0);
                if (deletecounter>0) {
                    cartindex=Integer.parseInt(counterTV.getText().toString())-deletecounter;
                    invalidateOptionsMenu();
                }
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.user, menu);
        final View menu_list = menu.findItem(R.id.action_hawk).getActionView();
        counterTV = (TextView) menu_list.findViewById(R.id.cartcounter);
        UpdateCartCount(cartindex);
        new MyMenuItemStuffListener(menu_hotlist, "Show message") {
            @Override
            public void onClick(View v) {
                Intent intent= new  Intent(UserActivity.this,CartActivity.class);
                intent.putExtra("ProductTitle",pname);
                intent.putExtra("ProductUrl",purl);
                intent.putExtra("ProductPrice",pprice);
                intent.putExtra("BargainPrice",bargainprice);
                UserActivity.this.startActivity(intent);
            }
        };
        return true;
    }

    //Function to update cart count
    public void UpdateCartCount(final int new_number) {
        cartindex = new_number;
        if (counterTV == null) return;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (new_number == 0)
                    counterTV.setVisibility(View.INVISIBLE);
                else {
                    counterTV.setVisibility(View.VISIBLE);
                    counterTV.setText(Integer.toString(new_number));
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        if (CartActivity.cart.size()!=0) {
            cartindex=CartActivity.cart.size(); 
            invalidateOptionsMenu();
            super.onRestart()
        }
Blastocoel answered 22/12, 2015 at 9:12 Comment(9)
No, still not working. Problem is when I press the delete button, selected products are deleted and the CartActivity finishes itself, even when products are still there in the cart and the UserActivity appears with zero counter in the cart. I don't want UserActivity to appear at all when I click delete! If I press back than it should appear with the updated count of the cart.Salomo
replace if(deletecounter!=0) condition with if(mCartList.size()==0) in CartActivityBlastocoel
UserActivity is called as deletecounter is incremented when item is deleted which satisfy condition deletecounter!=0 and Intent is fired so better to check size of arraylist if 0 or not if 0 then only Intent to UserActivity should be firedBlastocoel
Done. Resolves the problem of starting up of 'UserActivity` on click of delete button. Counter problem still there. Let's say I added 2 items in my cart, cart counter shows 2. I move to the cart activity and delete an item. Then I press the back button cart counter still shows 2. This issue is still not resloved.Salomo
ok call invalidateOptionsMenu(); in onResume() method of UserActivityBlastocoel
and use one static variable to manage count of item in cart and initilize value in it in onPause() method of CartActivity and check in onResume() method of UserActivity if(staticVarialblename!=0){ invalidateOptionsMenu(); }Blastocoel
I declared a variable named cartcounter in CartActivity, I initialised it with number of items in the cart calling mcartlist.size(). Now how will I access it in onResume method of UserActivity? Do you want me to use startactivityforresult() in onPause() of CartActivity?Salomo
i have edited UserActivity code of mine try it will work when user press back button from CartActivityBlastocoel
It worked, thanks a lot Kapil! I was stuck in this problem since 2 days. I know how its working now.Salomo

© 2022 - 2024 — McMap. All rights reserved.