Search code examples
androidandroid-intentandroid-activityintentfilteronactivityresult

Why is onActivityResult() not getting executed?


I'm an experienced java programmer taking my first steps in Android development. My problem is simple, my onActivityResult() is not getting executed in the main activity. Here is what I did.

In the MainActivity's onCreate method,

Intent intent = new Intent(MainActivity.this, NewScreen.class);

startActivityForResult(intent,RESULT_OK);

And I did override the onActivityResult method in MainActivity:

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

    Log.d("Debug", "Received");
}

In NewScreen Activity:

Intent intent = new Intent(NewScreen.this, MainActivity.class);

this.setResult(RESULT_OK,intent);

Log.d("Debug", "Setting the Result");

finish();

My Manifest file:

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".MainActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="NewScreen"></activity>

</application>

Solution

  • In NewScreen activity, try using the default (parameter-less) constructor for the Intent...

    Intent intent = new Intent();
    
    setResult(RESULT_OK,intent);
    
    Log.d("Debug", "Setting the Result");
    
    finish();
    

    EDIT: Also the 'request code' you send to the activity might be better as some value other than RESULT_OK, e.g...

    startActivityForResult(intent, 1234);