如果数据库中存在项目,则Android Firestore更新字段值

时间:2019-03-26 16:23:32

标签: android firebase google-cloud-firestore

如果数据库中的值已经存在(例如,我想将Cheetos添加到firestore中,而数据库中的cheetos已经存在),那么我想更新该项目的数量字段。我制作这样的代码,但当值相同时,应用程序仍会添加新项目。我认为系统无法检测到我的'if(task.getResult().getDocuments().size()>0'

这是Firestore数据enter image description here

这是方法代码

private void uploadItem() {
        merk = etMerk.getText().toString().trim();
        type = etType.getText().toString().trim();
        typemerk = merk + " - " + type;
        qty = etQty.getText().toString().trim();
        price = etPrice.getText().toString().trim();
        date = datetime.getText().toString();
        FirebaseFirestore db = FirebaseFirestore.getInstance();

        db.collection("watchlist").whereEqualTo("merk",typemerk)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            if (task.getResult().getDocuments().size()>0){
                                Toast.makeText(AddItemActivity.this, "Barang Sama", Toast.LENGTH_SHORT).show();
                                for (QueryDocumentSnapshot document : task.getResult()) {
                                    Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());
                                    String itemid = document.getString("id");
                                    String date = document.getString("date");
                                    String type = document.getString("type");
                                    String Oldqty = document.getString("qty");
                                    String price = document.getString("price");

                                    int sum= Integer.parseInt(Oldqty) + Integer.parseInt(qty);
                                    String newQty = String.valueOf(sum);

                                    Map<String, Object> newstock = new HashMap<>();
                                    newstock.put("qty",newQty);

                                    FirebaseFirestore database = FirebaseFirestore.getInstance();
                                    database.collection("watchlist")
                                            .document(itemid).update(newstock).addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            Toast.makeText(AddItemActivity.this, "Berhasil Menambahkan jumlah barang", Toast.LENGTH_SHORT).show();
                                            progressBar.setVisibility(View.GONE);
                                            etMerk.setText("");
                                            etType.setText("");
                                            etQty.setText("");
                                            etPrice.setText("");
                                            etMerk.setFocusable(true);
                                        }
                                    }).addOnFailureListener(new OnFailureListener() {
                                                @Override
                                                public void onFailure(@NonNull Exception e) {
                                                    Toast.makeText(AddItemActivity.this, "Gagal Memasukkan stok, silahkan coba lagi.", Toast.LENGTH_SHORT).show();
                                                    progressBar.setVisibility(View.GONE);
                                                }
                                            });

                                }
                            }
                            else {
                                upload();
                            }
                        } else {
                            Log.w(Tag.ITEM, "error getting documents", task.getException());
                        }
                    }
                });
    }

1 个答案:

答案 0 :(得分:0)

此代码有效

private void cutStock() {
        merk = etMerk.getText().toString().trim();
        type = etType.getText().toString().trim();
        typemerk = type + " - " + merk;
        qty = etQty.getText().toString().trim();
        price = etPrice.getText().toString().trim();
        date = datetime.getText().toString();
        final FirebaseFirestore db = FirebaseFirestore.getInstance();
        CollectionReference documentReference = db.collection("watchlist");
        final CollectionReference documentSales = db.collection("sales");


        documentReference.whereEqualTo("type",typemerk)
                .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(Tag.ITEM, document.getId() + "=>" + document.getData());

                        String id = document.getString("id");
                        String oldqty = document.getString("qty");
                        Integer i = Integer.parseInt(oldqty) - Integer.parseInt(qty);
                        String newQty = String.valueOf(i);

                        Map<Object, String> map = new HashMap<>();
                        map.put("qty",newQty);
                        db.collection("watchlist").document(document.getId()).set(map, SetOptions.merge());

                        Map<String, Object> sales = new HashMap<>();
                        sales.put("date", date);
                        sales.put("type", typemerk);
                        sales.put("qty", qty);
                        sales.put("price", price);



                        documentSales.add(sales).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                            @Override
                            public void onSuccess(DocumentReference documentReference) {
                                Toast.makeText(AddItemActivity.this, "Berhasil mencetak transaksi", Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                etMerk.setText("");
                                etType.setText("");
                                etQty.setText("");
                                etPrice.setText("");
                            }
                        })
                                .addOnFailureListener(new OnFailureListener() {
                                    @Override
                                    public void onFailure(@NonNull Exception e) {
                                        Toast.makeText(AddItemActivity.this, "Gagal mencetak", Toast.LENGTH_SHORT).show();
                                        progressBar.setVisibility(View.GONE);
                                    }
                                });
                        progressBar.setVisibility(View.GONE);
                    }
            }
            else {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(AddItemActivity.this, "Barang tidak terdaftar", Toast.LENGTH_SHORT).show();
                    Log.w(Tag.ITEM, "error getting documents", task.getException());
                }
            }
        });
    }