Like i can send data from one activity to another using this:
intent.putExtra("Name", Value);
how can i send data when i am using finish()
to get back to the previous activity.
In my app from Activity_A
i am going to Activity_B
. In Activity_B
i am marking a location on map, which gives me latitude and longitude. Then i want to use this lat and lng in Activity_A
. But i don't want to get back to Activity_A
using an intent, because i don't want to recreate the Activity_A
since some data already filled will be lost.
As you are using intent.putExtra("Name", Value);
, use the same thing while finishing the activity also.
For ex.:
From activityA you call activityB like:
intent.putExtra("Name", Value);
now instead of startActivity() use `startActivityForResult()`
And from activityB, while finishing the activity, call:
setResult(RESULT_OK);
Now in activityA, your onActivityResult
will be called, which is like:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
}
So inthis way you can handle it.
In Activity A:
// Add more, if you call different activities from Activity A
private static final REQUEST_GET_MAP_LOCATION = 0;
void doSomething() {
...
startActivityForResult(theIntentYouUseToStartActivityB, REQUEST_GET_MAP_LOCATION);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GET_MAP_LOCATION && resultCode == Activity.RESULT_OK) {
int latitude = data.getIntExtra("latitude", 0);
int longitude = data.getIntExtra("longitude", 0);
// do something with B's return values
}
}
In Activity B:
...
setResult(Activity.RESULT_OK,
new Intent().putExtra("latitude", latitude).putExtra("longitude", longitude));
finish();
...
Call your Activity_B
with startActivityForResult()
, from your Activity_A
:
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), Activity_B.class);
// starting new activity
startActivityForResult(nextScreen,1000);
Once you finished working on the Activity_B
, you call setResult()
to set the data, followed by finish()
like this
//Starting the previous Intent
Intent previousScreen = new Intent(getApplicationContext(), Activity_A.class);
//Sending the data to Activity_A
previousScreen.putExtra("Bla"," Blabla");
setResult(1000, previousScreen);
finish();
This will bring you back to your previous Activity_A
.
In Activity_A
, override onActivityResult()
.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
String bla = data.getStringExtra("Bla");
}
Found here
use startActivityForResult
to start B and setResult
before B finish
and handle onAcitivityResult
in A