Title: How to setResult from within a PreferenceFragment?
Tags: android;android-fragments;preferencefragment
Question: I created a "Settings" activity using the Android Studio wizard. In this activity is the following PreferenceFragment class..
public static class MyPreferenceFragment extends PreferenceFragment
I have some listeners within this PreferenceFragment class and I want to setResult() from within PreferenceFragment class. But I am getting a crash "method not found exception".
How do I access activity/setResult?
Comment: Post your logcat. Which method isn't found?


Here is another answer: Fragments cannot have "results", you should call that in activity.
You could do it like this wherever you want to set result:
Activity activity = getActivity();
//activity in fragment is nullable,
//so null check is suggested to avoid NullPointerException
if (activity != null) {
activity.setResult(RESULT_OK);
activity.finish();

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:06/11/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<android><android-fragments><preferencefragment>', 'Title': 'How to setResult from within a PreferenceFragment?', 'ViewCount': 109, 'id': 50797014, 'user_AboutMe': '', 'user_AccountId': 4744506.0, 'user_DisplayName': 'LAX_DEV', 'user_Reputation': 1961.0, 'user_Views': 159.0, 'user_id': 3836181.0}}