繁体   English   中英

在片段和活动之间使用共享的首选项

[英]Using shared preferences between fragment and activity

我试图在我的第一个活动和第二个活动中固定的片段之间使用共享的偏好。 该代码显示了我到目前为止所做的事情,但是在获取上下文时遇到了问题。 我还认为我正在做的事情行不通,所以只需要一些快速帮助。 谢谢

尝试在空对象引用上调用虚拟方法'android.content.Context android.content.Context.getApplicationContext()'

阅读首选项

 sharedPreferences =  getSharedPreferences("alexcz", MODE_PRIVATE);
 String drawableString = sharedPreferences.getString("PARTICLE_TYPE", "null")

写参考

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_particle_type, container, false);

        white_blur = (ImageButton)view.findViewById(R.id.white_blur);
        green_blur = (ImageButton)view.findViewById(R.id.green_blur);
        orange_blur = (ImageButton)view.findViewById(R.id.orange_blur);
        pink_blur = (ImageButton)view.findViewById(R.id.pink_blur);
        yellow_blur = (ImageButton)view.findViewById(R.id.yellow_blur);
        blue_blur = (ImageButton)view.findViewById(R.id.blue_blur);

        main main = new main();
        Context context = main.getApplicationContext();

        sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE);
        editor = sharedPref.edit();

 editor.putString("PARTICLE_TYPE", "white_blur");

        setOnClickListeners();
        return view;
    }

永远不要这样做: main main = new main(); 而是:

Context context = getActivity().getApplicationContext();

如果您希望访问片段内部的applicationContext 当您使用构造函数初始化Android活动时,一切都搞砸了,只是不要这样做。 参考这个问题

只需替换这些行:

main main = new main();
Context context = main.getApplicationContext();
sharedPref = context.getSharedPreferences("alexcz", main.MODE_PRIVATE);

有:

sharedPref = getActivity().getSharedPreferences("alexcz", getActivity().MODE_PRIVATE);
editor = sharedPref.edit();

getActivity().MODE_PRIVATE将显示警告,提示您通过instance访问static成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM