bimbima

Daily life experience of ayurvedic medicines, complementary therapies.

Android: Passing object from one activity to another

While doing application programming in android we need to pass objects from one activity to another. These objects can be any thing like string, numbers, dates or some user defined class objects.

What type objects you can pass to an activity? We will discuss it later in this post before that i will start with simple types.

There are mainly two scenario

  1. Passing data from one activity to another activity while starting another activity.
  2. Returning from activity to previous activity, when started activity for result.

 

I am going to take first case with one simple example.

Put this code from where you want to start new activity

int activityID = 0x100;
Intent intent;
intent = new Intent().setClass(this, MySecondActivity.class);
intent.putExtra("name","value");
startActivityForResult(intent, activityID);

 

Intent and Bundle are two classes to transfer object's from one activity to another activity. You can create bundle object and put them into intent as given below.

It will be better you refer Android SDK document for complete details of Intent and Bundle. Here i am discussing only them in context of passing objects from one activity to another.

To receive this object in  MySecondActivity Write This Code.

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.metadataview);
        Bundle extras = getIntent().getExtras();
        String data = extras.getString("name")
 
    }

Android framework automatically format String object and transfer it to another activity.

Now i am going to explain second case when we want to return some values from MySecondActivity to caller activity. Put following code just before calling finish ()method of an activity.

            Intent intent = new Intent();
            
            Bundle extras = new Bundle();
            extras.putString("userid", "admin");
            extras.putString("pwd","12345");
            intent.putExtras(extras);
            setResult(RESULT_OK, intent);        
            finish();//Finish  current activity
 

and in caller activity's onActivityResult overridden method get values like given below

    /* (non-Javadoc)
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) 
        {
            case 0x100:
            {                
                if(resultCode == RESULT_OK)
                {
                    Bundle extras = data.getExtras();
                    setUserID(extras.getString("userid"));
                    setPwd(extras.getString("pwd"));
                }
            }
        }
    }

These are two typical scenario  to pass object from one activity to another activity. In above example i have passed String type. So question that what are the types one can pass from one activity to another using Bundle and Intent.

You can pass all primitive types, primitive types their array,  Parcel , ArrayList<T> of int, string  and Parcelable using intent and bundle in same manner as described above.

Using Parcel type you can create parcel of primitive types and their array and you can pass this will intent and on receiving side you can read your data from parcel in same sequence in which you have added to this. For more details please refer android sdk documentation.

You can also pass types create by you and array list of your object but for this you have to implement Parcelable interface to your class. I am going to give one example class of implementation of Parcelable interface.

import android.os.Parcel;
import android.os.Parcelable;
 
public class Person implements Parcelable
{
 
    private String Name = "anupama";
    private String Address = "India";
    private int Age = 30;
    
    @Override
    public int describeContents()
    {
        // TODO Auto-generated method stub
        return 0;
    }
 
    @Override
    public void writeToParcel(Parcel dest, int flag)
    {
        // TODO Auto-generated method stub
        dest.writeString(Name);
        dest.writeString(Address);
        dest.writeInt(Age);
    }
    public Person(Parcel in)
    {
        this.Name = in.readString();
        this.Address = in.readString();
        this.Age = in.readInt();
    }
 
    @SuppressWarnings("unchecked")
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public Person createFromParcel(Parcel in)
        {
            return new Person(in);
        }
 
        public Person[] newArray(int size)
        {
            return new Person[size];
        }
    };
}

 

You can just add this class object to Intent or bundle as i given below.

Person person = new Person();

intent.putExtra("person",person);

and for reading back use like this.

Person person = (Person)data.getParcelableExtra(name);

And just like other array you can create array or array list of these objects and pass it between activities.