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

Time:01-11

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

CodePudding user response:

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
    }

CodePudding user response:

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.

  •  Tags:  
  • Related