Reputation: 61
I am developing a "book an appointment" application for android mobiles which have Users I have a User class for it, with properties userID, email, name, password and phonenumber. And I have different activities which are using it.
I want to store those data in the Sharedpreference
. But something goes wrong, in the storeUserData()
in debug mode, there are all the data in the user
. And in the setUserLoggedIn()
I added to the same preference a boolean
, but somehow it returns false
. And the end the user = null
.... But I call setUserLoggedIn
like this:
private void logUserIn(User returnedUser) {
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
}
So I give it a true
value. What have I missed? How should I get those data from storeUserData
?
Here's the code:
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;
}
Upvotes: 0
Views: 393
Reputation: 537
You are getting wrong key
here. It must be LoggedIn
instead of loggedIn
. So your code should be:
public User getLoggedInUser(){
if(userLocalDatabase.getBoolean("LoggedIn", false) == false){
return null;
}
}
Upvotes: 2