【问题标题】:How to create Cardview with firebase getKey parameter如何使用 firebase getKey 参数创建 Cardview
【发布时间】:2019-07-18 05:31:26
【问题描述】:

我尝试使用 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 函数一起使用....

"列出产品 = items.getValue(List.class);"

提前致谢

【问题讨论】:

  • 当您使用items.getKey() 时发生了什么?你有错误吗?

标签: android firebase firebase-realtime-database cardview


【解决方案1】:

我不确定你想做什么,但要获得每个产品的密钥,你可以使用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);
        }

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    相关资源
    最近更新 更多