3

I've got a simple ActivityResultLauncher implementation, where I can select an image from the gallery:

ActivityResultLauncher<Intent> actResLauncher;
actResLauncher = registerForActivityResult(   new ActivityResultContracts.StartActivityForResult(),this);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
actResLauncher.launch(intent);

And the result:

@Override
public void onActivityResult(ActivityResult  result) {
    if(result.getResultCode()== Activity.RESULT_OK){

    }
}

The issue is with this code is that I rely on the predefined Resultcodes like Activity.RESULT_OK or Activity.RESULT_CANCELED. Is there a way to pass custom Requestcodes when launching the intent?

Jenej Fjrjdn
  • 337
  • 2
  • 13

1 Answers1

8

First of all, you do not need onActivityResult(). That way was old. You now have launchers for specific purposes. So no more request codes You now do it like below. Create a function like this:

ActivityResultLauncher<String> imageActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.GetContent(),
            uri -> 
               //do something with uri
            });

And then wherever you want to launch this, just write:

imageActivityResultLauncher.launch("image/*");

For more details refer to this stackoverflow answer https://stackoverflow.com/a/63654043/12555686

Simran Sharma
  • 852
  • 7
  • 16
  • 1
    How would i handle cancel events in that way or lets say in otjer words, how do you from which intent u receive the uri? with custom result code(s) u would now the result origin, or am i missing something? – Jenej Fjrjdn Aug 17 '21 at 23:30
  • This lets you have a activity result for everytime you launch – Simran Sharma Aug 18 '21 at 00:07
  • So its specific. If you had another launcher you'll create another launcher function like this. This one is specific to one launch i.e. image one – Simran Sharma Aug 18 '21 at 00:09
  • You'll have a launcher function specific for that one launch so no more request codes. If you want to startactivityresult for another thing, create another function like that – Simran Sharma Aug 18 '21 at 00:14
  • I have also made edits to my answer. Please refer that link – Simran Sharma Aug 18 '21 at 00:21
  • 1
    so the answer is that it's not possible to pass request codes, as i need to create an own listener for each intent i want to launch? :/ – Jenej Fjrjdn Aug 18 '21 at 01:11
  • In this approach how should I pass the IP address I want the file be uploaded to and is specific for each file?? – AKTanara Sep 18 '22 at 04:16