【问题标题】:Attempt to invoke virtual method 'Context.getSharedPreferences()' on a null object reference尝试在空对象引用上调用虚拟方法“Context.getSharedPreferences()”
【发布时间】:2020-08-29 16:19:30
【问题描述】:

我尝试从我的应用程序中的片段访问我的共享首选项,如下所示:

SharedPreferences sp_app_prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), MODE_PRIVATE);

String path = sp_app_prefs.getString("path", "");

但我收到 NullPointerException:

Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

我真的不明白为什么,这对我来说没有意义。 从活动中调用此共享首选项完全可以。 我错过了什么?

这里是完整的字符串方法:

public String getFilePath(int i) {

        File filePath;


        SharedPreferences sp_app_prefs = getActivity().getSharedPreferences(getActivity().getPackageName(), MODE_PRIVATE);
        String path = sp_app_prefs.getString("path", "");

        filePath = new File(path);


    }


    return String.valueOf(filePath);
}

希望有人可以帮助我

【问题讨论】:

  • 代码对我来说看起来不错。看起来启动片段的活动给出了一个空上下文。你能分享一下你是如何从活动中启动这个片段的吗?
  • 您在 Fragment 生命周期的哪个位置调用 getFilePath()

标签: java android nullpointerexception sharedpreferences


【解决方案1】:

虽然你的问题是模棱两可的。 但我猜你正在将代码放在 onCreateView() 方法体中。 相反,您应该将代码放在 onViewCreated() 方法体中。

在 onViewCreated() 方法中使用以下代码...

    SharedPreferences sharedPreferences = getContext().getSharedPreferences("filename", MODE_PRIVATE);
        SharedPreferences.Editor editor=  sharedPreferences.edit();

        editor.putString("key", "value");
        editor.apply();

        String text = sharedPreferences.getString("key", null);

        Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();

【讨论】:

  • 我从片段中的 String 方法调用它。查看已编辑的问题
猜你喜欢
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
  • 2019-05-10
  • 2015-06-26
  • 2017-01-10
  • 1970-01-01
相关资源
最近更新 更多