0

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.

user9507446
  • 333
  • 1
  • 3
  • 14
  • I've tried your code and it's working fine, the code inside `if (resultCode == Activity.RESULT_OK)` being called normally, also keep it in your mind, the `startActivityForResult()` only works with activities that are intended to be called that way. If the activity you are calling doesn't explicitly return a result, you will get the default result RESULT_CANCELED as mention is this [answer](https://stackoverflow.com/a/16982498/7954210) – Mouaad Abdelghafour AITALI Dec 31 '19 at 17:55

1 Answers1

0

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"