Boron
Boron

Reputation: 129

Android firebase - show specific data

I'm trying to create a Firebase Realtime database project in which the data stored is either type A or type B, etc. This is how it looks like on the console:

Firebase Database

enter image description here

The user can then add more posts, of which are saved to the database then displayed on a ListView.

My Code

final DatabaseReference room = FirebaseDatabase.getInstance().getReference().getRoot();

    chatRoomAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, chatList);
    lvChatRoom.setAdapter(chatRoomAdapter);

    btnAddChatRoomMa.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            strChatRoomName = etChatRoom.getText().toString();
            etChatRoom.setText("");

            Map<String, Object> chatMap = new HashMap<>();
            chatMap.put(strChatRoomName + " -TYPEA", "");
            room.updateChildren(chatMap);
        }
    });

    room.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterator iterator = dataSnapshot.getChildren().iterator();
            Set<String> set = new HashSet<>();

            while (iterator.hasNext()) {
                set.add(((DataSnapshot) iterator.next()).getKey());
            }
            chatList.clear();
            chatList.addAll(set);
            chatRoomAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I only want to show for instance, TYPEA (on the database), without displaying the rest. How can I achieve this?

Upvotes: 1

Views: 157

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138944

If you want to display only the value of the property TYPEA, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("fruit-TYPEA");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String fruitTYPEA = dataSnapshot.getValue(String.class);
        Log.d("TAG", fruitTYPEA);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);

The output will be: orange.

Upvotes: 1

Related Questions