开发者

Why is onActivityResult() not getting executed?

开发者 https://www.devze.com 2023-03-15 15:20 出处:网络
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 wha

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>


You used RESULT_OK as request code. The value of RESULT_OK is negative (-1 actually). That's why you didn't receive result from NewScreen activity. If you look into documentation for requestCode argument, it says:

requestCode If >= 0, this code will be returned in onActivityResult() when the activity exits.

So, you should define your non-negative request code and use it for startActivityForResult. Here is the example:

public class MainActivity extends Activity
{

    static final int REQUEST_CODE = 13;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
         //...             

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


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);


Are you sure that its not getting called. Try printing out the result code. If its zero it could mean that the result is being cancelled giving you the illusion that the method is infact doing nothing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号