非活动类 NullPointerException 中的 SharedPreferences [英] SharedPreferences in non activity class NullPointerException

查看:83
本文介绍了非活动类 NullPointerException 中的 SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在活动中的 onResume() 的非 activity 类中使用 SharedPreferences,但我收到 NullPointerException在上下文.

I'm trying to use SharedPreferences in a non activity class from onResume() in an activity but I'm getting a NullPointerException on the context.

由于某种原因,我无法在 onResume() 中获取 context.不确定我是否遗漏了什么,但任何帮助将不胜感激.

For some reason I cannot get the context in onResume(). Not sure if I'm missing something, but any help would be appreciated.

onResume() 方法在我的活动中

@Override
protected void onResume() {
    super.onResume();
    // The activity has become visible (it is now "resumed").

    // Check User's Access Token exists and hasn't expired.
    AccountFunctions accountFunctions = new AccountFunctions();

    if (!accountFunctions.validateUserToken(this)) {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }
}

AccountFunctions 类中的validateUserToken(Context context) 方法

public Boolean validateUserToken(Context context) {

    SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
    String accessToken = sharedPref.getString(getString(R.string.user_access_token), null);
    DateTime expiryDate = new DateTime(sharedPref.getLong(getString(R.string.user_expires), 0));

    if (accessToken == null || expiryDate.isBeforeNow()) {
        return false;
    } else {
        return true;
    }
}

错误

java.lang.RuntimeException:无法恢复活动{uk.co.itsstonbury.www.intouch/uk.co.itsstonbury.www.intouch.MainActivity}:java.lang.NullPointerException:尝试调用虚方法'android.content.Contextandroid.content.Context.getApplicationContext()' 在一个空对象上参考

java.lang.RuntimeException: Unable to resume activity {uk.co.itsstonbury.www.intouch/uk.co.itsstonbury.www.intouch.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

推荐答案

replace getString(R.str with context.getString 因为 AccountFunctions类尚未由操作系统创建,因此它没有准备好自己的上下文.

replace getString(R.str with context.getString because AccountFunctions class has not been created by the OS so it doesn't have it's own context ready.

基本上,当 oncreate 函数被操作系统回调调用时,Activity 会获取它的上下文表单应用程序,因为在这种情况下它不会发生,所以 AccountFunctions 对象将没有它自己的上下文

Basically activity gets it's context form application when oncreate function get called by OS callbacks since it's not gonna happen in this case so AccountFunctions object will not have it's own context

这段代码只是假设 AccountFunctions 将通过 intent 正常创建,但在这种情况下,它就像一个简单的类对象,与 Activity 生命周期调用无关.

This code simply assume that AccountFunctions will be created normally through intent but in this case it is like a simple class object which has no connection with activity life-cycle calls.

所以你的代码看起来像

public Boolean validateUserToken(Context context) {

    SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
    String accessToken = sharedPref.getString(context.getString(R.string.user_access_token), null);
    DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));

    if (accessToken == null || expiryDate.isBeforeNow()) {
        return false;
    } else {
        return true;
    }
}

或者你可以直接使用字符串值

or you can use string values directly

    SharedPreferences sharedPref = context.getSharedPreferences("yourkey", Context.MODE_PRIVATE); // This is where the error is thrown

更好的选择是为辅助函数创建一个单独的 Util 类,而不是像

The better option is create a separate Util class for helper function rather like

class Util{

    public static boolean validateUserToken(Context context) {

        SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.user_file_key), Context.MODE_PRIVATE); // This is where the error is thrown
        String accessToken = sharedPref.getString(context.getString(context.R.string.user_access_token), null);
        DateTime expiryDate = new DateTime(sharedPref.getLong(context.getString(R.string.user_expires), 0));

        if (accessToken == null || expiryDate.isBeforeNow()) {
            return false;
        } else {
            return true;
        }
    }
}

从你的活动中称之为

 Util.validateUserToken(this);

这篇关于非活动类 NullPointerException 中的 SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