Firestore查询空指针异常:调用getLong时对象为null
解决Firestore加载书籍数据时的NullPointerException问题
核心问题出在这几个地方:
- 循环条件错误:原代码中
for (int i=1; 1 <= bookCount ;i++)的判断逻辑写错,会导致无限循环,反复尝试获取不存在的书籍ID,最终让bookDoc变为null。 - 缺失null校验:从
docList获取bookDoc后未判断是否为null;调用getLong("NO_OF_BOOK")后直接调用intValue(),如果字段不存在或为null,同样会触发空指针。
修复后的代码如下:
public static void LoadBook(MyCompleteListener completeListener) { bookList.clear(); g_firestore.collection("BOOKS").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { Map<String, QueryDocumentSnapshot> docList = new ArrayMap<>(); for (QueryDocumentSnapshot doc : queryDocumentSnapshots) { docList.put(doc.getId(), doc); } QueryDocumentSnapshot bookListDoc = docList.get("Categories"); if (bookListDoc == null) { completeListener.onFailure(new Exception("Categories文档不存在")); return; } Long bookCount = bookListDoc.getLong("COUNT"); if (bookCount == null || bookCount <= 0) { completeListener.onSuccess(); return; } // 修正循环条件为i <= bookCount for (int i = 1; i <= bookCount; i++) { String bookID = bookListDoc.getString("BOOK" + String.valueOf(i) + "_ID"); if (bookID == null || bookID.isEmpty()) { continue; } QueryDocumentSnapshot bookDoc = docList.get(bookID); if (bookDoc == null) { continue; } // 处理NO_OF_BOOK字段,避免null Long noOfBookLong = bookDoc.getLong("NO_OF_BOOK"); int noOfBook = noOfBookLong != null ? noOfBookLong.intValue() : 0; String bookName = bookDoc.getString("NAME"); String bookType = bookDoc.getString("TYPE"); if (bookName != null && bookType != null) { bookList.add(new BookModel(bookID, bookName, bookType, noOfBook)); } } completeListener.onSuccess(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { completeListener.onFailure(e); } }); }
额外说明:
- 对所有可能返回null的对象和字段都做了校验,从根源避免空指针。
- 修正了循环逻辑,防止无限循环占用资源。
- 新增了失败场景的回调传递,让上层能感知加载异常。
- 给
NO_OF_BOOK设置了默认值0,你可以根据业务需求调整默认值。
内容的提问来源于stack exchange,提问作者sarthak tiwari
相关产品推荐
相关产品推荐

