Search code examples
androidandroid-intentandroid-activitystartactivityforresult

Using startActivityForResult, how to get requestCode in child activity?


I have four activities, say A, B, C and D. My situation is A will start the activity B by startActivityForResult.

startActivityForResult(new Intent(this,B.class),ONE);

In another situation I will start activity B with a different request code, like:

 startActivityForResult(new Intent(this,B.class),TWO);

In B, I need to call C or D depending on requestCode. I.e if ONE need to start C else D.
So I need to know how to check the requestCode in the child Activity (B here).
In other words, I want to get the request code that Activity B was started with.


Solution

  • You can pass request code by put extra.

    intent.putExtra("requestCode", requestCode);   
    

    Or if you have used startActivityForResult many times, then better than editing each, you can override the startActivityForResult in your Activity, add you code there like this

    @Override
        public void startActivityForResult(Intent intent, int requestCode) {
            intent.putExtra("requestCode", requestCode);
            super.startActivityForResult(intent, requestCode);
        }
    

    So there is no need to edit all your startActivityForResult
    Hope it helped you