【问题标题】:NullpointerException on getting the value from share preference from service where i am putting value into it in ActivityNullpointerException 从我在 Activity 中投入价值的服务中获取共享偏好的价值
【发布时间】:2013-01-21 10:50:45
【问题描述】:

我正在尝试将sharepreference 值从一项活动访问到一项服务,但它正在抛出NullPointerException,我尝试了很多但仍然遇到同样的问题,我搜索了许多与此相关的问题并尝试了他们的解决方法,但没有奏效。如果你能在这方面指导我,你会很棒。提前致谢,

这里是代码

我已在我的服务类中将 SharePreferences 定义为

SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor=preferences.edit();   

而且我试图在“我的活动”中将其价值作为

foregroundService.editor.putString(foregroundService.com, data.getComponent().toString());
foregroundService.editor.commit();

再次返回服务类以访问该值

preferences.getString(com, "not available");

请帮忙,谢谢

【问题讨论】:

    标签: android service android-activity nullpointerexception


    【解决方案1】:

    您可以使用以下方法在活动中添加值:

    SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    Editor editor=preferences.edit(); 
    editor.putString(foregroundService.com, data.getComponent().toString());
    editor.commit();
    

    它总是相同的偏好,因为你使用的是默认的

    【讨论】:

      【解决方案2】:

      看看你把名字写成foregroundService.com的那一行

      foregroundService.editor.putString(foregroundService.com, data.getComponent().toString());
      

      而你正试图成为

      preferences.getString(com, "not available");
      

      put 和 get 的名称必须相同。

      把它改成preferences.getString(foregroundService.com, "not available");

      试试看..

      【讨论】:

        【解决方案3】:

        假设 Activity 和 Service 都使用相同的包,因此共享相同的 Context,我认为这与 Service 内部的 Context = null 的事实有关,因为 getApplicationContext() 不是可用。

        解决办法是:

        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(context);
        

        如果上下文在您的服务中不可用,您需要在实例化服务时将其传递给您的服务的 onCreate 函数。

        【讨论】:

        • 嗨@Mat,你的回答对理解它很有帮助。我试图在 getDefaultSharedPreferences 中传递上下文而不是“服务类未启动”错误来了,我现在该怎么办,请帮忙
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 1970-01-01
        • 2020-08-12
        • 1970-01-01
        相关资源
        最近更新 更多