在android中的片段内显示MODE_PRIVATE的错误

时间:2016-07-11 13:24:16

标签: android android-fragments

在onCreateView

中使用MODE_PRIVATE for sharedPreferences时显示错误
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View layout = inflater.inflate(R.layout.activity_package_categories, container, false);
    SharedPreferences pref = getActivity().getSharedPreferences("PackageType", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString("package_categories_id", position);
    editor.commit();
    return layout;
    }

2 个答案:

答案 0 :(得分:1)

您应该像Context.MODE_PRIVATE一样使用它。

 @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.activity_package_categories, container, false);
        SharedPreferences pref = getActivity().getSharedPreferences("PackageType", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("package_categories_id", position);
        editor.commit();
        return layout;
        }

答案 1 :(得分:0)

在代码中添加上下文,如:

SharedPreferences pref = getActivity()。getSharedPreferences(“PackageType”,Context.MODE_PRIVATE);