不了解如何对Firebase实时数据库中的每个键执行操作

时间:2018-11-26 16:11:42

标签: java android firebase firebase-realtime-database

我试图将所有键获取到值下并为它们生成一个弹出窗口。但是我不知道怎么做。我尝试了很多“ for”语句,但无法弄清楚。 我目前的代码:

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
        final DatabaseReference myRef = database.getReference("Anzeigen");



        // Read from the database
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot childSnapshot:dataSnapshot.getChildren())


 {


        RecyclerView recyclerView = findViewById(R.id.anzeigen_list);
        final List<generater> mList = new ArrayList<>();
        RecyclerView.Adapter adapter = new generater_anzeigen_setter(this,mList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        mList.add(new generater(Name , Was , Preis));



    }    
                }





    }
                @Override
                public void onCancelled(DatabaseError error) {
                    // Failed to read value
                    Log.w(TAG, "Failed to read value.", error.toException());
                }
            });

这是我的数据库:

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试一下:

myRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    final List<generater> mList = new ArrayList<>();
                    for(DataSnapshot ds:dataSnapshot.getChildren()){
                        String name,was,preis;

                        for(DataSnapshot childSnapShot:ds.getChildren()){
                            if(childSnapShot.getKey().equals("Name")){
                                name=childSnapShot.getValue().toString();
                            }
                            if(childSnapShot.getKey().equals("Was")){
                                was=childSnapShot.getValue().toString();
                            }
                            if(childSnapShot.getKey().equals("Preis")){
                                preis=childSnapShot.getValue().toString();
                            }

                        }
                        generater generater = new generater(name , was , preis);
                        mList.add(generater);
                    }
                    RecyclerView recyclerView = findViewById(R.id.anzeigen_list);
                    final List<generater> mList = new ArrayList<>();
                    RecyclerView.Adapter adapter = new generater_anzeigen_setter(this,mList);
                    recyclerView.setAdapter(adapter);
                    recyclerView.setLayoutManager(new LinearLayoutManager(this));
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });