I have a activity that shows a list of products and a detail view where I can edit these products. I want to access the same list of products from both activities.
How do I store/use this global data between these multiple activities?
I have a activity that shows a list of products and a detail view where I can edit these products. I want to access the same list of products from both activities.
How do I store/use this global data between these multiple activities?
You may want to use a Singleton design pattern: create a class and limit it to have only one instance that will hold a list of products. After that, access this instance and the same list from both of your activities:
// singleton Manager
public class ProductManager {
private static ProductManager sInstance;
private List<Product> mProducts;
// private constructor to limit new instance creation
private ProductManager() {
// may be empty
}
public static ProductManager getInstance() {
if (sInstance == null) {
sInstance = new ProductManager();
}
return sInstance;
}
public List<Product> getProducts() {
return new ArrayList<>(mProducts);
}
// add logic to fill the Products list
public void setProducts(List<Product> products) {
mProducts = new ArrayList<>(products);
}
}
Access it later from both activities:
MyListActivity.java:
// set products once you get them
ProductManager.getInstance().setProducts(yourProductsList);
// ...
DetailsActivity.java:
// get the same list
ProductManager.getInstance().getProducts();
// ...
1) You can define array List as a static in Application Level or Base Activity.
2) Pass array List to other Activity using serializable or parcelable.
3) You have more data in array list then you can use SharedPreferences.