Android中AssetManager解析本地JSON文件出现NullPointerException求助
Hey there! Let's break down why you're hitting that NullPointerException and fix it step by step.
The Root Cause
Looking at your error log:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.content.Context.getAssets()' on a null object reference
This happens because your JSONParser class inherits from AppCompatActivity, but you're creating it with a simple new JSONParser() call. Activities rely on the Android system to initialize their context—when you manually instantiate an Activity subclass like this, its context remains null, so getAssets() fails.
Plus, your userList in JSONParser is only declared, not initialized—this would cause another NPE when you try to add items to it later.
Fixed Code
Let's rewrite the classes to fix these issues:
1. JSONParser.java (converted to a utility class)
package com.thkoeln.stucked; import android.content.Context; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; public class JSONParser { private final Context context; public ArrayList<HashMap<String, String>> userList; // Pass context through constructor to access assets safely public JSONParser(Context context) { this.context = context; userList = new ArrayList<>(); // Initialize the list to avoid NPE } public String loadJSONFromAsset() { String json = null; try { InputStream is = context.getAssets().open("users.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; // Return null if loading fails } return json; } public ArrayList<HashMap<String, String>> parseJson() { String jsonStr = loadJSONFromAsset(); if (jsonStr == null) { Log.e("JSONParser", "Failed to load JSON file from assets"); return userList; } try { JSONObject reader = new JSONObject(jsonStr); JSONArray users = reader.getJSONArray("users"); Log.d("AnzahlUser", String.valueOf(users.length())); for (int i = 0; i < users.length(); i++) { JSONObject u = users.getJSONObject(i); Log.d("Details-->", u.toString()); String uid = u.getString("uid"); String uname = u.getString("uname"); String ustart = u.getString("ustart"); HashMap<String, String> user = new HashMap<>(); user.put("uid", uid); user.put("uname", uname); user.put("ustart", ustart); userList.add(user); } } catch (final JSONException e) { e.printStackTrace(); Log.e("JSONParser", "Error parsing JSON: " + e.getMessage()); } return userList; } }
2. MainActivity.java (updated to use the fixed parser)
package com.thkoeln.stucked; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { ListView activityList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activityList = findViewById(R.id.activityList); String fromArray[] = {"uid", "uname", "ustart"}; int to[] = {R.id.uid, R.id.uname, R.id.ustart}; // Pass the activity context to JSONParser JSONParser jp = new JSONParser(this); ArrayList<HashMap<String, String>> userList = jp.parseJson(); // Set up the ListView adapter ListAdapter adapter = new SimpleAdapter(this, userList, R.layout.user_item, fromArray, to); activityList.setAdapter(adapter); } }
Key Fixes Explained
- Removed Activity inheritance from JSONParser: It's a utility class, not a screen—no need to inherit
AppCompatActivity. - Added Context to JSONParser constructor: This gives the parser access to the app's assets safely using the activity's valid context.
- Initialized userList: Prevents an NPE when adding items to the list during parsing.
- Added error handling: Checks if the JSON file loads successfully before trying to parse it.
Quick Check
Make sure your users.json file is placed in the src/main/assets directory (create the assets folder if it doesn't exist) and that the filename matches exactly (case-sensitive!).
内容的提问来源于stack exchange,提问作者jrappen1

