Reputation: 925
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.
Upvotes: 0
Views: 635
Reputation: 1
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
.
Upvotes: 0
Reputation: 798
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
Upvotes: 0
Reputation: 92
It does not seem to be a good practice.
You can try doing like this:
ListContainer
, with your static mList
inside.ListContainer.getList()
return mList==null ? new ArrayList() : mList
I think it is a good way to do whatever you want to your list :D
Upvotes: 1
Reputation: 47
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.
Upvotes: 0
Reputation: 859
You can create a new class and put the ArrayList in it instead of Activity A. So, when Activity A is created, ArrayList won't be reinitialized.
Upvotes: 1
Reputation: 1786
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..
Upvotes: 0
Reputation: 156
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.
Upvotes: 0