我需要从Firebase数据库中的节点密码中获取字符串值,以便与用户输入进行比较,但遗憾的是我无法获取该值。这是我的firebase数据库的链接,如下图所示。
这是我的代码:
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("pin_code");
mDatabase.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
@Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
if (rface.equals("") || rface.equals(null)){
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
Pin pin = new Pin(authUserId, userPassword);
mDatabase.child(userId).setValue(pin);
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
Toast.makeText(PinActivity.this,"Invalid PIN code", Toast.LENGTH_SHORT).show();
return;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
这是json代码
{
"pin_code" : {
"id" : "TQYTo1NHNnhPJnOxhe1Vok3U6ic2",
"pincode" : "12345"
}
}
答案 0 :(得分:0)
尝试更改此内容:
String rface = (String) dataSnapshot.child("pincode").getValue();
对此:
String rface = (String) dataSnapshot.child("pincode").getValue(String.class);
答案 1 :(得分:0)
此FirebaseDatabase.getInstance().getReference("pin_code")
未引用您要查找的节点。您很可能知道 id
属性,在这种情况下,您可以通过以下方式获取节点:
DatabaseReference collection = FirebaseDatabase.getInstance().getReference("p...");
Query query = collection.orderByChild("id").equalTo("TQT...ic2");
query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
@Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String rface = (String) child.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
我所做的改变:
id
属性上创建一个查询。onDataChange
我们添加了一个循环。这是必需的,因为针对Firebase数据库的查询可能会有多个结果。因此dataSnapshot
包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。我们循环dataSnapshot.getChildren()
来处理这些多重结果。如果只有一个节点具有相同的id
,则应考虑更改数据结构以使用id
作为节点的键。所以:
pin_codes
uid1: "pincode1"
uid2: "pincode2"
然后您的代码变得非常简单,因为您不再需要查询用户。您可以直接从路径中读取:
DatabaseReference user = FirebaseDatabase.getInstance().getReference("pin_codes").child("TQT...ic2");
user.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
@Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.getValue();
if (rface.equals(userPassword) && !rface.equals("")){
答案 2 :(得分:0)
使用以下内容:
Object some = dataSnapshot.getValue();
String value = some.toString();