Articles → Android → Passing Parameters Through Intent In Android

Passing Parameters Through Intent In Android






Different Ways Of Passing Parameters




  1. Using extra attribute
  2. Using bundle object
  3. 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




  1. Create an object that you want to serialize and implement Parcelable class. Here is the implementation
  2. 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);
      }
    }


  3. Create an intent object in MainActivity
  4. Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
    
    Person p =new Person();
    p.setName("karan");
    
    intent.putExtra("parcel", p);
    
    startActivity(intent);


  5. Get the value in second activity
  6. 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 2, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250