Big.Child Big.Child - 4 months ago 32
Android Question

What is Intent from onActivityResult Parameters

Here is my

first activity
code from where I call the
second Activity
:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
startActivityForResult(new Intent("chap.two.Chapter2Activity2"),request_Code);
}
return false;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK)
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}


And here is a code of
chap.two.Chapter2Activity2
:

Button n = (Button) findViewById(R.id.btn_OK);
n.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Intent data = new Intent();
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();

}
});


here I see that
setResult(RESULT_OK, data)
has two arguments but

onActivityResult(int requestCode, int resultCode, Intent data)
has three and I want know how
onActivityResult
gets value for third parameter? How it works can anyone tell me? Why isn't this error ?

Answer

When you call Activity.startActivityForResult(), you set the requestCode. Later, this request code is needed by onActivityResult() in order to determine what Activity is sending data to it. We don't need to supply requestCode again on setResult() because the requestCode is carried along.

The data is intent data returned from launched intent. We usually use this data when we set extras on the called intent.

Consider this example:

CALL SECOND ACTIVITY

Intent i = new Intent(MainActivity.this, CheckActivity.class);
startActivityForResult(i, REQUEST_CODE_CHECK);

ON SECOND ACTIVITY, SET INTENT RESULT

getIntent().putExtra("TADA", "bla bla bla");
setResult(RESULT_OK, getIntent());
finish();

BACK TO FIRST ACTIVITY, ONACTIVITYRESULT()

if(requestCode == REQUEST_CODE_CHECK && resultCode == RESULT_OK){
    text1.setText(data.getExtras().getString("TADA") );
}

There you go. You should now understand what is Intent data and how to set and fetch the value.