startActivityForResult resultcode always 0 - android

I'm trying to get edited list back from activity 2 to activity 1.
Here is my code:
public void listDataSms(ArrayList<MySmsLog> stringList) {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(NUMBER_LIST, stringList);
Intent i = new Intent(this, MyCommonListActivity.class);
i.putExtra(WHO_INT, SMS_LOG);
i.putExtras(bundle);
startActivityForResult(i, SMS_LOG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SMS_LOG) {
if (resultCode == RESULT_OK) {
ArrayList<MySmsLog> mySmsLogs = (data.getParcelableArrayListExtra(PICK_SMS_LOG));
mainLog.setSmsLog(mySmsLogs);
}
if (resultCode == RESULT_CANCELED) {
// do something if there is no result
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
Bundle result = new Bundle();
switch (who) {
case SMS_LOG:
result.putParcelableArrayList(MainActivity.PICK_SMS_LOG, mySmsLogList);
break;
}
setResult(RESULT_OK, intent);
intent.putExtras(result);
}
But I never get setSmsLog because resultCode is always 0.
I tried Android onActivityResult is always 0 this but with no result.
Even if I change my condition to if (resultCode == RESULT_CANCELED) {do smth} program ends with NullPointerException.

Assuming that onBackPressed() from your code shown above is from MyCommonListActivity, that is too late to call setResult(). At best, your code might work if you call super.onBackPressed() as the last thing, not the first. The typical solution is to call setResult() and finish() as soon as the user taps on something in a ListView or otherwise chooses the particular item to work with, rather than wait until the user presses BACK.

Try to put super.onBackPressed(); after intent.putExtras(result);

Related

How to make an intent and launch an activity in onActivityResult()?

I am trying to launch an activity after a user has selected a photo. I was trying to do this:
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent selectImageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
selectImageIntent.setType("image/*");
startActivityForResult(selectImageIntent, 1);
Intent goToActivityIntent = new Intent(view.getContext(), SendPhotoChangeActivity.class);
goToActivityIntent.putExtra("email", email);
goToActivityIntent.putExtra("donorEmail", donorEmail);
goToActivityIntent.putExtra("orderId", orderId);
goToActivityIntent.putExtra("uriString", uriString);
view.getContext().startActivity(goToActivityIntent);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
uriString = data.getData().toString();
}
}
But I realised that with this code, the code for launching the activity (SendPhotoChangeActivity) executes before the user selects the image, crashing the app because the uriString variable is null.
I tried simply copy/pasting the code into onActivityResult(), but the view variable (in view.getContext()) was, of course, not recognized in onActivityResult().
I am thinking of simply replacing view.getContext() by getApplicationContext() in onActivityResult(). Is this the right thing to do? If not, please tell me how I can start an activity in onActivityResult().
If you are in Activity then you can just use this as Context
Intent goToActivityIntent = new Intent(this, SendPhotoChangeActivity.class);
If you are in a Fragment then you can obtain Context by calling getContext()
Intent goToActivityIntent = new Intent(getContext(), SendPhotoChangeActivity.class);
And use that code inside onActivityResult() as you were trying to.
set an integer code for the act of selecting a picture like REQUEST_CODE_TAKE_PICTURE so you know that has happened, this works ok in Kotlin, I assume that works as well with java:
if (requestCode == REQUEST_CODE_TAKE_PICTURE && resultCode == Activity.RESULT_OK) {
Intent goToActivityIntent = new Intent(view.getContext(),SendPhotoChangeActivity.class);
goToActivityIntent.putExtra("email", email);
goToActivityIntent.putExtra("donorEmail", donorEmail);
goToActivityIntent.putExtra("orderId", orderId);
goToActivityIntent.putExtra("uriString", uriString);
view.getContext().startActivity(goToActivityIntent);
if (data == null) {
//Display an error
println("error accuered at onActivityResult ")
return
}
Have you tried this simpler one:
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent selectImageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
selectImageIntent.setType("image/*");
startActivityForResult(selectImageIntent, 1);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
uriString = data.getData().toString();
Intent goToActivityIntent = new Intent(view.getContext(), SendPhotoChangeActivity.class);
goToActivityIntent.putExtra("email", email);
goToActivityIntent.putExtra("donorEmail", donorEmail);
goToActivityIntent.putExtra("orderId", orderId);
goToActivityIntent.putExtra("uriString", uriString);
startActivity(goToActivityIntent);
}
}
Just call
startActivity(goToActivityIntent);
to call the activity.
This assumes you are calling it from your activity or fragment. If this doesn't meet your requirements, let me know. There are other ways to implement this.

Activity always returns RESULT_CANCELLED despite manually setting the result as RESULT_OK

