Monday, March 18, 2013

Returning Result from Activity

In Android an Activity can be started for some results, means an
Activity can return some result to the Parent/Previous Activity.

An Activity can return String, Int, float, boolean etc as Result.

In this post I have two Activities MainActivity and SecondActivity.
Second Activty returns a String to the First MainActivity as Result.
From MainActivity we start the Second Activity to get Result with follwing method

startActivityForResult(Intent intent, int requestCode);

to get the Result back we need to override the method..

onActivityResult(int requestCode, int resultCode, Intent data)

the
data object (last parameter of above method) contains the returned
Result, we need to fetch the result from data(object of Intent).See the Execution Flow

First Screen: Click on get Message (MainActivity)

Second Screen: Enter the Message " I am much Busy" and click on Submit Message (Second Activity)

3rd
Screen : See the returned message MainActivity , you can see
the result is being returned to Previous Activity i.e. MainActivity
(Which have started the activity for result)

// get The refference of The textView
textViewMessage=(TextView)findViewById(R.id.textViewMessage);
}

// Method to handle the Click Event on GetMessage Button
public void getMessage(View V)
{ // Create The Intent and Start The Activity to get The message
Intent intentGetMessage=new Intent(this,SecondActivity.class);
startActivityForResult(intentGetMessage, 2);// Activity is started with requestCode 2
}

// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{ // fetch the message String
String message=data.getStringExtra("MESSAGE"); // Set the message string in textView
textViewMessage.setText(message);