简体   繁体   中英

How to modify ArrayList declared in another activity?

I have an ArrayList let's call it list in Activity A . Now Activity A calls Activity B and Activity B calls Activity C . In Activity C I want to insert some elements in list and reflect those changes when i come back to Activity A .

Approaches i have taken

1) Declared List as public static so i can access it in any activity but the problem is list gets reinitialized when Activity A is called by Activity C

Thanks in advance.

您可以创建一个新类并将ArrayList代替Activity A放入其中。因此,当创建Activity A时,不会重新初始化ArrayList。

It does not seem to be a good practice.

You can try doing like this:

  1. Create another class, a ListContainer , with your static mList inside.
  2. Access your list from any Activity using ListContainer.getList()
  3. Inside getList() you must do return mList==null ? new ArrayList() : mList return mList==null ? new ArrayList() : mList

I think it is a good way to do whatever you want to your list :D

Take a look on Observer pattern, it may help you. You can subscribe on changes in activity A and push them from any part of app if you are subscribed. Also here are some useful libs: EventBus, Otto.

If your flow is from A -> B -> C and after making changes going from C->B->A then startActivityForResult and setting that result within and passing it along would be best approach to use..

Still if you want to go with static approach, then it should be initialized in Activity A only.. and there is no way that static arraylist initialized more then once.. it will always take single memory allocation and initialized for once only..

When you need some variable accessible to different activities then you can declare, define and modify those kind of variable in Application class. You should declare those variables static and add getter & setter for these. Refer this for creating Application class:

https://guides.codepath.com/android/Understanding-the-Android-Application-Class

I am sure this will help you because we have solved this problem by this way.

use singleton model class make array list there use this array-list anywhere and change from any class .just call classname .arraylist;

otto is one more liabrary u can use you will get but i recomdent to make singleton model class

You can define your list static . static variables are not often used due to some issues but you can use it for few (one or two) variables but use carefully. static variables can be used with class name like ShoppingActivity.product_purchases .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM