Android解析JSON填充RecyclerView报错:List.add空对象引用
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:
- Duplicate
onCreate()methods: Android will only execute one of these methods (typically the last one defined), which means any initialization code in the unusedonCreate(like setting upproductList) never runs. - Incorrect variable scoping/initialization: Your
productListis either declared but never initialized, or it's a local variable in a scope that doesn't persist to where you're trying to calladd().
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
productListas 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
productListreference 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
AsyncTaskor Kotlin Coroutines) to avoid blocking the UI.
内容的提问来源于stack exchange,提问作者Asad Mallick

