Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any recommendations for request codes values in Android?

Tags:

android

Now I am using random numbers for request codes. So, every time I add new activity for startActivityForResult I need to check all other such activities to avoid collisions. May be there are any practices for defining values, non-collidable by design? What do you think?

like image 986
darja Avatar asked Nov 01 '12 14:11

darja


People also ask

What are request codes in Android?

The request code is any int value. The request code identifies the return result when the result arrives. ( You can call startActivityForResult more than once before you get any results. When results arrive, you use the request code to distinguish one result from another.

How do I use registerForActivityResult?

registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you'll use to launch the other activity. An ActivityResultContract defines the input type needed to produce a result along with the output type of the result.


2 Answers

Actually you don't need to check all your Activities and it doesn't matter much if you've the same values in different Activities.

The idea for the request codes is that you, in your Activity X, in onActivityResult() can distinguish between the results of different requests you started with startActivityForResult().

So if you have 3 different startActivityForResult() calls in your activity, you'll need 3 different request codes in order to be able to distinguish between them in onActivityResult() - so you can tell which result belongs to which start. But if you have another Activity Y where you're doing something similar, it doesn't matter when the request codes there are the same like in Activity X.

like image 74
Ridcully Avatar answered Sep 28 '22 01:09

Ridcully


If you still need to check the result of an activity and like the visually polished structures please check this method.

Declare the internal class inside your activity class:

class RequestCode {     static final int IMPORT = 100;     static final int WRITE_PERMISSION = 101; } 

Use a code when starting activity:

startActivityForResult(intent, RequestCode.IMPORT); 

Check the result:

public void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);     if (requestCode == RequestCode.IMPORT && resultCode == RESULT_OK) {         //...     } } 
like image 40
SoftDesigner Avatar answered Sep 28 '22 02:09

SoftDesigner