如何在Firebase Android中获取子名称

时间:2017-09-22 18:46:39

标签: android firebase firebase-realtime-database

我正在尝试获取唯一的子名称,但它始终返回相同的ID,或者它返回我在子项引号中输入的内容。

uid持有“用户”而非进入用户 uid hold "users" instead of traveling into users

我试图在用户下获取子名称,这是长键/字符串: Im trying to get the child name under users which is the long key/string

public class displayUserBooks extends AppCompatActivity {

ListView listViewBooks;
List<existingBooks> existingBookses;
private FirebaseAuth mAuth;
FirebaseDatabase databaseViewbooks = FirebaseDatabase.getInstance();
DatabaseReference myRef = databaseViewbooks.getReference("Books");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_user_books);
    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    listViewBooks= (ListView) findViewById(R.id.listViewBooks);
    existingBookses = new ArrayList<>();


}
@Override
protected void onStart() {
    super.onStart();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            checkBooks(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

private void checkBooks(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();
        String uid=ds.child("users").getKey();
        existingBooks eBooks = new existingBooks();
        eBooks = ds.getValue(existingBooks.class);
         //   if(user.getUid().equals(uid))
            existingBookses.add(eBooks);
    }

    Booklist adapter = new Booklist(displayUserBooks.this,existingBookses);
    listViewBooks.setAdapter(adapter);
}}

1 个答案:

答案 0 :(得分:0)

enter image description here根本原因很可能是构造对子节点的引用。它可能被定义为太深&#34;。请参考数据库树的分层图片的快照,以及下面的工作代码部分。在侦听器内部,它进入每个用户的数据(由用户ID定义):

FirebaseDatabase frDb = FirebaseDatabase.getInstance();
        DatabaseReference frDbRef = frDb.getReference("apps/gastracking").child("users").child(mAuth.getCurrentUser().getUid());
        ChildEventListener chEvLst = frDbRef.addChildEventListener(new ChildEventListener() {
            ArrayList<RawReport> listOfRawreports = new ArrayList<RawReport>();

            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                if (dataSnapshot.getChildrenCount() > 0) {
                    for (DataSnapshot ds1 : dataSnapshot.getChildren()) 

//<...... Put your code here.....>

}

} }

数据库节点的层次结构:遗憾的是我无法添加平面快照 - 所以请参阅我答案开头的链接。