2017-01-08 49 views
0

在我的Firebase中,我有一个应用程序的数据库。比方说,这是我的火力地堡JSON:从Firebase获取特定的子女

{ 
    "Users" :{ 
    "User1":{ 
     "City": "Genk" 
    } 
    ,"User2":{ 
     "City": "Hasselt" 
    } 
    ,"User3":{ 
     "City": "Genk" 
    } 
    ,"User4":{ 
     "City": "As" 
    } 
    ,"User5":{ 
     "City": "Genk" 
    } 
    } 
} 

现在,我要的是所有城市用户的ArrayList。这怎么可能?我想使用此ArrayList将居住在城市中的特定用户置于ListView中。

+0

检查此链接[https://firebase.google.com/docs/database/android/lists-of-data #sorting_and_filtering_data](https://firebase.google.com/docs/database/android/lists-of-data#sorting_and_filtering_data)。尤其是在“排序和筛选”部分。它有你想要的一切 – koceeng

+0

@koceeng我读过了,我试过了,但它不起作用。我需要从数据库中的每个孩子那里获取孩子的“城市”,并在ListView中排序 –

+3

听起来好像你已经尝试过某些东西并且无法使其工作。在这种情况下:分享再现问题的最小代码。你更有可能以这种方式获得帮助。 –

回答

0

我建议你从根源创建另一个孩子,如“UsersCity”,这样你就可以调用这个孩子并将其检索到你的列表视图。这是我做的:

String key = mDatabase.child("post").push().getKey(); 
UserPost userPost = new UserPost(author,uid,setemoticon,postData,mDate,latlng); 
Map<String, Object> postValues = userPost.toMap(); 

Map<String, Object> childUpdates = new HashMap<>(); 
       childUpdates.put("/post/" + key,postValues); 
       childUpdates.put("/user-post/" + uid + "/" + key, postValues); 

mDatabase.updateChildren(childUpdates); 

下面是JSON输出为:

{ 
"post" : { 
"-KcGVPpS9CTWPNax61wf" : { 
    "authorName" : "Test 1", 
    "dateCreated" : { 
    "dateCreated" : 1486352395887 
    }, 
    "postDescription" : "sample post", 
    "postEmotion" : 2130837658, 
    "userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1" 
} 
}, 
"user-post" : { 
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : { 
    "-KcGVPpS9CTWPNax61wf" : { 
    "authorName" : "Test 1", 
    "dateCreated" : { 
     "dateCreated" : 1486352395887 
    }, 
    "postDescription" : "sample post", 
    "postEmotion" : 2130837658, 
    "userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1" 
    } 
} 
}, 
//This child node is for users where you'll want to get the $uid to use for creation of other child nodes. 
"users" : { 
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : { 
    "fullname" : "Test 1" 
    } 
} 
} 

我只是一个新手程序员,我知道我的答案是不是最好的,但我希望它可以帮助你解决你的问题。 :)

+0

而且哦! mDatabase变量的值是数据库的主要根。 –

0

只是获取特定节点的数据,其工作非常适合我

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 


     for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { 
      Log.e(TAG, "======="+postSnapshot.child("email").getValue()); 
      Log.e(TAG, "======="+postSnapshot.child("name").getValue()); 
     } 
    } 

    @Override 
    public void onCancelled(DatabaseError error) { 
     // Failed to read value 
     Log.e(TAG, "Failed to read app title value.", error.toException()); 
    } 
});