Articles → Android → Return Result From Intent In Android

Return Result From Intent In Android






Example




  1. Add a button with the caption ‘NAVIGATE’ in MainActivity.
  2. On click of a button, add data in intent and navigate to SecondActivity.
  3. Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
    intent.putExtra("name", "karan");
    startActivityForResult(intent, 0);


  4. In SecondActivity, add a button with the caption ‘NAVIGATE BACK’.
  5. On click of the button display the text passed from MainActivity.
  6. if (getIntent().hasExtra("name")) {
      String name = getIntent().getExtras().getString("name");
      Toast.makeText(SecondActivity.this, name, Toast.LENGTH_LONG).show();
    }


    Picture showing how navigation is done from one screen to other using intent
    Click to Enlarge

  7. On click of ‘NAVIGATE BACK’, add the following code
  8. @Override
    public void finish() {
      super.finish();
    }
    
    public void NavigateBack(View view) {
      Intent intent = new Intent();
      intent.putExtra("name", "Karan-Return value");
      setResult(RESULT_OK, intent);
    
      finish();
    }


  9. In the MainActivity, add the following code
  10. @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
      if (data != null) {
        if (data.hasExtra("name")) {
          Toast.makeText(this, data.getExtras().getString("name"), Toast.LENGTH_LONG).show();
        }
      }
    }




Picture showing how the screen is navigated back using intent
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, November 29, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250