I have a class that extends AppCompatActivity. Within this activity I do two different calls to two startActivityForResult methods which are hooked to two button listeners. The first one calls a camera intent like so:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and the second one calls another AppCompatActivity which holds a Google Map to wit:
Intent getLatLongIntent = new Intent(Form.this, MapsLatLongActivity.class);
startActivityForResult(getLatLongIntent, LATLONG_REQUEST);
The first startActivityForResult works fine and I can manipulate the response from the camera intent in the onActivityResult method. What is puzzling is that the same onActivityResult does not get triggered when I close the child activity of the second call using this code:
Intent intent = new Intent();
intent.putExtra("brdgHouseLat", latitude);
intent.putExtra("brdgHouseLong", longitude);
setResult(RESULT_OK, intent);
finish();
Below is my code for the onActivityResult method:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
himgres.setImageBitmap(photo);
} else if (requestCode == LATLONG_REQUEST && resultCode == Activity.RESULT_OK) {
latitude = data.getDoubleExtra("brdgHouseLat", 0);
longitude = data.getDoubleExtra("brdgHouseLong", 0);
Log.v(TAG, "and form has a lat = " + latitude);
Log.v(TAG, "and a long = " + longitude);
}
}
Needless to say I have goggled for solutions on this and have checked into my manifest (I haven't set any flags); fragments (no fragments here), etc.
Am starting to think that maybe SharedPreferences will be a better option but am just puzzled of the inconsistency of the responses. Any help will be appreciated
=========================================================================
Here are the three methods of the second activity relevant to this question:
#Override
public void onBackPressed() {
super.onBackPressed();
packLatLong();
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home: {
packLatLong();
}
}
return (super.onOptionsItemSelected(menuItem));
}
private void packLatLong() {
if (latitude != 0 && longitude != 0) {
Log.v(TAG, "packing this lat = " + latitude);
Log.v(TAG, "packing this long = " + longitude);
Intent intent = new Intent();
intent.putExtra("brdgHouseLat", latitude);
intent.putExtra("brdgHouseLong", longitude);
setResult(RESULT_OK, intent);
finish();
}
}
Please note that pressing either the back button as well as the home button in the action bar triggers the packLatLong method
I ended up solving this problem with some hints from #Pavneet_Singh:
Here is the solution:
In the method:
#Override
public void onBackPressed() {
super.onBackPressed();
packLatLong();
}
remove the call to super as it always returns a RESULT_CANCEL even if you set it to RESULT_OK.
This answer helped me on this -- https://stackoverflow.com/a/35241952/1637525.
I also changed
setResult(RESULT_OK, intent);
to
setResult(Activity.RESULT_OK, intent);
Related
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.
I must be doing something very silly, but even after a whole day, I cant call onActivityResult on MainActivity from another activity.
In my AuxActivity, I have
adapter.setOnItemClickListener(new CityListAdapter.ClickListener() {
#Override
public void onItemClick(View v, int position) {
City city =adapter.getCityAtPosition(position);
// Toast.makeText(getApplicationContext(),
// city.getCity()+"\n"+city.getLatitude()+"\n"+city.getLongitude(),
// Toast.LENGTH_LONG).show();
Double Lat = city.getLatitude();
Double Long = city.getLongitude();
Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
mainIntent.putExtra("Lat", Lat);
mainIntent.putExtra("Long", Long);
mainIntent.putExtra("DbResultCode", Db_ACTIVITY_REQUEST_CODE);
startActivityForResult(mainIntent, Db_ACTIVITY_REQUEST_CODE);
finish();
}
});
In MainActivity, I am doing
// Inside onCreate
// Check Intent from Db
Intent intent = getIntent();
if (intent != null) {
Lat = intent.getDoubleExtra("Lat", 0.0);
Long = intent.getDoubleExtra("Long", 0.0);
DbResultStat = intent.getIntExtra("DbResultCode", 0);
}
I am getting values of Lat and Long properly here. But, then,
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(this, ""+requestCode, Toast.LENGTH_LONG).show();
if (requestCode == DbActivity.Db_ACTIVITY_REQUEST_CODE){
if (resultCode==RESULT_OK){
setupViewPager();
}
}
This part is never called. I am still learning android, using the codelabs. So, anything new is giving me a lot of headache.
What I am doing wrong here?
Try these two steps:-
1)Pass Context of Main Activity instead of Application:
Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
to:
Intent mainIntent = new Intent(this, MainActivity.class);
Then Run
2)Remove Super from override method of onActivityResult:
super.onActivityResult(requestCode, resultCode, data);
Then Run
Hope it Helps
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"
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);
I'm building an application where the first Activity starts another one by startActivityByResult. After some setting is done, I need to send the setting result back.
So I override the second Activity's onPause() method, I get the intent, putExra, and send it back through setResult().
Back to the first Activity. onActivityResult has definitely been called. I got the resultCode set before, but the intent data is null. I can't figure out what's wrong.
Here's my code:
The first Activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("page1", requestCode + "_");
Log.e("page1", resultCode + "_");
Log.e("page1", (data == null) + "_");
// if ((requestCode == 1) && (data != null)) {
if (data != null) {
String size = data.getStringExtra("size");
Log.e("switch", size + "_");
switch (size.charAt(0)) {
case '1': {
text.setTextSize(10);
}
break;
case '2': {
text.setTextSize(20);
}
break;
case '3': {
text.setTextSize(30);
}
break;
}
}
}
My second Activity
#Override
protected void onPause() {
Intent intent = getIntent();
Log.e("prefs", (intent == null) + "_");
intent.putExtra("size", size);
setResult(3, intent);
super.onPause();
}
I've tested in LogCat. In the second Activity. The intent about to be sent is definitely not null. But when it goes to the first Activity. Null just returned. This is driving me really crazy.
Problem with your code is in String size = data.getStringExtra("size"); this line.
You should change it with String size = data.getExtras.getString("size");
In your first activity:
Intent intent = new Intent(context,SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);
And in your second activity make a button called SAVE and in its listener;
Intent result = new Intent();
Bundle bundle = new Bundle();
bundle.putString("keyName", "KeyValue");
result.putExtras(bundle);
setResult(RESULT_OK,result);
finish();
And again in your first activity's onActivityresult method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode==RESULT_OK){
if(requestCode == REQUEST_CODE){
Log.d("Activity Result", data.getExtras.getString("keyName");
}
}
}
Can you try this.
you want to finish your activity in all the cases in pause manually and in back press automatically so it will be better to save your intent data in onDestroy
#Override
protected void onPause() {
super.onPause();
finish();
}
#Override
public void onDestroy() {
Intent intent = getIntent();
intent.putExtra("size", size);
setResult(3, intent);
super.onDestroy();
}