将字符串(Cookie)保存到SharedPrefs导致NullPointerException

时间:2016-06-20 13:42:13

标签: java android cookies nullpointerexception android-sharedpreferences

我做了一个帮助我处理身份验证的课程(将Cookie保存到SharedPrefs)。

public class Authentication extends Application {

    String PREFS_NAME = "UserData";
    String DEFAULT = "";

    Context context;
    public static SharedPreferences sharedPreferences;
    public static SharedPreferences.Editor editor;
    public static String token;

    public Authentication(Activity context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        token = sharedPreferences.getString("Cookie", DEFAULT);
    }

    //speichert Token in den Shared Preferences
    public static void setToken(String token) {
        Log.d("Cookie", token);
        editor.putString("Cookie", token);
        }
}

当我调用Authentication.setToken(token) - 方法时,我的响应(RegisterActivity)将得到一个NullPointerException:

java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)' on a null object reference

你们有人可以帮助我解决这个问题吗?提前致谢

1 个答案:

答案 0 :(得分:2)

您没有在最明确的情况下注册您的申请。 或者首先使用您的代码创建身份验证 首先在最清楚的地方注册

使用

更改身份验证
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

public class Authentication extends Application {
    String PREFS_NAME = "UserData";
    String DEFAULT = "";
    Context context;
    public static SharedPreferences sharedPreferences;
    public static SharedPreferences.Editor editor;
    public static String token;

    public Authentication() {
        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context  = this;
        sharedPreferences = getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        token = sharedPreferences.getString("Cookie", DEFAULT);
    }

    // speichert Token in den Shared Preferences
    public static void setToken(String token) {
        Log.d("Cookie", token);
        if(editor==null){
            throw new NullPointerException("Register your application "+Authentication.class+" in AndroidManifiest.xml");
        }
        editor.putString("Cookie", token);
    }

}

<强> AndroidManifiest.xml

<application
        android:name="com.android.Authentication"
        android:icon="@mipmap/ic_launcher_home"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.blue"
         >
.
.
.
 <activity.../>
<service.../>

  </application>