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 Answers2

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.

laalto
  • 150,114
  • 66
  • 286
  • 303
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);
KishuDroid
  • 5,411
  • 4
  • 30
  • 47