Ozan Manav Ozan Manav - 3 months ago 14
Android Question

When press Back Button, to send a value previous Activity

Hi everyone I want to this: When press Action bar Back Button, to send a value previous Activity. And check value stay there.

public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
//i'm giving error because i mustnt create new activity i must to send previous activity..
LoginActivity yeni=new LoginActivity();
yeni.setPassword("");
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}

}


When I press the back button sign out the application and go loginscreen but I must change a value in loginactivity because if I don't login activity again login same values and start main activity...

Clearly, When I pressed the back button I must send a value maybe null to a method in
LoginActivity
. Like this:

public void setPassword(String comingpass)
{
_passwordText.setText(comingpass);

}


When it knows
_passwordtext=null
stay there and wait for new login...

Answer
// call activity with startActivityForResult
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);


//back press
switch (item.getItemId()) {
        case android.R.id.home:
 Intent returnIntent = new Intent();
returnIntent.putExtra("flag",1);
setResult(Activity.RESULT_OK,returnIntent);
finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }


//handle back in main activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == 1) {
    if(resultCode == Activity.RESULT_OK){
        if(data.getIntExtra("flag",0)==1){
        yeni.setPassword("");
    }
    }
    if (resultCode == Activity.RESULT_CANCELED) {
        //Write your code if there's no result
    }
}
}