Search code examples
javaandroidonactivityresult

onActivityResult() is not firing in my Android application


I am at a loss for what the problem is, I have read pretty much every single related question but am stumped as to what my problem could be, the Activity runs fine and it closes on the finish() method, but nothing is done in my MainActivity class. I made sure that my manifest does not call noHistory and singleton activity. I placed a few toasts and a text set but none of them are being called. Here is my code implementation:

On MainActivity:

Intent placeShips = new Intent(this, SetShips.class); //MainActivity.this works too
startActivityForResult(placeShips, RESULT_OK);

.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_OK && resultCode == RESULT_OK) {
        Toast.makeText(MainActivity.this, "worked", Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "worked", Toast.LENGTH_SHORT).show();
    }
    newGame.setText("PLS ");  //these aren't being called either
    toast("PLS");
}

On called Activity: (Please note the buttons work fine)

    setShips.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            setResult(RESULT_OK);
            finish(); //return to main activity, giving intent with stored player information
        }
    });

Further notes; toasts are shown correctly on the setShips button listener, however, nothing passes back to the onActivityResult method, as explained, not even toasts show. Am I missing something else?


Solution

  • It looks like you haven't properly set your request code. You need to do:

    static final int YOUR_CODE = 1; 
    Intent placeShips = new Intent(this, SetShips.class); //MainActivity.this works too
    startActivityForResult(placeShips, YOUR_CODE);
    

    Then you can do:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
        if (requestCode == YOUR_CODE && resultCode == RESULT_OK) {
            Toast.makeText(MainActivity.this, "worked", Toast.LENGTH_SHORT).show();
            Toast.makeText(this, "worked", Toast.LENGTH_SHORT).show();
        }
        newGame.setText("PLS ");  //these aren't being called either
        toast("PLS");
    }