我在另一个片段的SharedPreferences
方法调用的DialogFragment
类中查询onClick
。
我已经关注了这些链接,但没有运气:Android SharedPreferences in Fragment,Accessing SharedPreferences through static methods,Static SharedPreferences。
我的代码如下:
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);
}
我不知道该放什么" context
"在上面的SomeDialogFragment
代码段中。
无论我尝试过什么,都给我一个NullPointerException
。
我到目前为止所尝试的事情是:
SomeDialogFragment.this.getParentFragment().getActivity()
SomeDialogFragment.this
SomeDialogFragment.this.getActivity()
SomeDialogFragment.this.getActivity().getApplicationContext()
SomeDialogFragment.this.getParentFragment().getActivity().getApplicationContext()
编辑:我正在从内部班级调用firstRun
。
答案 0 :(得分:0)
上下文
class SomeDialogFragment extends DialogFragment
{
private boolean firstRun;
@Override
public void onCreate(Bundle savedInstanceState) {
firstRun = QueryPreferences.getFirstRun(getContext());
}
}
答案 1 :(得分:0)
你可以做这样的事情
public class SomeDialogFragment extends DialogFragment
{
private boolean firstRun;
private Context context;
public SomeDialogFragment()
{
context = getActivity();
firstRun = QueryPreferences.getFirstRun(context);
}
}