Android Activity

In my last example I explained how to open an activity from another activity. Now in this example we will learn how to pass data from one activity to other activity.

I am taking the same example which I used in previous article. I have one textbox in the main activity to take input.


<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/editText"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Open Another Activity"
    android:id="@+id/button"
    android:onClick="btn_OpenActivity"
    android:layout_below="@+id/editText"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

		

Also add textview on another activity to display output.

Now go to the main java file’s method which we have created in the last example and mapped it with button on click even.

 /code>
		public void btn_OpenActivity(View v)
{

String str= ((android.widget.EditText)findViewById(R.id.editText)).getText().toString();

Intent intent=new Intent(MainActivity.this, AnotherActivity.class);

//data is the key which is user defined
intent.putExtra("data",str);

startActivity(intent);


}

		

Now go to the onCreate method on another activity

		
		public class AnotherActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another);
        android.widget.TextView txt=(android.widget.TextView)findViewById(R.id.textView);
        String str=getIntent().getExtras().getString("data");
        txt.setText(str);
    }
}

		

now execute the code

pass data to activity
result