如何从Android中的Firebase中从特定节点检索数据

时间:2018-10-04 18:23:48

标签: android firebase firebase-realtime-database

我正在尝试检索当前用户的CircleMembers下加入的电话号码,但datasnapshot返回null。请帮帮我。哪种方法是检索mycircle下成员的正确方法? 谢谢你。

我的firebase数据库在下面 my firebase

这是我的代码。

 
   userReference = FirebaseDatabase.getInstance().getReference().child( "Users" );
       databaseReference = FirebaseDatabase.getInstance().getReference().child( "Users").child( user.getUid() ).child( "CircleMembers" );
     databaseReference.addListenerForSingleValueEvent( new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

nameList.clear(); if(dataSnapshot.exists()){ for(DataSnapshot dss:dataSnapshot.getChildren()){ String circlememberID = dss.child( "CircleMembers" ).getValue(String.class); userReference.child( circlememberID ) .addListenerForSingleValueEvent( new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { phone = dataSnapshot.getValue( Phone.class ); //fetching phone numbers under Circlemembers (to which circle current user is joined) nameList.add( phone); adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText( getApplicationContext(), databaseError.getMessage(), Toast.LENGTH_SHORT ).show(); } } ); adapter = new MembersAdaptor(nameList,getApplicationContext()); recyclerView.setAdapter( adapter ); adapter.notifyDataSetChanged(); } } else{ Toast.makeText( getApplicationContext(), "No circle", Toast.LENGTH_SHORT ).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } } );

2 个答案:

答案 0 :(得分:0)

进行试用。我认为这是代码应遵循的方式:

ObjectMapper objectMapper = new ObjectMapper();

答案 1 :(得分:0)

要获取CircleMemebers节点下存在的所有电话号码,请使用以下代码:

String phoneNo = FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference circleMemebersRef = rootRef.child("Users").child(phoneNo).child("CircleMemebers");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String phoneNumber = ds.getValue(String.class);
            Log.d(TAG, phoneNumber);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
circleMemebersRef.addListenerForSingleValueEvent(valueEventListener);

您的logcat中的输出将是:

+919212143422
+615325453454