Firestore数据获取空指针异常求助:从Firebase提取字段值遇问题
Hey there, let's break down why you're hitting that java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference error and fix it step by step.
What's Causing the Error?
The root issue is that doc.get("No_of_subjects") is returning null when you try to fetch it. This happens for one of these common reasons:
- The field name
No_of_subjectsdoesn't exactly match what's in your Firebase Firestore document (check for typos, case sensitivity likeno_of_subjectsvsNo_of_subjects, or missing underscores). - The
Subjectsdocument doesn't actually have this field at all. - The field's data type in Firestore doesn't match what you're trying to cast to (e.g., you stored a String instead of a Number, or a Long instead of an Integer).
Step-by-Step Fixes
1. Verify Your Firestore Document Structure
First, head to the Firebase Console and double-check:
- The
Online Classcollection has a document namedSubjects. - Inside that document, there's a field named exactly
No_of_subjects, and its type is set toNumber(either Integer or Long—Firestore stores whole numbers as Long by default).
2. Safely Retrieve the Count Value
Instead of forcing a cast directly (which crashes if the value is null), use Firestore's type-safe getter methods and add null checks:
Replace this risky line:
Integer count = new Integer( (Integer) doc.get("No_of_subjects") );
With this safe approach (handling both null and type mismatches):
// Use getLong() since Firestore stores whole numbers as Long by default Long countLong = doc.getLong("No_of_subjects"); // Check if the count is null (field missing or invalid) if (countLong == null) { Toast.makeText(CategoriesActivity.this, "Failed to find subject count", Toast.LENGTH_SHORT).show(); finish(); return; } // Convert Long to int (safe since count of subjects won't exceed int limits) int count = countLong.intValue();
3. Add Safety Checks for Subject Names
Your loop fetches fields like Subject 1, Subject 2—these could also be missing, leading to null values in your list. Add a quick check to avoid adding nulls:
for (int i = 1; i <= count; i++) { String subjectName = doc.getString("Subject " + String.valueOf(i)); // Only add the name if it exists if (subjectName != null) { categoryist.add(subjectName); } else { // Optional: Log a warning for missing fields Log.w("CategoriesActivity", "Subject " + i + " is missing in the Firestore document"); } }
Full Revised loadData() Method
Here's how your updated method should look:
private void loadData() { categoryist.clear(); firestore.collection("Online Class").document("Subjects") .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot doc = task.getResult(); if (doc.exists()) { // Safely get the subject count Long countLong = doc.getLong("No_of_subjects"); if (countLong == null) { Toast.makeText(CategoriesActivity.this, "Subject count field missing", Toast.LENGTH_SHORT).show(); finish(); return; } int count = countLong.intValue(); // Fetch each subject safely for (int i = 1; i <= count; i++) { String subjectName = doc.getString("Subject " + i); if (subjectName != null) { categoryist.add(subjectName); } else { Log.w("CategoriesActivity", "Subject " + i + " not found"); } } // Don't forget to update your UI here if needed! // (e.g., notify your adapter if you're using a RecyclerView) } else { Toast.makeText(CategoriesActivity.this, "No Subject Exists", Toast.LENGTH_SHORT).show(); finish(); } } else { Toast.makeText(CategoriesActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); }
One Last Tip
If you're still running into issues, add a Log.d statement to print the entire document's data—this will help you see exactly what's being retrieved:
Log.d("CategoriesActivity", "Document data: " + doc.getData().toString());
This will show all fields and their values in Logcat, making it easy to spot typos or missing fields.
内容的提问来源于stack exchange,提问作者SuRaj Das

