简体   繁体   English

Firestore 查询未获取最新文档

[英]Firestore Query Not Obtaining Latest Document

I am currently building an Android application for a basic inventory management system for a haberdashery and the one feature/function I would like to implement is the ability to choose categories that when selected will filter the products.我目前正在为Haberdashery建立ZE84E30B9390CDB64DB6DB6DB6DB2C9AB87846DZ应用程序,用于Haberdashery的基本库存管理系统,而我想实现的一个功能/功能是选择类别的能力,这些类别在选择时会过滤产品。 I am pretty much just playing around with the idea for now, but I currently have a CardView set up, where each Card contains a button that are labelled according to the category's name.我现在几乎只是在玩这个想法,但我目前有一个 CardView 设置,其中每个 Card 都包含一个根据类别名称标记的按钮。 I am currently using Google's Firestore to store all my information, which you can see below.我目前正在使用 Google 的 Firestore 来存储我的所有信息,您可以在下面看到这些信息。 在此处输入图像描述

As you can see, there are 9 categories currently, each containg a different id value starting from 1 and ending on 9. I want to be able to add new categories within my application.如您所见,目前有 9 个类别,每个类别包含从 1 到 9 的不同 id 值。我希望能够在我的应用程序中添加新类别。 So I figured that in order to add a new category, I first need to find the latest one that was added, obtain its id value, increment it by 1 and then write the new category with its new name(which is obtained through the application) and id to the database.所以我想,要添加一个新类别,我首先需要找到最新添加的类别,获取它的 id 值,将其加 1,然后用它的新名称写入新类别(通过应用程序获得) 和 id 到数据库。 This worked the first time, however if I start to consecutively add items the database it does not seem to find the latest document whenever I click the button to do so, for example, if the latest document is "ONAYBHFDTII6rcRbKxSf" with id value 9, then the first time will work whereby it will create a new document with id value 10, but when I try to add an 11th document, the query does not find the previously created document with id value 10, and instead uses document "ONAYBHFDTII6rcRbKxSf" again, giving me now two documents with id value 10, but with different category names.这是第一次工作,但是如果我开始连续向数据库添加项目,每当我单击按钮时,它似乎都找不到最新的文档,例如,如果最新的文档是 id 值为 9 的“ONAYBHFDTII6rcRbKxSf”,那么第一次将起作用,它将创建一个 id 值为 10 的新文档,但是当我尝试添加第 11 个文档时,查询没有找到先前创建的 id 值为 10 的文档,而是再次使用文档“ONAYBHFDTII6rcRbKxSf” ,现在给我两个 id 值为 10,但类别名称不同的文档。

I have pasted below the method I used to perform this action.我在下面粘贴了我用来执行此操作的方法。 This method is called in my button's onClickListener() .此方法在我的按钮的onClickListener()中调用。 I first took in my new category name using an AlertDialog and then performed my read for the latest document by using an orderBy() and limit() method, to obtain the latest id, to which I then incremented and then wrote a new document back to the database.我首先使用 AlertDialog 获取我的新类别名称,然后使用orderBy()limit()方法执行我对最新文档的读取,以获得最新的 id,然后我将其递增,然后写回一个新文档到数据库。

I am still very new when it comes to Firestore/Firebase and I am trying to delve deeper into it, therefore my question is, am I doing something wrong?我对 Firestore/Firebase 还是很陌生,我正在尝试更深入地研究它,因此我的问题是,我做错了什么吗? Is my logic out of place?我的逻辑不合适吗? If possible I would like to keep the structure of my database, but if it is absolutely necessary to change it in order for it to function properly then I won't mind.如果可能的话,我想保留我的数据库的结构,但是如果绝对有必要更改它以使其正确地更改为 function,那么我不会介意。

private void showTextDialog(View view)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("Enter Category");
        final EditText input = new EditText(getContext());
        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_DATETIME_VARIATION_NORMAL);
        builder.setView(input);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String newCategory = input.getText().toString();
                db = FirebaseFirestore.getInstance();
                newCategories = new HashMap<>();
                db.collection("categories")
                        .orderBy("id", Query.Direction.DESCENDING)
                        .limit(1)
                        .get()
                        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                                int latestID = 0;
                                for(QueryDocumentSnapshot document : task.getResult())
                                {
                                    latestID = Integer.parseInt(document.get("id").toString());
                                    Log.d("Latest Document", document.getId().toString());
                                }
                                latestID++;
                                newCategories.put("id", latestID);
                                newCategories.put("categoryName", newCategory);
                                db.collection("categories")
                                        .add(newCategories)
                                        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                                            @Override
                                            public void onSuccess(DocumentReference documentReference) {
                                                Log.d("fragment", "Successfully added document");
                                                getCategories();
                                            }
                                        })
                                        .addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception e) {
                                                Log.d("fragment", "Failed to add document");
                                            }
                                        });
                            }
                        });


            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }

I figured out the solution to my little problem stated above.我想出了解决上述小问题的方法。 Simply put, ensure that all the value in your database are exactly the same.简而言之,确保数据库中的所有值都完全相同。 In my case, some of the id values were strings and not number types在我的情况下,一些 id 值是字符串而不是数字类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM