Menu

Android – Pass a value from one activity to another on button click

In android app development, we play with multiple activities. In most of the app, the activities are related to each other in the mean that they share data/message with each other. So, its important to know how to pass data/value from one activity to another activity with button click.

Here we are going to implement a button click event which passes a value or multiple values to another activity. Lets see the simple coding behind this. The below code is to define button and its click event. Here in this first activity, user input some value in edit textbox. And with a button click, the values are passed to SecondActivity.


EditText mytext1 = (EditText) findViewById(R.id.my_text1);

EditText mytext2 = (EditText) findViewById(R.id.my_text2);

Button btn = (Button) findViewById(R.id.my_btn);
btn .setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

Intent i = new Intent(view.getContext(), SecondActivity.class);

String val1 = mytext1.getText().toString();
String val2 = mytext2.getText().toString();

//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("value1", val1 );
bundle.putString("value2", val2);
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
}}

Now in Second Activity, for receiving the passed value, we use buldle to get the values. We are using the textview to display the received text/values.


//Get the data from bundle

Bundle bundle = getIntent().getExtras();
String data1 = bundle.getString("value1");
String data2 = bundle.getString("value2");

//define the textview to display the received text

TextView textView1 = (TextView) findViewById(R.id.textView1);
TextView textView2 = (TextView) findViewById(R.id.textView2);

//Displaying the receiving text in text view

textView1.setText(data1);
textView2.setText(data2);

Hope, this will help you in your app development.

Learn the most easy method of implementing Android Action Bar  in Android app development.

 

Leave a Reply

Your email address will not be published. Required fields are marked *