Sometimes you may have problems to pass an Id, a form data with multiple values from one activity to another in Android. But this post completely solves your problem. This is achieved easily by using class Intent and bundle. Class Intent is responsible for starting an activity. Also, we will use the two methods, I.e, putString() contains the Id and the String value to be passed and putExtras() that contains the bundled value to be passed as shown below.
MainActivity.java
Intent intent=new Intent(MainActivity.this, Activity2.class);
Bundle extras = new Bundle();
extras.putString("NameId", "Peter");
extras.putString("ContactId", "+08823443");
intent.putExtras(extras);
startActivity(intent);
Besides, you can use Bundle with variables as shown below.
Bundle with Variables
String name="Peter";
String contact="+08823443";
Intent intent=new Intent(MainActivity.this, Activity2.class);
Bundle extras = new Bundle();
extras.putString("NameId", name);
extras.putString("ContactId", contact);
intent.putExtras(extras);
startActivity(intent);
Activity2.java
For the second activity, we will use Bundle to get the passed Id and get the value passed by that ID as shown below.
Bundle extras = getIntent().getExtras();
String name = extras.getString("NameId");
String name = extras.getString("ContactId");
Our final output will be Peter and +08823443.
Passing Integer Values
For the case of an integer, use the following code to pass multiple integer values.
MainActivity.java
Intent intent=new Intent(MainActivity.this, Activity2.class);
intent.putExtra("intVariableName", intValue);
startActivity(intent);
Activity2.class
Activity2.java, use the following code to receive integer values from the MainActivity.java
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
Congrats:Now you can pass multiple Strings and Integers from one class to another.
http://whats-online.info/science-and-tutorials/49/Android-passing-multiple-data-from-one-activity-to-another/
Comments
Post a Comment