To receive result back from called activity you can use startActivityForResult() instead of startActivity() it override onActivityResult() to receive result.
Here is complete example of how to retrieve result from calling activity.
1. Create class from which you want to start new activity.
public class SetResultActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnGetResult=(Button) findViewById(R.id.btnResult);
final Intent intent=new Intent(this,SecondActivity.class);
btnGetResult.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(intent, 1); // call new activity
}
});
}
// these method call when called activity finished.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==1) // check result code set in secondActivity that is 1
{
String str=data.getStringExtra("STR");
TextView tv=(TextView) findViewById(R.id.tvShow);
tv.setText(str);
}
else
Log.i("Result", "not Receive");
}
}
2. Create second Activity from which you want to receive result.
public class SecondActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondlayout);
final Intent intent=new Intent();
Button btnOk=(Button) findViewById(R.id.btnOk);
btnOk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText etText=(EditText) findViewById(R.id.etText);
String str=etText.getText().toString();
intent.putExtra("STR", str); // set value in intent
setResult(1,intent); // set result here 1 is result code used in when //we return multiple result back to main activity
finish(); // finishes current activity
}
});
}
}
3. Register secondActivity in AndroidManifest.xml
<activity android:name="SecondActivity"></activity>
No comments:
Post a Comment