android sharedpreferences返回null

时间:2016-03-10 19:18:30

标签: android sharedpreferences android-sharedpreferences

我正在为Android手机开发一个“预约预约”应用程序,其中有用户我有一个User类,具有属性userID,email,name,password和phonenumber。我有不同的活动正在使用它。 我想将这些数据存储在Sharedpreference中。但出现问题的是,在调试模式的storeUserData()中,user中存在所有数据。在setUserLoggedIn()我添加了相同的首选项boolean,但不知何故它返回false。结束user = null ....但我这样称setUserLoggedIn

private void logUserIn(User returnedUser) {

    userLocalStore.storeUserData(returnedUser);
    userLocalStore.setUserLoggedIn(true);
}

所以我给它一个true值。我错过了什么?我应该如何从storeUserData获取这些数据? 这是代码:

public void storeUserData(User user){
    SharedPreferences.Editor userLocalDatabaseEditor = userLocalDatabase.edit();
    userLocalDatabaseEditor.putInt("userID", user.userID);
    userLocalDatabaseEditor.putString("name", user.name);
    userLocalDatabaseEditor.putString("email", user.email);
    userLocalDatabaseEditor.putString("password", user.password);
    userLocalDatabaseEditor.putString("phonenumber", user.phonenumber);
    userLocalDatabaseEditor.commit(); //May I should use apply() ?
}

public void setUserLoggedIn(boolean loggedIn){
    SharedPreferences.Editor userLocalDatabaseEditor = userLocalDatabase.edit();
    userLocalDatabase.getString("name", "");
    userLocalDatabaseEditor.putBoolean("LoggedIn", loggedIn);
    userLocalDatabaseEditor.commit();
}

public User getLoggedInUser(){

    if(userLocalDatabase.getBoolean("loggedIn", false) == false){
        return null;
    }

    int userID = userLocalDatabase.getInt("userID", -1);
    String name = userLocalDatabase.getString("name", "");
    String email = userLocalDatabase.getString("email", "");
    String password = userLocalDatabase.getString("password", "");
    String phonenumber = userLocalDatabase.getString("phonenumber", "");
    //String name, String username, String password, String email, String phonenumber
    User user = new User(userID, name, email, password, phonenumber);

    return user;
}

1 个答案:

答案 0 :(得分:2)

你在这里弄错了key。它必须是LoggedIn而不是loggedIn。所以你的代码应该是:

public User getLoggedInUser(){
    if(userLocalDatabase.getBoolean("LoggedIn", false) == false){
        return null;
    }
}