Friday 3 January 2020

android - How to save an activity's state?





As stated in the question, I want to know how to save an activity's state. My application has a list of products and allows the user to click on a product, starting the second activity that displays all the information about that product. On that second activity, the user can "Add the product to the shopping cart" by pressing a button.
When you press the button, the 3rd activity starts. It's a listview displaying the added product's name and price - as shown in the below code.
How do I save the data added so that if I go back and add another product, it adds it to the listview below the one already there?



I hope the question is clear, if not, please ask and i'll add whatever is needed.




Thanks in advance :)



package activity_app;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;

import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class shopping_cart extends ListActivity {

private ListView lv;
private Intent intent;
private String name;
private String price;

ArrayList> oslist;
private static final String PROD_PRICE ="price";
private static final String PROD_NAME = "name";
ListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_cart_activity);
getActionBar().setTitle("Ordered Products");

intent = getIntent();
name = intent.getStringExtra("PROD_NAME");
price = intent.getStringExtra("PROD_PRICE");
oslist = new ArrayList>();

HashMap map = new HashMap();
map.put(PROD_NAME, name);
map.put(PROD_PRICE, price);
oslist.add(map);


adapter = new SimpleAdapter(shopping_cart.this, oslist,
R.layout.shoppingcart,
new String[] {PROD_NAME, PROD_PRICE}, new int[] {R.id.name, R.id.Price});
setListAdapter(adapter);

Answer



You need to store your shopping cart data to persistent storage somewhere. Take a look at the storage option documentation that someone else mentioned.



Basically, you need to save your cart item to the file system somewhere (sqlite db, text file, shared prefs). You'll do this when your activity exits onStop() or onDestroy() then retrieve the saved cart item in your activity onCreate() or onResume() or whichever method you are using to populate your cart.




The other way to do this is to use intent extras to pass your item data between activities by using intent.putExtra(name, value). This works fine as long as your activities don't get killed, in which case the data will be lost. So, it's safer to save to persistent storage.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...