Feeds:
Posts
Comments

Archive for the ‘Android Intent- Passing Data’ Category

How to pass user defined Object from one activity to other

In the previous blog we saw how to pass the primitive data from one activity to other. In this blog we’ll see how we can pass user defined data from one activity to other. Let us say we have a user defined class Employee having two attributes id and name. In order to enable us to pass object of Employee from 1 activity to other the Employee class needs to implement the interface called Parcelable. This interface is for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface.

Employee.java


package com.passdata;

import android.os.Parcel;
import android.os.Parcelable;

public class Employee implements Parcelable {
	int id;
	String name;
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 1;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeInt(id);
		dest.writeString(name);

	}

	public Employee(Parcel source) {
		// TODO Auto-generated method stub
		id = source.readInt();
		name = source.readString();

	}

	public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {

		@Override
		public Employee createFromParcel(Parcel source) {
			// TODO Auto-generated method stub
			return new Employee(source);
		}

		@Override
		public Employee[] newArray(int size) {
			// TODO Auto-generated method stub
			return new Employee[size];
		}
	};

}

When a class implements Parcelable interface it needs to override 2 methods – describeContents method and writeToParcel method. writeToParcel method is overriden to flatten this object in to a Parcel. In our overriden method of Employee class we are just writing the id and name attribute of Employee object into Parcelable object. Also, classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface. So in our Employee class we are making a static field CREATOR. We need to override 2 methods here:
1. createFromParcel(Parcel source)
Create a new instance of the Parcelable class, instantiating it from the given Parcel whose data had previously been written by Parcelable.writeToParcel().
2.newArray(int size)
Create a new array of the Parcelable class.
As our overriden version of createFromParcel returns a new Employee object by calling constructor of Employee with Parcelable object as argument we need to create a constructor in Employee class for the same.

public Employee(Parcel source) {
// TODO Auto-generated method stub
id = source.readInt();
name = source.readString();

}
Once the above is done, we can create the Activity class as follows:

ActivityOne.java


package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ActivityOne extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button button = (Button) findViewById(R.id.btn);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent = new Intent(ActivityOne.this,ActivityTwo.class);
				Bundle b = new Bundle();
				Employee e = new Employee(1, "shawn");
				b.putParcelable("parse", e);
				intent.putExtras(b);
				startActivity(intent);
			}
		});
	}
}

ActivityTwo.java


package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityTwo extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity2);
		TextView textView = (TextView) findViewById(R.id.txt);
		Intent intent = getIntent();
		Bundle b = intent.getExtras();
		Employee e = b.getParcelable("parse");

		textView.setText(e.getId() + ":" + e.getName());
	}

}

The layout xml files are as follows:
main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Pass Data"
    android:id="@+id/btn"
    />
</LinearLayout>

activity2.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView
  
   android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/txt"
   />
    
</LinearLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.passdata"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ActivityOne"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="ActivityTwo"></activity>

    </application>
</manifest>

Do let me know your feedback.

Advertisements

Read Full Post »

How to pass collection of primitive data types  from one activity to other

Objects can also be passed from one activity to other by packaging them in a Bundle object.
In the example below we are packaging a string object and a string array in a Bundle Object and passing it to Activity2. All the xml files strings.xml,main.xml,activity2.xml,AndroidManifest.xml are same as Part1 of blog- Android Intents for Passing Data between Activities-Part1

ActivityOne.java

package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ActivityOne extends Activity {
EditText editText;
Button button;
final String[] arr = new String[] { "one", "two", "three" };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.main);

editText= (EditText) findViewById(R.id.edit1);
button = (Button) findViewById(R.id.btn);

/** setting the onclick listener for button */
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

/** getting the value of edit text entered by user */
String textVal = editText.getText().toString();
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);

/** setting the textVal in intentExtra */
/** passing string */
Bundle b = new Bundle();
b.putString("name", textVal);

/** passing string array*/
b.putStringArray("array", arr);
intent.putExtras(b);

/** start Activity2 */
startActivity(intent);
}
});

}
}

In the above example the Bundle object b is created by calling the constructor of Bundle object. In the bundle object string is passed by calling putString with the key and value parameters. Similarly, boolean, float, long etc can be passed. In the above code we are also passing string array by calling putStringArray(“array”, arr) on bundle object. Finally, the bundle object is set in intent.

