I want to get the points and show to the owner of that account when he is logged in I tried reading firebase documentation but I couldn't made it here is the code that I use for assigning the random key and saving the child data
const autoid = firebase.database().ref("user").push().key;
firebase.database().ref("user").child(autoid).set({
Email :email,
Password : password,
Points :"500"
});
I want whenever the user is login get his points from database and show it on their profile.
CodePudding user response:
In your code you are generating a random key and then assigning it to a variable. A better way to do is to get the userId
and assign it as a documentid
and then when retrieving the data use the userId
to get the user's data.
For example, to add the data:
const database = firebase.database();
const user = firebase.auth().currentUser;
if (user !== null) {
// Add user data in collection "users"
database.ref("users").child(user.uid).set({
email :email,
password : password,
points :"500"
})
.then(() => {
console.log("data successfully written!");
})
.catch((error) => {
console.error("Error writing data: ", error);
});
}
Then after the user logins in, you can do the following to retrieve points
:
const database = firebase.database();
const user = firebase.auth().currentUser;
if (user !== null) {
let ref = database.ref("users").child(user.uid);
ref.get().then((snapshot) => {
if (snapshot.exists()) {
console.log("data:", snapshot.val());
console.log(snapshot.val().points);
}
}).catch((error) => {
console.log("Error getting data:", error);
});
}
CodePudding user response:
I can show you how to do it in java just adjust it to your kotlyn code: Define the reference you want to listen to(above the onCreate):
FirebaseDatabase FBDB = FirebaseDatabase.getInstance();
DatabaseReference refUsers=FBDB.getReference("Users");
FirebaseUser user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user=FirebaseAuth.getInstance().getCurrentUser()
refUsers.child(user.getUid()).addListenerForSingleValueEvent(new
ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
customer = dataSnapshot.getValue(Customer.class);
int points = customer.getPoints();
ShowPoints();
});
}
}