Articles → Android → Passing parameters through intent in android

Passing parameters through intent in android






Different ways of passing parameters













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






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);
   }
}




Intent intent = new Intent(getApplicationContext(), SecondActivity.class);

Person p =new Person();
p.setName("karan");

intent.putExtra("parcel", p);

startActivity(intent);




Intent intent = getIntent();
Bundle b= intent.getExtras();

Person p = (Person)b.getParcelable("parcel");

Toast.makeText(SecondActivity.this, p.getName(), Toast.LENGTH_LONG).show();



Posted By  -  Karan Gupta
 
Posted On  -  Monday, December 02, 2019

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250