Android Studio中如何获取Firestore新创建文档的自动生成ID
错误原因
你当前调用productsRef.getId()获取的是Products集合本身的ID,而非新创建文档的自动生成ID。Firestore的add()方法是异步写入操作,新建文档的随机ID会在写入成功的回调结果中返回。
解决方案
方案1:在写入成功的回调中获取ID
将你原来获取ID跳转的代码替换为如下逻辑,监听add()方法的成功回调即可拿到新建文档的引用,进而获取ID:
productsRef.add(product).addOnSuccessListener(documentReference -> { // 从回调返回的文档引用中获取自动生成的ID String productId = documentReference.getId(); Intent intent = new Intent(getApplicationContext(), saveProductImage.class); intent.putExtra("productID", productId); startActivity(intent); finish(); }).addOnFailureListener(e -> { // 可选:添加写入失败的提示逻辑 Toast.makeText(newProduct.this, "商品创建失败,请重试", Toast.LENGTH_SHORT).show(); });
如果你需要在Instructor分支中也获取ID跳转,对该分支下的productsRef.add(product)做同样的修改即可。
方案2:提前生成ID再写入数据
如果不需要等待写入完成再操作ID,也可以先生成带随机ID的空文档引用,拿到ID后再写入数据:
// 先生成带自动随机ID的空文档引用 DocumentReference newProductRef = productsRef.document(); // 直接获取生成好的ID,不需要等待异步写入完成 String productId = newProductRef.getId(); // 将数据写入该文档引用 newProductRef.set(product); // 后续直接使用productId即可 Intent intent = new Intent(getApplicationContext(), saveProductImage.class); intent.putExtra("productID", productId); startActivity(intent); finish();
内容的提问来源于stack exchange,提问作者Aldridge Yong
相关产品推荐
相关产品推荐

