Best way to pass objects between Activities,Android

http://vandzi.wordpress.com/2011/12/24/android-passing-objects-between-activities/


Android: Passing objects between activities

In Uncategorized on December 24, 2011 at 12:33
In this post I am going to show you how to easily pass object from one activity to another.
There are many ways how to pass data between activities. It’s easy with primive type such as String, int, boolean… You can use Intent’s putExtra methods.
Problem is when you want pass non primitive object. Your object can implement Parcelable  interface or there are many ways. But I didn’t want to implement this interface in every object which I want pass. That’s why I created my own way. I crated one static object which play bridge role between activities. See code bellow.
You have to create only one java class. I called it ActivitiesBridge.

/**
* Help to pass object between activities
*/
public class ActivitiesBringe {
private static Object object;
/**
* set object to static variable and retrieve it from another activity
*
* @param obj
*/
public static void setObject(Object obj) {
object = obj;
}
/**
* get object passed from previous activity
*
* @return
*/
public static Object getObject() {
Object obj = object;
// can get only once
object = null;
return obj;
}
}
When you have this class you can use it very easily.
Pass object:

Intent intent = new Intent(this, ClassToWhichIwantToPassObject.class);
ActivitiesBringe.setObject(new MyObject());
startActivity(intent);

Retrieve object:

public class ClassToWhichIwantToPassObject extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

MyObject myObject= (MyObject) ActivitiesBringe.getObject();

}
}
That’s it. This is how it works for me. It can also work for you. Just try it. It’s very simple.

Comments

Popular posts from this blog

Custom Dialog with no title and full screen in Android

Best working code to set Date limits on Date Picker Dialog,in Android

code to display .pdf,.text,.DOC,.DOCX,.doc extension files exists in SDCard