Md Anik
Md Anik

Reputation: 71

How to go back to the previous activity by pressing the back button with some data?

I am trying to get some data from the second activity by pressing the back button. But whenever I press the back button, I exit from the app- not going to the previous activity. I attached an image for the back button. Here's my code.

**MainActivity:**

public class MainActivity extends AppCompatActivity {

private TextView myTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView myTextView = (TextView) findViewById(R.id.txtV);

    Button myBtn = (Button)findViewById(R.id.btnF);

    myBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, Second.class);
            activityResultLaunch.launch(intent);
        }
    });


}

ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == 123) {
                    Intent data = result.getData();
                    assert data != null;
                    String myStr = data.getStringExtra("MyData");
                    myTextView.setText(myStr);
                }
            }
        });

}

Second Activity:

public class Second extends AppCompatActivity {

private EditText myEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    myEditText = (EditText) findViewById(R.id.editTextSec);

}

@Override
public void onBackPressed() {
    String data = myEditText.getText().toString();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(123, intent);
    finish();
}

}Back Button

Upvotes: 1

Views: 364

Answers (2)

Md Anik
Md Anik

Reputation: 71

Thanks all for your answers. The problem is solved by removing the silly mistake I made in the mainactivity at line 7 where I declared TextView type two times. I couldn't solve it without your help.

Upvotes: 0

navylover
navylover

Reputation: 13549

The default value of the edit text is null, so input something before pressing back button.

And the safer way is to check its value before using it:

    import android.text.TextUtils;

    Intent data = result.getData();
    String myStr = data.getStringExtra("MyData");
    if (!TextUtils.isEmpty(myStr )) {
        //Do something
    }

Upvotes: 1

Related Questions