Articles → Android → Passing Parameters Through Intent In Android
Passing Parameters Through Intent In Android
Different Ways Of Passing Parameters
- Using extra attribute
- Using bundle object
- Using Parcelable method
Using Extra Attribute
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra(key, value);
startActivity(i);
String str = getIntent().getExtras().getString(key);
Using Bundle Object
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
Bundle b = new Bundle();
b.putString("name", "karan");
b.putString("country", "india");
intent.putExtra("bundle", b);
startActivity(intent);
Intent intent = getIntent();
Bundle b= intent.getBundleExtra("bundle");
b.getString("name")
b.getString("country")
Using Parcelable Method
- Create an object that you want to serialize and implement Parcelable class. Here is the implementation
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
private String name;
protected Person(Parcel in ) {
name = in .readString();
}
protected Person() {}
public void setName(String myName) {
name = myName;
}
public String getName() {
return name;
}
public static final Creator < Person > CREATOR = new Creator < Person > () {
@Override
public Person createFromParcel(Parcel in ) {
return new Person( in );
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
@Override
public int describeContents() {
return hashCode();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
}
}
- Create an intent object in MainActivity
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
Person p =new Person();
p.setName("karan");
intent.putExtra("parcel", p);
startActivity(intent);
- Get the value in second activity
Intent intent = getIntent();
Bundle b= intent.getExtras();
Person p = (Person)b.getParcelable("parcel");
Toast.makeText(SecondActivity.this, p.getName(), Toast.LENGTH_LONG).show();