Pass Objects From One Activity To Another To Change Their Values
If I have 3 class: MainActivity, SecondActivity, A. Please see my pseudo code below. I would like to know how to pass objects from one activity to another. Every explanation I've f
Solution 1:
You could use a singleton to hold some number of instances of A
. If you have data that you want to persist in an app session consistently across different Activities, you cannot reliably store that in an Activity (Activities can be killed and recreated in the background).
For example, here's a way to hold an arbitrary number of unique instances in a map:
staticclassAHolder {
privatestatic AHolder instance;
static AHolder getInstance() {
if( instance == null ) {
instance = newAHolder();
}
return instance;
}
privateAHolder() {}
privateHashMap<String,A> myCollection = newHashMap<>();
voidaddA(String key, A val) {
myCollection.put(key,val);
}
booleanhasA(String key) {
return myCollection.containsKey(key);
}
A getA(String key) {
return myCollection.get(key);
}
}
Then in MainActivity
you can add instances of A
to this with
AHolderah= AHolder.getInstance();
if(!ah.hasA("A1") ) {
ah.addA("A1",newA());
}
if(!ah.hasA("A2") ) {
ah.addA("A2",newA());
}
Aa1= ah.getA("A1");
Aa2= ah.getA("A2");
and to access and edit them in the other activity you can do
AHolderah= AHolder.getInstance();
Aa1= ah.getA("A1");
Aa2= ah.getA("A2");
Solution 2:
Singleton is one option. You can use serializable and parcelable interfaces and pass data through intent from one activity to anoter.
Post a Comment for "Pass Objects From One Activity To Another To Change Their Values"