简体   繁体   English

从共享首选项中获取值时获取 NullPointerException

[英]Getting NullPointerException while fetching value from shared preference

I'm trying to get the value stored in Shared Preference else return default value.我正在尝试获取存储在 Shared Preference 中的值,否则返回默认值。 Here is my code:这是我的代码:

Long count = SharedPref.getSdkInfo(context, "count");

This line is in onCreate.此行在 onCreate 中。

public static Long getSdkInfo(Context context,String key){
    SharedPreferences sharedPref = context.getSharedPreferences(ApiConstant.SDK_INFO, 0);
    Long data = sharedPref.getLong(key, 0L);
    return data;
}

getSdkInfo method is in different class called SharedPref. getSdkInfo 方法位于不同的 class 中,称为 SharedPref。 Here key contains a string value which is also used while saving value in shared preference.这里的 key 包含一个字符串值,在共享首选项中保存值时也会使用该值。

Here is the error:这是错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.viral.snapminttracker/com.viral.snapminttrackersdk.SendDataActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I have tried many examples but none worked and not able to identify mistake.我尝试了很多示例,但没有一个有效并且无法识别错误。 Please help.请帮忙。 Thanks谢谢

No, the link provided is just an explaination why nullPointerException occurs, I have posted my code, which seems to be correct but still getting the error.不,提供的链接只是解释为什么会发生 nullPointerException,我已经发布了我的代码,这似乎是正确的,但仍然出现错误。 I'm asking if it has any mistake then please point it out请问一下有没有错误请指出

Where does your "context" variable comes from?您的“上下文”变量来自哪里? Be sure that it isn't null.确保它不是 null。

If, as you say, it is in the OnCreate method of your activity, you can change the line as follows:如果如您所说,它在您的活动的 OnCreate 方法中,您可以按如下方式更改该行:

Long count = SharedPref.getSdkInfo(this, "count");

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

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