【发布时间】:2020-08-11 07:54:07
【问题描述】:
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.我现在几乎只是在玩这个想法,但我目前有一个 CardView 设置,其中每个 Card 都包含一个根据类别名称标记的按钮。我目前正在使用 Google 的 Firestore 来存储我的所有信息,您可以在下面看到这些信息。
如您所见,目前有 9 个类别,每个类别包含从 1 到 9 的不同 id 值。我希望能够在我的应用程序中添加新类别。所以我想,要添加一个新类别,我首先需要找到最新添加的类别,获取它的 id 值,将其加 1,然后用它的新名称写入新类别(通过应用程序获得) 和数据库的 id。这是第一次工作,但是如果我开始连续向数据库添加项目,每当我单击按钮时,它似乎都找不到最新的文档,例如,如果最新的文档是 id 值为 9 的“ONAYBHFDTII6rcRbKxSf”,那么第一次将起作用,它将创建一个 id 值为 10 的新文档,但是当我尝试添加第 11 个文档时,查询没有找到先前创建的 id 值为 10 的文档,而是再次使用文档“ONAYBHFDTII6rcRbKxSf” ,现在给我两个 id 值为 10,但类别名称不同的文档。
我在下面粘贴了我用来执行此操作的方法。此方法在我的按钮的onClickListener() 中调用。我首先使用 AlertDialog 获取我的新类别名称,然后使用 orderBy() 和 limit() 方法执行我对最新文档的读取,以获得最新的 id,然后我将其递增,然后将新文档写回到数据库。
在 Firestore/Firebase 方面我还是个新手,我正在尝试更深入地研究它,因此我的问题是,我做错了什么吗?我的逻辑不合适吗?如果可能的话,我想保留我的数据库的结构,但如果绝对有必要更改它以使其正常运行,那么我不会介意。
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();
}
【问题讨论】:
-
这段代码中到底有什么不符合您的预期?
-
获取最新ID值时。第一次它会做对,但之后的任何其他时间,它都会使用第一次尝试获得的相同文档
标签: java android firebase google-cloud-firestore