1

I have some trouble working with SharedPreferences in DialogFragment. And I keep getting NullPointerException in line sharedPreferences = getActivity().getSharedPreferences("pref", 0);. Here is may basic code.

public class ADialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
    SharedPreferences sharedPreferences;
    public ADialogFragment(int a) {
        sharedPreferences = getActivity().getSharedPreferences("pref", 0);
        if (a == 0) {
            saveToPref(0);
        } else if (a == 1) {
            saveToPref(1);
        } else saveToPref(2);
    }
    private void saveToPref(int itemInt) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt(getString(R.string.item), itemInt);
        editor.commit();
    }
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    ...
    }
}

How can i fix it?

2
  • please learn fragments lifecycle ... you cennot get activity when fragment is not attached to it ...
    – Selvin
    Oct 20, 2015 at 13:54
  • can you post the stacktrace. it makes it easier for the rest to answer.
    – shreyas
    Oct 20, 2015 at 13:54

2 Answers 2

4

You are calling getActivity() too early in fragment constructor and it returns null. A fragment is only attached to an activity in onAttach() or later in the fragment lifecycle.

Move the code that needs shared preferences to a later phase in the lifecycle.

Also note that fragments should not have constructors that take arguments. Use setArguments() to pass in parameters to fragments.

1
  • Thank you for the detailed and informative answer. I`ll try your advices. Oct 20, 2015 at 14:01
0

The method getSharedPreferences is a method of the Context object, so just calling getSharedPreferences from a Fragment will not work.

So you need to do it like below

sharedPreferences = this.getActivity().getSharedPreferences("pref", 0);
2
  • And it still not working. Oct 20, 2015 at 13:56
  • @Selvin : May be you are over smart and i am not.
    – KishuDroid
    Oct 21, 2015 at 4:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.