Search code examples
androidandroid-intentonbackpressed

How to send data by click back button?


I'm using two activities, MainActivity & SubActivity.

MainActivity.class

public class MainActivity extends AppCompatActivity {
    Button button;

    @Override
    protected void onCreate() {
        ...
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sub = new Intent(this, SubActivity.class);
                sub.putExtra("name", "a");
                startActivity(sub);
            }
        }
    }
}

SubActivity

public class SubActivity extends AppCompatActivity {
    EditText text;
    @Override
    protected void onCreate() {
        ...
        text.setText(getIntent().getStringExtra("name"));
    }

    @Override
    public void onBackPressed() {
       super.onBackPressed();
    }
}

In this case, if I change the text in EditText in SubActivity, I want to send changed text data to MainActivity when back button pressed in SubActivity(It means SubActivity onDestroy()). I don't want to make the second MainActivity like this in SubActivity.

@Override
public void onBackPressed() {
    Intent intent = new Intent (this, MainActivity.class);
    intent.putExtra("name", text.getText().toString());
    startActivity(intent);
}

Is there any way to send text data when SubActivity removed from the activity stack?


Solution

  •   public class MainActivity extends AppCompatActivity {
          Button button;
    
         @Override
         protected void onCreate() {
          ...
           button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                   Intent sub = new Intent(this, SubActivity.class);
                  sub.putExtra("name", "a");
                  startActivityForResult(sub , 2);
            }
        }
    }
    @Override  
       protected void onActivityResult(int requestCode, int resultCode, Intent data)  
       {  
                 super.onActivityResult(requestCode, resultCode, data);  
                  // check if the request code is same as what is passed  here it is 2  
                   if(requestCode==2)  
                         {  
                            String message=data.getStringExtra("name");   
                            textView1.setText(message);  
                         }  
       }  
    }
    

    And

          @Override
           public void onBackPressed() {
            Intent intent = new Intent (this, MainActivity.class);
            intent.putExtra("name", text.getText().toString());
            setResult(2,intent);  
        }