Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start Activity from preferences.xml and get the result in onActivityResult

It's a complement to this question.

I can launch the Activity but I also need to be able to get the result. How do I do it?

I tried overriding onActivityResult on my PreferencesActivity to no avail.

Am I missing some extra properties in the preferences.xml?

like image 331
Eliseo Soto Avatar asked Mar 03 '12 10:03

Eliseo Soto


People also ask

Which method should you use to start activity and get the result back?

First you use startActivityForResult() with parameters in the first Activity and if you want to send data from the second Activity to first Activity then pass the value using Intent with the setResult() method and get that data inside the onActivityResult() method in the first Activity .

Is start activity for result deprecated?

onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.

What is result code in onActivityResult?

onActivityResult - resultCode is always 0.


2 Answers

The cleanest solution that I know of is to listen to the click on the preference and launch the intent explicitly. This way onActivityResult will be called as usual.

Assuming that your intent-preference is defined in XML you can attach a listener to it like this (where 1234 is a request code for onActivityResult):

Preference pref = (Preference) findPreference("prefKey");
pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
  @Override
  public boolean onPreferenceClick(Preference preference) {
    startActivityForResult(preference.getIntent(), 1234);
    return true;
  }
});
like image 199
Kaarel Avatar answered Sep 20 '22 12:09

Kaarel


Try overriding startActivity() in your PreferencesActivity class and make it call startActivityForResult() instead after checking that the intent is the one we are interested in, similar to the following (with 1234 as the request code):

public class PreferencesActivity {
    // ...

    @Override
    public void startActivity(Intent intent) {
        if (thisIsTheExpected(intent)) {
            super.startActivityForResult(intent, 1234);
        } else {
            super.startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int reqCode, int resCode, Intent data) {
        if (reqCode == 1234) {
            // should be getting called now
        }
    }

    // ...
}

Depending on your needs, this could be simpler compared to adding several OnPreferenceClickListener in your code :)

like image 34
Joe Avatar answered Sep 20 '22 12:09

Joe