Skip to content Skip to sidebar Skip to footer

Global Data Between 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/u

Solution 1:

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 ManagerpublicclassProductManager {
    privatestatic ProductManager sInstance;
    private List<Product> mProducts;

    // private constructor to limit new instance creationprivateProductManager() {
        // may be empty
    }

    publicstatic ProductManager getInstance() {
        if (sInstance == null) {
            sInstance = new ProductManager();
        }
        return sInstance;
    }

    publicList<Product> getProducts() {
        returnnew ArrayList<>(mProducts);
    }

    // add logic to fill the Products listpublicvoidsetProducts(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();
// ...

Solution 2:

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.

Post a Comment for "Global Data Between Activities"