首页 > 解决方案 > Android Studio Firebase 如何在 Firebase 实时数据库中插入长列表?

问题描述

我正在尝试使用以下代码在实时数据库中插入一长串产品。该列表有大约 90 种产品,但是当我尝试添加它们时,我得到的产品更少,比如缺少 2-3 种产品。有没有办法插入所有产品?我相信我得到的产品更少,因为我使用的是时间戳。

这是我的代码

DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
String[] productTitles = {length of array is 93};
String[] productQuantities = {length of array is 93};
String[] productIcons = {length of array is 93};
String[] productCategories = {length of array is 93};

        HashMap<String, Object> hashMap = new HashMap();
        hashMap.put("discountAvailable","false");
        hashMap.put("discountNote","");
        hashMap.put("discountPrice","0");
        hashMap.put("isAvailable","Available");
        hashMap.put("isApproved","Approved");
        hashMap.put("productType","Default");
        hashMap.put("originalPrice","");
        hashMap.put("productDescription", "");
        hashMap.put("uid",""+firebaseAuth.getUid());
        String timestamp;
        for (int i = 0; i < productTitles.length; i++) {
            timestamp = "" + System.currentTimeMillis()+1;
            hashMap.put("timestamp", "" + timestamp);
            hashMap.put("productTitle", "" + productTitles[i]);
            hashMap.put("productCategory", "" + productCategories[i]);
            hashMap.put("productQuantity","" + productQuantities[i]);
            hashMap.put("productIcon",""+productIcons[i]);
            hashMap.put("productId",""+timestamp);
            reference.child(firebaseAuth.getUid()).child("Products").child(timestamp).setValue(hashMap);

        }

标签: androidfirebasefirebase-realtime-database

解决方案


您可以用 firebase 密钥替换时间戳。

for (int i = 0; i < productTitles.length; i++) {
        timestamp = "" + System.currentTimeMillis()+1;
        hashMap.put("timestamp", "" + timestamp);
        hashMap.put("productTitle", "" + productTitles[i]);
        hashMap.put("productCategory", "" + productCategories[i]);
        hashMap.put("productQuantity","" + productQuantities[i]);
        hashMap.put("productIcon",""+productIcons[i]);
        hashMap.put("productId",""+timestamp);
        String uniqueID = reference.push().getKey();
        reference.child(firebaseAuth.getUid()).child("Products")
        .child(uniqueID).setValue(hashMap);

    }

我不确定这是否有效。


推荐阅读