You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore数据获取空指针异常求助:从Firebase提取字段值遇问题

Fixing the NullPointerException in Firebase Firestore Data Retrieval

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_subjects doesn't exactly match what's in your Firebase Firestore document (check for typos, case sensitivity like no_of_subjects vs No_of_subjects, or missing underscores).
  • The Subjects document 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 Class collection has a document named Subjects.
  • Inside that document, there's a field named exactly No_of_subjects, and its type is set to Number (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:37:36