如何使用firebase getKey参数创建Cardview

问题描述 投票:0回答:1

我尝试使用listAdapter从firebase数据创建cardview。它适用于getValue,但不适用于getKey。任何人都可以帮助我......

        reference = FirebaseDatabase.getInstance().getReference().child("products");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                list = new ArrayList<List>();

                Iterable<DataSnapshot> itemSnapShot = dataSnapshot.getChildren();
                for(DataSnapshot items : itemSnapShot)
                {
                    List products = items.getValue(List.class);
                    list.add(products);
                }
                adapter = new ListAdapter(Stock.this,list);
                recyclerView.setAdapter(adapter);
            }

它有效,但如何在此代码中使用getKey函数....

“List products = items.getValue(List.class);”

提前致谢

android firebase firebase-realtime-database cardview
1个回答
0
投票

我不确定你想做什么,但要获得每个产品的关键,你可以使用getKey()方法完成这项任务,就像这样......

 reference = FirebaseDatabase.getInstance().getReference().child("products");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapShot data : dataSnapshot.getChildren())
            {
                //This key string is key of a child in the database.
                String key = data.getKey(); 

                //Do what do you want here....
            }
        }

并且为了显示数据库中的所有产品都使用此代码。

reference = FirebaseDatabase.getInstance().getReference().child("products");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
           list = new ArrayList<List>();
           for(DataSnapShot data : dataSnapshot.getChildren())
            {
                List products = items.getValue(List.class);
                list.add(products);
                //Do what do you want here....
            }

           adapter = new ListAdapter(Stock.this,list);
           recyclerView.setAdapter(adapter);
        }

希望它能帮到你!

© www.soinside.com 2019 - 2024. All rights reserved.