1

I have 2 activities A and B first one having products list and second one is the shopping cart. On click of a button in the list I am adding products to the cart.

Now I go to the cart and delete some items from it. I press back and came to the activity A again. Now if I go to the B(cart) again the list is null i.e there are no products in the cart.

I am using onSaveInstanceState and onRestoreInstanceState to save an restore the instance of cart activity but that is not working. Perhaps this is happening because I clicked the back button which destroyed cart activity and these methods were never called. I referred to this question: Saving activity state on Android and this Activity state after pressing back button. On pressing of back button activity is destroyed and popped out of the stack so I maybe its the case that I cannot use onSaveInstanceState and onRestoreInstanceState.

What I should use to save the products in my cart activity even if I press back button and how can I retrieve that on recreation of the activity? During some research I got to know I can use shared preferences, or SQLite database to store my activity state but I didn't found a good implementation. Any help regarding this is appreciated. Please share any useful SO links or tutorials regarding the same.

Community
  • 1
  • 1
gautamprajapati
  • 2,055
  • 5
  • 16
  • 31
  • 2
    Possible duplicate of [How do you save your Activity's state when exiting? Android](http://stackoverflow.com/questions/2308628/how-do-you-save-your-activitys-state-when-exiting-android) – Iamat8 Dec 30 '15 at 09:35
  • what you have used to show list of product?? array list or products come from database – Dhaval Parmar Dec 30 '15 at 09:38
  • I am using ArrayList to show products, I have a ProductClass and Products are the objects of this class – gautamprajapati Dec 30 '15 at 09:40
  • @Mohit I have stated in the question that `onSaveInstanceState` and `onRestoreInstanceState` are not working. The possible duplicate you have marked isn't addressing my problem. I have edited they question, hope it is more clear now. – gautamprajapati Dec 30 '15 at 09:52
  • Trigger your saving function call inside destroy method of your activity.which will save the details before it get destroyed. The other thing is you can override `public void onBackPressed() { moveTaskToBack(true); }` to move your task to back. – Madhukar Hebbar Dec 30 '15 at 10:11

0 Answers0