Retrieve data passed in ActivityTwo:

package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityTwo extends Activity {

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.activity2);
textView = (TextView) findViewById(R.id.txt2);
/** get the intent */
Intent intent = getIntent();

/** get the bundle from intent*/
Bundle b = intent.getExtras();
/** retrieve the string extra passed */
String a = b.getString("name");

/** retrieve the stringarray extra passed */
String[] arrRecd = b.getStringArray("array");
textView.setText(a + ":val:" + arrRecd[1]);
}

}

To retrieve the data passed in intent first we get the intent object. The activity class has method called getIntent() that returns the intent object that started this activity. Once we have the intent object  we can use getExtras to get the bundle object.Then on the  bundle object we can call getString to get the string type passed in the intent. This method takes the string argument which is the key used when we set the data in intent object in ActivityOne.

In the last part of this post we will see

How to pass user defined Object from one activity to other

Read Full Post »

This blog is covered in 3 parts. It will help you in understanding the following:
1. How to pass primitive data type from one activity to other
2. How to pass collection of primitive data types  from one activity to other
3. How to pass user defined objects from one activity to other

The first part covers

How to pass primitive data from one Activity to other.

In Android to pass data from one Activity to other we use Intent class objects. Intents can be thought of mechanism to pass objects between activity or broadcast reciver or services.
Example:
Let us say we have an acivity, ActivityOne which has a  TextView and a Button. The user enters some text in the text box and clicks on the Button. The click event will redirect the user to the next Activity, ActivityTwo. ActivityTwo displays a customised welcome message to the user with the text entered by user in ActivityOne. We have to pass the text entered by the user in ActivityOne to ActivityTwo. This can be achieved by creating Intent Object.

ActivityOne .java


package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ActivityOne extends Activity {
EditText editText;
Button button;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.main);

editText= (EditText) findViewById(R.id.edit1);
button= (Button) findViewById(R.id.btn);

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

/** getting the value of edit text entered by user */
final String textVal = editText.getText().toString();

Intent intent = new Intent(ActivityOne.this,
ActivityTwo.class);

/** setting the textVal in intentExtra */
intent.putExtra("name", textVal);
intent.putExtra("testBool", true);

startActivity(intent);
}
});

}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/edit1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="@string/buttonText"

/>
</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, ActivityPassDataActivity!</string>
    <string name="app_name">ActivityPassData</string>
    <string name="buttonText">Pass Data</string>
</resources>

In the button onClickListener we are creating an Intent object. The Intent object takes 2 arguments. First argument is the context and second is the Class to which the intent is passed. In this example we are passing the intent to ActivityTwo, so we are setting the class as ActivityTwo.class. The Intent object has a public method putExtra. This method takes 2 arguments. The first argument is the key and 2nd argument is the value for that key.  The 2nd argument can be of any type boolean , float, double, long etc. For example, if we have to pass boolean we can use i.putExtra(“test”, true);

Retrieve data passed in ActivityTwo:

ActivityTwo.java

package com.passdata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ActivityTwo extends Activity {

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
/** setting the view of the activity to xml */
setContentView(R.layout.activity2);
textView = (TextView) findViewById(R.id.txt2);

/**get the intent*/
Intent intent = getIntent();

/**retrieve the string extra passed*/
String stringRecd = intent.getStringExtra("name");

/*retrieve the boolean extra passed*/
Boolean boolRecd = intent.getBooleanExtra("testBool", false);
textView.setText(stringRecd + ":boolval:"+boolRecd );
}

}

activity2.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/txt2"
android:layout_marginTop="30sp"
android:gravity="center"
/>

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.passdata"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ActivityOne"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="ActivityTwo"></activity>

    </application>
</manifest>

To retreive the data passed in intent first we get the intent object. The activity class has method called getIntent() that returns the intent object that started this activity. Once we have the intent object  we can use getStringExtra or getBooleanExtra or getFloatExtra depending on the data type passed in intent. In the above example to get the string type passed in the intent we used getStringExtra. This method takes the string argument which is the key used when we set the data in intent object in ActivityOne. In the method intent.getBooleanExtra(“testBool”, false), the second argument is the defaultValue to be returned if no value of the desired type is stored with the given name.

In the next post we will see

How to pass collection of primitive data types  from one activity to other

Read Full Post »