Issue
Hello I am implementing Firebase in my Android Project But it seems that the function dataSnapshot is not being initialized It is being underlined red
Here is the Code for my .java
table_user.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(dataSnapshot.child(edtphone.getText().toString()).exists()) {
mDialog.dismiss();
User user = dataSnapshot.child(edtphone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(edtpass.getText().toString())) {
Toast.makeText(signin.this, "Sign In Successful",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(signin.this, "Sign In Failed",
Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(signin.this, "User Not Found",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
Both of my dataSnapshot functions are not working.
I have tried changing it to DataSnapshot but then the .child
is not working
Is there an update for this function or a different syntax to try?
Changing to DataSnapshot returns this error
Non-static method 'child(java.lang.String)' cannot be referenced from a static context
Solution
Your onDataChange() has an argument called snapshot
and not dataSnapshot
, hence that error:
"cannot resolve symbol dataSnapshot"
What you have to do is to change all occurrences of dataSnapshot
with snapshot
:
table_user.addValueEventListener(new ValueEventListener() {
@Override
//👇
public void onDataChange(@NonNull DataSnapshot snapshot) {
//👇
if(snapshot.child(edtphone.getText().toString()).exists()) {
mDialog.dismiss();
//👇
User user = snapshot.child(edtphone.getText().toString()).getValue(User.class);
if (user.getPassword().equals(edtpass.getText().toString())) {
Toast.makeText(signin.this, "Sign In Successful",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(signin.this, "Sign In Failed",
Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(signin.this, "User Not Found",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
The following operation will also not work:
Changing to DataSnapshot returns this error: Non-static method 'child(java.lang.String)' cannot be referenced from a static context
Because the child()
method is an instance method and not a static method.
Answered By - Alex Mamo
Answer Checked By - Senaida (JavaFixing Volunteer)