android 如何从 firebase 数据库中检索特定节点
How to retrieve specific node from firebase database in android
我正在尝试在我的 android 应用程序中使用 Firebase。我正在关注 Saving and retrieving 的文档,
但是教程中使用的示例数据库(Dragon)与我的数据库结构不同。
这是我将数据推送到 firebase 的代码
Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
User userName = new User(socialNum, name, datofBirth, mob1, mob2, healthCondition);
Firebase usersRef = myFirebaseRef.child(name);
Map<String, User> users = new HashMap<String, User>();
users.put(name, userName);
myFirebaseRef.push().setValue(users);
创建这样的数据库格式
{
"android" : {
"saving-data" : {
"fireblog" : {
"-JiRtkpIFLVFNgmNBpMj" : {
"Name" : {
"birthDate" : "100",
"fullName" : "Name",
"healthCond" : "fyhft",
"mob1" : "5855",
"mob2" : "5858",
"socialNumber" : "100"
}
},
"-JiRv0RmHwWVHSOiZXiN" : {
"mast" : {
"birthDate" : "100",
"fullName" : "mast",
"healthCond" : "fyhft",
"mob1" : "5855",
"mob2" : "5858",
"socialNumber" : "100"
}
}
}
}
}
}
我想从 firebase 中检索数据,这样,如果我将 "full Name" 放入我的应用程序搜索框中,它应该检索该特定节点,以便我可以在 Listview 中填充该信息。
这就是我试图检索的方式,
final String Find = find.getText().toString(); //Get text for search edit text box
Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
Query queryRef = myFirebaseRef.orderByChild("fullName");
// System.out.println(dataSnapshot.getKey() + "is" + value.get("socialNumber"));
System.out.println(Find);
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChild) {
System.out.println(dataSnapshot.getValue());
Map<String,Object> value = (Map<String, Object>) dataSnapshot.getValue();
String name1 = String.valueOf(value.get("fullName"));
//System.out.println(dataSnapshot.getKey() + "is" + value.get("fullName").toString());
if (name1.equals(Find)){
System.out.println("Name" + value.get("fullName"));
}
else{
System.out.println("its is null");
}
}
但是它returns所有节点,
02-19 12:18:02.053 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ name
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {Name={socialNumber=100, birthDate=100, fullName=Name, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {mast={socialNumber=100, birthDate=100, fullName=mast, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
我如何检索特定节点,以便如果我输入 fullName = mast,它应该只检索第二个节点以及该节点中的所有字段。
您正在这一行中创建查询:
Query queryRef = myFirebaseRef.orderByChild("fullName");
就像查询按 fullName
值对子节点排序一样。但它还没有限制返回什么子节点。
要限制节点,还得过滤。例如:
Query queryRef = myFirebaseRef.orderByChild("fullName").equalTo("gooner");
您还可以通过使用 startAt
and/or endAt
而不是 equalTo
.
进行过滤来获取一系列节点
正如 Kato 评论的那样:
It looks like there is a superfluous level of children. The data is structured as saving-data/fireblog/<record id>/fluff/...actual data..
. and the fluff layer needs to be removed for those queries to work. You can't query children of children.
这是使用 Hashmap 从 firebase 数据库中检索单个值的另一种方法。
ArrayList<HashMap<String,String>> AllUserscourselist;
String SelectedCourseUserUId;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("User_course_Details").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// emergencyContactsList = new ArrayList<>();
AllUserscourselist = new ArrayList<HashMap<String, String>>();
if(dataSnapshot.exists())
{
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
for (DataSnapshot courseUID : postSnapShot.getChildren()){
UsercourseDetails usercourseDetails = courseUID.getValue(UsercourseDetails.class);
HashMap<String, String> map = new HashMap<String, String>();
String user_id = postSnapShot.getKey();
String course_id = usercourseDetails.getcourse_id();
String course_type = usercourseDetails.getcourse_type();
String course_brand = usercourseDetails.course_brand;
String course_number_plate_url = usercourseDetails.course_number_plate_url;
map.put("user_id", user_id);
map.put("course_id", course_id);
map.put("course_type", course_type);
map.put("course_brand", course_brand);
map.put("course_number_plate_url", course_number_plate_url);
AllUserscourselist.add(map);
}
// AllUserscourselist.add(new UsercourseDetails(usercourseDetails.getcourse_type(),usercourseDetails.getcourse_brand(),usercourseDetails.getcourse_number_plate_url(),usercourseDetails.getcourse_id()));
}
Log.e("AllUserscourselist",""+AllUserscourselist);
courseIdList = new ArrayList<String>();
for (int i = 0; i < AllUserscourselist.size(); i++) {
String course_id_list;
course_id_list = AllUserscourselist.get(i).get("course_id")+" "+ AllUserscourselist.get(i).get("user_id");
courseIdList.add(course_id_list);
}
if(courseIdList.size()>0 && courseIdList!=null) {
for (int i = 0; i < courseIdList.size(); i++) { //used
String arr[] = courseIdList.get(i).split(" ");
if (arr[0].equals(coursenumber)) {
SelectedcourseUserUId = arr[1];
getUserEmergencyContacts(SelectedcourseUserUId);
break;
}
}
}
}else{
// NavigationActivity.this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_in_left);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
如果你想像这样获取特定节点或子节点的值
这里如果你想获取子节点(地址)值。你可以这样获取
FirebaseDatabase database;
DatabaseReference myRef;
myRef = database.getReference();
final DatabaseReference orders_Reference = myRef.child("Order");
orders_Reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(data.getKey().equals("address")){
String orderNumber = data.getValue().toString();
Log.d("Specific Node Value" , orderNumber);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
而不是获取所有节点然后迭代它以根据值获取节点,
只需触发 firebase 提供的查询即可。
private void readAllRequestedFormFromFirebaseDb(){
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("App_DB");
DatabaseReference childRef = ref.child("AllRequest");
Query queryRef =
childRef.orderByChild("fullName").equalTo("Jay");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// getting list
for(DataSnapshot dataSnapshot: snapshot.getChildren()){
QueryFormModel post = dataSnapshot.getValue(QueryFormModel.class);
queryFormModelArrayList.add(post);
/*the above list will have record only
with the provided fullName as Jay*/
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e("DetailsActivity", "onCancelled:readAllSubmittedRequestFromFirebaseDb: "+databaseError );
}
});
}
Click here and find the beautifully written post about this topic
我正在尝试在我的 android 应用程序中使用 Firebase。我正在关注 Saving and retrieving 的文档, 但是教程中使用的示例数据库(Dragon)与我的数据库结构不同。
这是我将数据推送到 firebase 的代码
Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
User userName = new User(socialNum, name, datofBirth, mob1, mob2, healthCondition);
Firebase usersRef = myFirebaseRef.child(name);
Map<String, User> users = new HashMap<String, User>();
users.put(name, userName);
myFirebaseRef.push().setValue(users);
创建这样的数据库格式
{
"android" : {
"saving-data" : {
"fireblog" : {
"-JiRtkpIFLVFNgmNBpMj" : {
"Name" : {
"birthDate" : "100",
"fullName" : "Name",
"healthCond" : "fyhft",
"mob1" : "5855",
"mob2" : "5858",
"socialNumber" : "100"
}
},
"-JiRv0RmHwWVHSOiZXiN" : {
"mast" : {
"birthDate" : "100",
"fullName" : "mast",
"healthCond" : "fyhft",
"mob1" : "5855",
"mob2" : "5858",
"socialNumber" : "100"
}
}
}
}
}
}
我想从 firebase 中检索数据,这样,如果我将 "full Name" 放入我的应用程序搜索框中,它应该检索该特定节点,以便我可以在 Listview 中填充该信息。
这就是我试图检索的方式,
final String Find = find.getText().toString(); //Get text for search edit text box
Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
Query queryRef = myFirebaseRef.orderByChild("fullName");
// System.out.println(dataSnapshot.getKey() + "is" + value.get("socialNumber"));
System.out.println(Find);
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChild) {
System.out.println(dataSnapshot.getValue());
Map<String,Object> value = (Map<String, Object>) dataSnapshot.getValue();
String name1 = String.valueOf(value.get("fullName"));
//System.out.println(dataSnapshot.getKey() + "is" + value.get("fullName").toString());
if (name1.equals(Find)){
System.out.println("Name" + value.get("fullName"));
}
else{
System.out.println("its is null");
}
}
但是它returns所有节点,
02-19 12:18:02.053 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ name
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {Name={socialNumber=100, birthDate=100, fullName=Name, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {mast={socialNumber=100, birthDate=100, fullName=mast, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426 8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
我如何检索特定节点,以便如果我输入 fullName = mast,它应该只检索第二个节点以及该节点中的所有字段。
您正在这一行中创建查询:
Query queryRef = myFirebaseRef.orderByChild("fullName");
就像查询按 fullName
值对子节点排序一样。但它还没有限制返回什么子节点。
要限制节点,还得过滤。例如:
Query queryRef = myFirebaseRef.orderByChild("fullName").equalTo("gooner");
您还可以通过使用 startAt
and/or endAt
而不是 equalTo
.
正如 Kato 评论的那样:
It looks like there is a superfluous level of children. The data is structured as
saving-data/fireblog/<record id>/fluff/...actual data..
. and the fluff layer needs to be removed for those queries to work. You can't query children of children.
这是使用 Hashmap 从 firebase 数据库中检索单个值的另一种方法。
ArrayList<HashMap<String,String>> AllUserscourselist;
String SelectedCourseUserUId;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("User_course_Details").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// emergencyContactsList = new ArrayList<>();
AllUserscourselist = new ArrayList<HashMap<String, String>>();
if(dataSnapshot.exists())
{
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
for (DataSnapshot courseUID : postSnapShot.getChildren()){
UsercourseDetails usercourseDetails = courseUID.getValue(UsercourseDetails.class);
HashMap<String, String> map = new HashMap<String, String>();
String user_id = postSnapShot.getKey();
String course_id = usercourseDetails.getcourse_id();
String course_type = usercourseDetails.getcourse_type();
String course_brand = usercourseDetails.course_brand;
String course_number_plate_url = usercourseDetails.course_number_plate_url;
map.put("user_id", user_id);
map.put("course_id", course_id);
map.put("course_type", course_type);
map.put("course_brand", course_brand);
map.put("course_number_plate_url", course_number_plate_url);
AllUserscourselist.add(map);
}
// AllUserscourselist.add(new UsercourseDetails(usercourseDetails.getcourse_type(),usercourseDetails.getcourse_brand(),usercourseDetails.getcourse_number_plate_url(),usercourseDetails.getcourse_id()));
}
Log.e("AllUserscourselist",""+AllUserscourselist);
courseIdList = new ArrayList<String>();
for (int i = 0; i < AllUserscourselist.size(); i++) {
String course_id_list;
course_id_list = AllUserscourselist.get(i).get("course_id")+" "+ AllUserscourselist.get(i).get("user_id");
courseIdList.add(course_id_list);
}
if(courseIdList.size()>0 && courseIdList!=null) {
for (int i = 0; i < courseIdList.size(); i++) { //used
String arr[] = courseIdList.get(i).split(" ");
if (arr[0].equals(coursenumber)) {
SelectedcourseUserUId = arr[1];
getUserEmergencyContacts(SelectedcourseUserUId);
break;
}
}
}
}else{
// NavigationActivity.this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_in_left);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
如果你想像这样获取特定节点或子节点的值
这里如果你想获取子节点(地址)值。你可以这样获取
FirebaseDatabase database;
DatabaseReference myRef;
myRef = database.getReference();
final DatabaseReference orders_Reference = myRef.child("Order");
orders_Reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if(data.getKey().equals("address")){
String orderNumber = data.getValue().toString();
Log.d("Specific Node Value" , orderNumber);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
而不是获取所有节点然后迭代它以根据值获取节点, 只需触发 firebase 提供的查询即可。
private void readAllRequestedFormFromFirebaseDb(){
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("App_DB");
DatabaseReference childRef = ref.child("AllRequest");
Query queryRef =
childRef.orderByChild("fullName").equalTo("Jay");
queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
// getting list
for(DataSnapshot dataSnapshot: snapshot.getChildren()){
QueryFormModel post = dataSnapshot.getValue(QueryFormModel.class);
queryFormModelArrayList.add(post);
/*the above list will have record only
with the provided fullName as Jay*/
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.e("DetailsActivity", "onCancelled:readAllSubmittedRequestFromFirebaseDb: "+databaseError );
}
});
}
Click here and find the beautifully written post about this topic