vandzi

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.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: