Skip to content Skip to sidebar Skip to footer

How Can I Transfer The Data Between Two Activities In Android

Possible Duplicate: How do I pass data between activities in Android? I have two activities A and B. Activity A has one editText and a button.Activity B has a editText, when I t

Solution 1:

I will assume that you have written two Activity classes: ActivityA & ActivityB and that you have written the onClickListener for the button in ActivityA.

To pass data between two activities, you will need to use the Intent class via which you are starting the Activity and just before startActivity for ActivityB, you can populate it with data via the Extra objects. In your case, it will be the content of the editText.

ActivityA onClickListener

Intenti=newIntent(getBaseContext(),ActivityB.class);

//Set the Data to passEditTexttxtInput= (EditText)findViewById(R.id.txtInput);
StringtxtData= txtInput.getText().toString();
i.putExtra("txtData", txtData);

startActivity(i);

Now in ActivityB, you can write code in the onCreate to get the Intent that launched it and extract out the data passed to it.

ActivityB onCreate

Intenti= getIntent();
//The second parameter below is the default string returned if the value is not there. StringtxtData= i.getExtras().getString("txtData","");
EditTexttxtInput2= (EditText)findViewById(R.id.txtInput2);
txtInput2.setText(txtData);

Hope this helps.

Solution 2:

When you're starting activity B send data in intent extras.

In Activity A, When you're starting activity B,

Intent activityBstartIntent = newIntent(getApplicationContext(), ActivityB.class);
activityBstartIntent.putExtra("key", editTextA.getText().toString());
startActivity(activityBstartIntent);

And in onCreate() of ActivityB do this

if(getIntent().getExtras() != null) {
editTextB.setText(getIntent().getExtras().getString("key");
}

Hope that helps.

Solution 3:

By using intent we can pass data across components like activities. In your first activity on click on button you need to write this get send data to second activity.

Intentintent=newIntent(this, DisplayMessageActivity.class);
EditTexteditText= (EditText) findViewById(R.id.edit_message);
Stringmessage= editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);

EXTRA_MESSAGE is String constant in your activity.

And second activity you will get that message like this

Intent intent = getIntent();

String message = intent.getStringExtra(MyFirstActivity.EXTRA_MESSAGE);

Here it's explained very clearly.

Solution 4:

Yes, someone can provide code for this, and Google even made it the subject of many tutorials and sample code. Try reading about Intents.

Post a Comment for "How Can I Transfer The Data Between Two Activities In Android"