I'm querying SharedPreferences
inside a DialogFragment
class called from the onClick
method of another fragment.
I've followed these links, but with no luck: Android SharedPreferences in Fragment, Accessing SharedPreferences through static methods, Static SharedPreferences.
My code is as follows:
QueryPreferences.java:
public class QueryPreferences
{
private static final String PREF_FIRST_RUN = "firstRun";
public static Boolean getFirstRun(Context context)
{
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(PREF_FIRST_RUN, true);
}
public static void setFirstRun(Context context, boolean firstRun)
{
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(PREF_FIRST_RUN, firstRun)
.apply();
}
}
MainFragment.java:
public class MainFragment extends Fragment
{
private static final String DIALOG_CHOOSER = "DialogChooser";
private TextView mTextView;
public static MainFragment newInstance()
{
return new MainFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_main, container, false);
mTextView = (TextView)v.findViewById(R.id.some_text);
mTextView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
FragmentManager manager = getFragmentManager();
SomeDialogFragment dialog = new SomeDialogFragment();
dialog.show(manager, DIALOG_CHOOSER);
}
});
return v;
}
}
SomeDialogFragment:
public class SomeDialogFragment extends DialogFragment
{
private boolean firstRun = QueryPreferences.getFirstRun(context);
}
I do not know what to put in "context
" in the SomeDialogFragment
code snippet above.
Whatever i have tried give me a NullPointerException
.
The things i have tried so far are:
SomeDialogFragment.this.getParentFragment().getActivity()
SomeDialogFragment.this
SomeDialogFragment.this.getActivity()
SomeDialogFragment.this.getActivity().getApplicationContext()
SomeDialogFragment.this.getParentFragment().getActivity().getApplicationContext()
EDIT: I'm calling firstRun
from an inner class.