Reputation: 91
I am trying to get user details from firebase once login task successful. like username, userphone number etc. so these details I want to store in sharedpreference variable. so that I can use these variables throughout the app. but when I try to save and access from outside its throwing null.
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
FirebaseUser user = task.getResult().getUser();
user_tbl.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user1=null;
//Check if user not exist in database
if (dataSnapshot.child(user.getUid()).exists()) {
user1 = dataSnapshot.child(user.getUid()).getValue(User.class);
// user_tbl.removeEventListener(this);
}
editor.putString("username", user1.getUserName());
editor.apply();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
editor.putString("logged", "logged");
editor.putString("email",email);
editor.commit();
Upvotes: 0
Views: 88
Reputation: 15423
Querying to firebase
is asynchronous operation, so you have to wail till finish the operation to get correct data. Besides this you already commit the current editor outside of onDataChange
. So, you have to initiate the editor again inside onDataChange
to work it out. Check below:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user1=null;
//Check if user not exist in database
if (dataSnapshot.child(user.getUid()).exists()) {
user1 = dataSnapshot.child(user.getUid()).getValue(User.class);
// user_tbl.removeEventListener(this);
}
SharedPreferences.Editor editor2 = settings.edit();
editor2.putString("username", user1.getUserName());
editor2.apply();
}
Upvotes: 2
Reputation: 69
Make your SharedPreferences settings as static and you can easily access anywhere between any activity and fragment that will be one of the best way to do it
public static SharedPreference settings ;
Then use it further and I hope this have helped you.
Upvotes: 0