2017-01-08 48 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()); 
    } 
});