简体   繁体   中英

How to get the data from Firebase realtime database to ListView?

-Quiz
  -MCQ
    -Question
       -1831
         -783444
           -//still got data
         -234567
           -//still got data

Above is my Firebase realtime database and I want only show the 783444 and 234567 to my ListView and clickable to next activity.

Please give some advise to solve my problem. Thank you very much.

To get only those keys, 783444 and 234567 in a ListView , please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Quiz").child("MCQ").child("Question").child("1831");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ArrayList<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();
            list.add(key);
        }
        ListView listView = (ListView) findViewById(R.id.list_view);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //Go to next activity
            }
        });
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM