How to handle request code in Android ActivityResultLauncher api - android

After updating my app to AndroidX I noticed startActivityForResult() is depreciated. I looked through the documentation and found some good explanations, but I'm still confused as to how to handle request codes. I've tried adding the request code param to onActivityResult, but obviously that does not work. This is my old onActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_1) {
fetchTags();
} else if (requestCode == REQUEST_CODE_2) {
if (resultCode == RESULT_CANCELED) {
finish();
}
}
}
Do I need to create separate ActivityResultLaunchers for both request codes?

There is no need of Request Codes in the new API. You launch individual intents and you get results under their own scopes.
Old Way
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
startActivityForResult(intent, 123);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 123) {
doSomeOperations();
}
}
New Way
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
doSomeOperations();
}
}
});
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
someActivityResultLauncher.launch(intent);
}
You can find more info in the documentation
https://developer.android.com/training/basics/intents/result

Related

Android: onActivityResult is not getting called for different resultcodes

I am starting an activity with startActivityForResult like this
#Override
public void onEmptyViewClicked(Calendar time) {
Bundle bundle = new Bundle();
bundle.putSerializable("time",time);
bundle.putInt("fragmentId",1);
Intent intent = new Intent(this,AddEventActivity.class);
intent.putExtras(bundle);
startActivityForResult(intent,1);
}
and in AddEventActivity i add fragments depending on the fragment id.The first fragment add events and second fragment delete events.onAddEvent and onDeleteEvent i setResult with appropriate data like this
#Override
public void onAddEventClicked(Bundle bundle) {
Intent intent = new Intent(this,MainActivity.class);
intent.putExtras(bundle);
setResult(1,intent);
finish();
}
#Override
public void eventDelete(Events event) {
Bundle bundle = new Bundle();
bundle.putSerializable("deleteEvent",event);
Intent newIntent = new Intent(this,MainActivity.class);
newIntent.putExtras(bundle);
setResult(2,newIntent);
finish();
}
OnActivityResult code is something like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == 1 && data != null){
if(requestCode == 1){
}
}else if(resultCode == 2){
}
}
}
Now onActivityResult is getting called onAdding event but not on deleting event.eventDelete method is getting called but it is not triggering onActivityResult.What could be the problem?Thankyou.
UPDATED
I put a debug at first line in onActivityResult but debugger doesn't stop there.
startActivityForResult(intent,1);
here 1 is your requestCode
setResult(1,intent);
here 1 is your resultCode
you are setting same resultcode for Two events
change your onActivityResult to
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) { //add event
if (requestCode == 1) {
if (data != null) {
if (data.getExtras().containsKey("deleteEvent")) {
} else {
}
}
}
} else if (resultCode == 2) { //delete event
//write code
}
}
you should add RESULT_OK and validate this resultCode:
Intent returnIntent = new Intent();
returnIntent.putExtra("returndata");
setResult(Activity.RESULT_OK, returnIntent);
finish();
after this, u need add the validation in your onActivityResult method...
if(requestCode == CODE_REQUEST){
if(resultCode == Activity.RESULT_OK){
//do something here
}{
//catch cancel result
}
}

FragmentActivity onActivityResult data is null

I know there are several questions about this, but I don't found a solution for my problem.
I have ActivityA which extends AppCompatActivity. It starts an ActivityB
Activity A
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("data", data);
startActivityForResult(intent, 1);
....
#Override
protected void onActivityResult(int requestCode, int result, Intent intent) {
super.onActivityResult(requestCode, result, intent);
if (requestCode != 1) { // check code
return;
}
if (intent == null) { // HERE INTENT IS NULL
return;
}
}
Activity B
// code called when an asynctask is done
Intent i = new Intent();
i.putExtra("dataone", "test");
i.putExtra("datatwo", objet);
setResult(RESULT_OK, i);
finish();
I don't understand why intent is null in onActivityResult() method.
Two things. I would refactor your code like the following:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
// example
// String myString = intent.getString("myStringFrom2ndActivity")
}
}
}
and also make sure that you are calling the right RESULT_OK. It should be something like Activity.RESULT_OK.

Wait for activity to finish in non-activity class

