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

Android解析JSON填充RecyclerView报错:List.add空对象引用

Fixing NullPointerException When Parsing JSON for RecyclerView in Stitle.java

Let's break down exactly why you're hitting this java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference error, and fix it step by step.

Root Causes

Your issue stems from two critical mistakes in Stitle.java:

  1. Duplicate onCreate() methods: Android will only execute one of these methods (typically the last one defined), which means any initialization code in the unused onCreate (like setting up productList) never runs.
  2. Incorrect variable scoping/initialization: Your productList is either declared but never initialized, or it's a local variable in a scope that doesn't persist to where you're trying to call add().

Step 1: Remove Duplicate onCreate() Methods

First, scrub your Stitle.java file for multiple @Override protected void onCreate(Bundle savedInstanceState) methods. Delete all but one—this ensures your initialization code runs reliably every time the activity starts.

Step 2: Fix productList Initialization & Scoping

You need to ensure productList is initialized before you try to add items to it, and that it's accessible where you're parsing JSON. Here's how:

  • Declare productList as a member variable of your Activity (not inside a local method) so it persists across method calls.
  • Initialize it immediately when declaring it, or in the single onCreate() method before parsing JSON.

Step 3: Corrected Code Example

Here's a cleaned-up version of Stitle.java that fixes both issues:

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;

public class Stitle extends AppCompatActivity {
    // Declare productList as a member variable and initialize it
    private List<Product> productList = new ArrayList<>();
    private RecyclerView recyclerView;
    private ProductAdapter productAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stitle);

        // Set up RecyclerView and Adapter
        recyclerView = findViewById(R.id.your_recycler_view_id);
        productAdapter = new ProductAdapter(productList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(productAdapter);

        // Trigger JSON parsing after all setup is done
        parseJsonData();
    }

    private void parseJsonData() {
        // Replace this with your actual JSON parsing logic
        try {
            // Example: Parse a JSON object into a Product model
            Product sampleProduct = new Product("Sample Product Title", "Sample Description");
            productList.add(sampleProduct); // No more NPE—list is initialized!
            productAdapter.notifyDataSetChanged(); // Notify adapter of data update
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Key Notes to Avoid Future Issues

  • Adapter Reference: Make sure your RecyclerView adapter holds the same productList reference you're updating—don't create a new list inside the adapter.
  • Null Checks: Add defensive null checks if your JSON parsing could return null objects (e.g., if (parsedProduct != null) productList.add(parsedProduct);).
  • Background Thread: For real-world JSON parsing, always do it on a background thread (like using AsyncTask or Kotlin Coroutines) to avoid blocking the UI.

内容的提问来源于stack exchange,提问作者Asad Mallick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:54:44