Reputation: 25
Which is the Best way to access data from one activity to another? 1.Making that variable static than access it in another class or another activity by using its class name as it is Java functionality. 2. using intent methods as it is Android functionality.
Which is the best?
What i learnt is that we have to use as much intents as much data we are transferring and in static we have just declare that variable static.
so please clear my doubt?
Upvotes: 1
Views: 91
Reputation: 11756
Avoid using the static methods inside activities, It is dangerous most of the time and is not considered as a good design practice in android. You can have any of the following approaches for transferring data between activities, services etc.
StartActivityForResults
method (to exchange data between activities).Start the second activity with startActivityForResult
instead of startActivity
.
In the second activity, When you want to finish and close the second activity and give back the result to the previous activity: -
Intent result=new Intent();
result.putExtra("var1",data1);
result.putExtra("var2", data2);
setResult(Activity.RESULT_OK, result);
finish();
Using an event bus (go here for a good library which already implemented this method)
Using a local broadcast manager
Upvotes: 1
Reputation: 36
Static variable inside Activity will easily cause memory leak. The static variable will still in memory even if the life cycle of Activities end. So if you want to pass objects, you can either pass inside intent where the object implements Parcelable (Serializable interface is slower), or you use a Singleton class of HashMap of WeakReferences.
e.g.
public class DataHolder {
private static final DataHolder holder = new DataHolder();
public static DataHolder getInstance() {return holder;}
Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
void save(String id, Object object) {
data.put(id, new WeakReference<Object>(object));
}
Object retrieve(String id) {
WeakReference<Object> objectWeakReference = data.get(id);
return objectWeakReference.get();
}
}
Then you could save / retrieve like
DataHolder.getInstance().save(id, object);
DataHolder.getInstance().retrieve(id);
Since the hashmap only holds a weakreference to the object, garbage collection can collect those unreferenced object
(static HashMap of strong reference to objects is a dangerous source of memory leak too)
Upvotes: 0
Reputation: 29
static methods for sending data between activity is so dangerous. you can use Extras for send and get it from Bundle
Upvotes: 0