共享首选项编辑器在Null对象参考Android上清除

时间:2019-04-20 14:52:13

标签: java android sharedpreferences

我是Android开发的新手。尝试清除与editor.clear();的登录会话时出现此错误

这是为了使用SharedPreferences.Editor清除登录会话

public void logout() {

        editor.clear();
        editor.commit();
        Intent login = new Intent(context, AccountLoginPage.class);
        context.startActivity(login);
        ((HomePage) context).finish();
    }

完整代码:

public class SessionHandler {

    SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    public Context context;
    int PRIVATE_MODE = 0;

    private static final String PREF_NAME = "LOGIN";
    private static final String LOGIN = "IS_LOGIN";
    public static final String EMAIL = "EMAIL";
    public static final String PASSWORD = "PASSWORD";

    public SessionHandler(Context context) {

        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    }

    public void createSession(String email, String password) {

        editor.putString(LOGIN, "IS_LOGIN");
        editor.putString(EMAIL, email);
        editor.putString(PASSWORD, password);
        editor.apply();
    }

    public boolean isLogin() {

        return sharedPreferences.getBoolean(LOGIN, false);
    }

    public void checkLogin() {

        if (this.isLogin()) {
            Intent login = new Intent(context, AccountLoginPage.class);
            context.startActivity(login);
            ((HomePage) context).finish();
        }
    }

    public HashMap<String, String> getUserDetail(){

        HashMap<String, String> user = new HashMap<>();
        user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
        user.put(PASSWORD, sharedPreferences.getString(PASSWORD, null));

        return user;
    }

    public void logout() {

        editor.clear();
        editor.commit();
        Intent login = new Intent(context, AccountLoginPage.class);
        context.startActivity(login);
        ((HomePage) context).finish();
    }

    public String getEmail() {

        return EMAIL;
    }

}

日志:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.content.SharedPreferences$Editor android.content.SharedPreferences$Editor.clear()' on a null object reference

0 个答案:

没有答案