I am writing a component that allows user to pick a location based on the place indicated by the location picker. One of the requirements is to send the LatLng object back from the map activity to the activity that called the former. The problem is that returned result code is always RESULT_CANCELLED, despite setting it explicitly to RESULT_OK. Here's the code:
Calling activity:
public void getLocationBtn(View view) {
Intent i = new Intent(this, PickLocationActivity.class);
startActivityForResult(i, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
location = data.getParcelableExtra("location");
Log.d(TAG, "gotLocation: " + location);
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Location not chosen", Toast.LENGTH_SHORT).show();
}
}
}
Called activity:
btnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
centerLatLang = mMap.getProjection().getVisibleRegion().latLngBounds.getCenter();
Button doneBtn = findViewById(R.id.locationPickerDoneBtn);
doneBtn.setEnabled(true);
}
});
}
public void doneBtn(View view) {
Intent returnIntent = new Intent();
returnIntent.putExtra("location", centerLatLang);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
btnFind get the coordinates, doneBtn confirms user's choice and comes back to the previous activity.
I have already tried replacing Intent returnIntent = new Intent(); with getIntent(), but it didn't work; the returned bundle was null.
it happen when your activity is using singleTask launch mode. so i recommand if you have below line in your manifest activity tab please remove it.
android:launchMode="singleInstance"

setResult(<resultCode> , <Intent>) does not work

I'm trying to pass byteArray and just a String from a current activity to a previous fragment.
public void uploadClick (View view) {
//Send results back to previous screen
switch (activity.from) {
case "review" :
if (activity.mCurrentPhotoPath != null && activity.bytes != null) {
Intent reviewReturnIntent = new Intent();
reviewReturnIntent.putExtra(ReviewsFragment.REVIEW_PHOTO_BITMAP, activity.bytes);
reviewReturnIntent.putExtra(ReviewsFragment.REVIEW_PHOTO_PATH, activity.mCurrentPhotoPath);
activity.setResult(Activity.RESULT_OK, reviewReturnIntent);
activity.finish();
}
break;
case "reply" :
break;
case "merchant" :
break;
}
}
Fragment onActivityResult :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REVIEW_REQUEST) {
if (resultCode == getActivity().RESULT_OK) {
if (data != null) {
returnedBitmap = data.getByteArrayExtra(REVIEW_PHOTO_BITMAP);
returnedPhotoPath = data.getStringExtra(REVIEW_PHOTO_PATH);
Bitmap bmp = BitmapFactory.decodeByteArray(returnedBitmap, 0, returnedBitmap.length);
binding.reviewIV.setImageBitmap(bmp);
binding.returnedImageLayout.setVisibility(View.VISIBLE);
}
}
}
}
startActivityForResult call:
public void uploadClick (View view) {
Intent uploadPhotoIntent = new Intent(fragment.getContext(), UploadPhotoActivity.class);
uploadPhotoIntent.putExtra(UploadPhotoActivity.FROM, "review");
fragment.startActivityForResult(uploadPhotoIntent, ReviewsFragment.REVIEW_REQUEST);
}
Every time I try to run the activity.setResult with an intent parameter. The compiler runs that code, but does not finish the activity (therefore I could not return to the previous fragment / activity).
I've added breakpoints and it runs the "setResult" and the "activity.finish()" methods. But it just doesn't seem to destroy the current activity.
Although, after taking out the intent parameter from the "setResult" method, everything works fine, but on the previous fragment I'm getting a null returned from "data".
Example :
activity.setResult(Activity.RESULT_OK);
Been trying to look for answers around the internet, still no luck.
Would really appreciate it , and thanks for reading. :)

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
}
}

What is Intent from onActivityResult Parameters

Here is my first activity code from where I call the second Activity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
startActivityForResult(new Intent("chap.two.Chapter2Activity2"),request_Code);
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_Code) {
if (resultCode == RESULT_OK)
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
And here is a code of chap.two.Chapter2Activity2:
Button n = (Button) findViewById(R.id.btn_OK);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent();
//---get the EditText view---
EditText txt_username =(EditText) findViewById(R.id.txt_username);
//---set the data to pass back---
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
//---closes the activity---
finish();
}
});
here I see that setResult(RESULT_OK, data) has two arguments but
onActivityResult(int requestCode, int resultCode, Intent data) has three and I want know how onActivityResult gets value for third parameter? How it works can anyone tell me? Why isn't this error ?
When you call Activity.startActivityForResult(), you set the requestCode. Later, this request code is needed by onActivityResult() in order to determine what Activity is sending data to it. We don't need to supply requestCode again on setResult() because the requestCode is carried along.
The data is intent data returned from launched intent. We usually use this data when we set extras on the called intent.
Consider this example:
CALL SECOND ACTIVITY
Intent i = new Intent(MainActivity.this, CheckActivity.class);
startActivityForResult(i, REQUEST_CODE_CHECK);
ON SECOND ACTIVITY, SET INTENT RESULT
getIntent().putExtra("TADA", "bla bla bla");
setResult(RESULT_OK, getIntent());
finish();
BACK TO FIRST ACTIVITY, ONACTIVITYRESULT()
if(requestCode == REQUEST_CODE_CHECK && resultCode == RESULT_OK){
text1.setText(data.getExtras().getString("TADA") );
}
There you go. You should now understand what is Intent data and how to set and fetch the value.
Third parameter is Intent, which you sent from the sub-Activity(Second Activity, which is going to finish).
If you want to perform some calculations or fetch some username/password in sub-activity and you want to send the result to the main activity, then you place the data in the intent and will return to the Main activity before finish().
After that you will check in onActivityResult(int, int, Intent) in main activity for the result with Intent parameter.
Example::
MainActivity:
public void onClick(View view) {
Intent i = new Intent(this, subActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("username") && data.hasExtra("password")) {
String username = data.getExtras().getString("username");
String password = data.getExtras().getString("password");
}
}
subActivity::
#Override
public void finish() {
// Create one data intent
Intent data = new Intent();
data.putExtra("username", "Bla bla bla..");
data.putExtra("password", "*****");
setResult(RESULT_OK, data);
super.finish();
}

Categories

Resources