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?
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 .
onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.
onActivityResult - resultCode is always 0.
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;
}
});
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With