I have a method in my application which starts a new Activity which starts the Camera Application. The Camera Application returns a result (picture taken or not taken), and I store this result in the Intent-Bundle.
In the original method I want to read this bundle, which does not work because the activity is not finished yet.
How can I wait for the activity to finish before going on in my method?
Method
#Override
public boolean startChallenge(Context context) {
Intent cam = new Intent(context, CameraIntent.class);
cam.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(cam);
Boolean done = cam.getExtras().get("done"); // << this fails obviously
}
Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAPTURE_IMAGE_CAPTURE_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
intent = getIntent();
if (requestCode == CAPTURE_IMAGE_CAPTURE_CODE) {
if (resultCode == RESULT_OK) {
intent.putExtra("done", true);
} else if (resultCode == RESULT_CANCELED) {
intent.putExtra("done", false);
}
}
finish();
}
I would like to keep the structure of the code because the startChallenge() Method is inherited from a superclass (Challenge) and startChallenge is different from type to type (e.g. there is a challenge where you have to take a picture, another challenge where you have to answer something, and so on). The method gets called in another activity, depending on the type of challenge.
startChallenge should have a reference to the Activity that expects the result back to be able to call startActivityForResult
Method
#Override
public boolean startChallenge(Activity activityB) {// Activity B in which you are expecting this result back.
Intent cam = new Intent(activityB, ActivityA.class);
activityB.startActivityForResult(cam, REQUEST_CODE_OPEN_CAMERA);
}
Activity A
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
intent = getIntent();
if (requestCode == CAPTURE_IMAGE_CAPTURE_CODE) {
if (resultCode == RESULT_OK) {
intent.putExtra("done", true);
} else if (resultCode == RESULT_CANCELED) {
intent.putExtra("done", false);
}
}
setResult(RESULT_OK, intent);
finish();
}
Another approach would be to use LocalBroadcastManager or Otto
Activity A
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_CAPTURE_CODE) {
if (resultCode == RESULT_OK) {
BusProvider.getInstance().post(new ImageCapturedEvent(true));
} else if (resultCode == RESULT_CANCELED) {
BusProvider.getInstance().post(new ImageCapturedEvent(false));
}
}
finish();
}

Get result from activity called with Intent [duplicate]

This question already has answers here:
How to manage startActivityForResult on Android
(14 answers)
Closed 8 years ago.
I am new to android development
I call an intent now how can i get result from called activity
can any one tell me how to perform this task ?
i have called intent like.
Intent I = new Intent (this ,abc.class);
startActivity(i);
thanks
Use startActivityForResult and then override onActivityResult in your FirstActivity.
In FirstActivity
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
Override onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
Log.i("Message is",message);
// logs Testing
}
}
In SecondAcivity
Intent intent=new Intent();
intent.putExtra("MESSAGE","Testing");
setResult(2,intent);
finish();//finishing activity
Reference to the docs:
http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)
Example:
http://www.javatpoint.com/android-startactivityforresult-example
For going to second activity use startActivityForResult in your firstclass
Intent callIntent = new Intent(FirstClass.this, SecondClass.class);
startActivityForResult(callIntent, 1);
then override onActivityResult method in your first class like this
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == 1) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// get values from data
}
} }
In your second class do this for returning back, if you want to send
something to first class. Store this in your intent.
Intent result = new Intent(); setResult(Activity.RESULT_OK, result);
finish();
hi you can get result calling activity
Start activity with startActivityForResult(intent, 0);
add below method in calling activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
// do your task
} else if (resultCode == RESULT_CANCELED) {
// do your task
}
}
}
In your main Class....
static final int CODE_REQUEST = 1; // The request code
....
Intent pickContactIntent = new Intent(MainClass.this, CallingClassName.class);
startActivityForResult(pickContactIntent, CODE_REQUEST);
..........
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
In your calling class
Intent result = new Intent();
setResult(Activity.RESULT_OK, result);
finish()

Why is onActivityResult not called in Android?

When I my app is launched I am showing a splash screen. That page is been shown for 10 sec, running on a thread.
When it switches over to new activity on a result I want o hit a URL in server and I will be getting a return value which I can use for my further implements.
Here is my code:
private final int SPLASH_DISPLAY_LENGHT = 1000;
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Log.e("Handler ","run");
Intent myIntent = new Intent(getApplicationContext(), CaptureActivity.class);
startActivityForResult(myIntent, imgDL);
finish();
}
}, SPLASH_DISPLAY_LENGHT);
public void onActivityResult(int requestCode, int resultCode, final Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == imgDL)
{
Log.e("onActivity Result","");
urlHitMethod("http://XXXXXXXXXXXXXXXXXX.com/banner_scan");
}
}
But here the onActivityResult is not called. How to fix this?
Also, please note than if you base activity (the one calling startActivityForResult) can't use the flag noHitory in the manifest.
If you do so, onActivityResult will never be called.
try this
Intent myIntent = new Intent(activity.this, CaptureActivity.class);
and
#Override
public void onActivityResult(int requestCode, int resultCode, final Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == imgDL)
{
Log.e("onActivity Result","");
urlHitMethod("http://XXXXXXXXXXXXXXXXXX.com/banner_scan");
}
if(resultCode==RESULT_OK)
{
Log.e("onActivity Result","come in onactivity result ok");
}
else
{
Log.e("onActivity Result","come in onactivity result with error");
}
}
If you are using onActivityResult, then you should not finish the activity when starting with intent otherwise it will crash the app.
Thanks.
In the CaptureActivity.class you have to set the result and then check in the onActivityResult in the First Activity the result code
In the CaptureActivity.class it should be like the following
Intent in = new Intent();
setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
finish();

Categories

Resources