问题
I have customers data stored in below format in my firebase
database.
{
"fEYfwd8p9oSGAF6iUtXDLkMBCqc2" : { //user id
"-KdLAGG-8VOMd62Noyc8" : { //customer id
"customerCode" : "shi",
"customerLimit" : "2569",
"customerName" : "Shishir"
},
"-KdOraGISFJ6epjWucfh" : { //customer id
//other cust details
}
},
"jxW41BgSNWdRPyWtUkZA2G0eLhf2" : { //user id
"-KdCgJKh6_Rb8MOi-fIj" : {
"customerCode" : "Kau",
"customerLimit" : "800",
"customerName" : "Kaushik"
},
"-KdCgacTYBkThnVWe4sb" : {
//other cust details
},
"-KdCggxld52mq0DsGRjH" : {
//other cust details
},
"-KdChbdoV7nxwZoGLWsY" : {
//other cust details
}
}
}
In my android application am trying to check whether customer code exists before creating other details for customers and below is how am doing it.
DatabaseReference dbRef=FirebaseDatabase.getInstance().getReference("customers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbRef.orderByChild("customerCode").equalTo(code).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (!snapshot.exists()) {
editTextAC.setText("");
editTextAC.setError("Customer code not found in database.");
} else {
//need to get customer id here.
}
}
@Override
public void onCancelled(DatabaseError dbError) {
Toast.makeText(activity, dbError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I am getting data in snapshot in below format.
{
key = jxW41BgSNWasdsaRPsdyaWtUkZA2G0eLhf2,
value = {-KdChbdoV7nfdasxwZoGLWsY = {
customerCode = Ses,
customerLimit = 78888,
customerName = Sheshu
}
}
}
I need to get customer Id from above value
. I tried doing snapshot.getKey()
which retrieves first level key
i.e. jxW41BgSNWasdsaRPsdyaWtUkZA2G0eLhf2
and when I say snapshot.getValue()
which would retrieve value
as string. How would I get customer Id from above?
回答1:
for (DataSnapshot child : snapshot.getChildren()) {
Log.i("TAG", "child key = " + child.getKey());
}
回答2:
DatabaseReference dbRef=FirebaseDatabase.getInstance().getReference("customers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());dbRef.orderByChild("customerCode").equalTo(code).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (!snapshot.exists()) {
editTextAC.setText("");
editTextAC.setError("Customer code not found in database.");
} else {
for (DataSnapshot child : snapshot.getChildren()) {
Log.e("Customer_id",child.getKey());}
}
}
@Override
public void onCancelled(DatabaseError dbError) {
Toast.makeText(activity, dbError.getMessage(), Toast.LENGTH_SHORT).show();
}});
来源:https://stackoverflow.com/questions/42431858/getting-key-within-key-firebase