如何解析JSONArray并赋值给不同TextView?解析遇NPE及JSONException求助
Hey Andrew, let's tackle your problem head-on—first we'll squash that JSONException and null pointer issue, then walk through how to safely parse a JSONArray and assign its values to different TextViews.
The error org.json.JSONException: Value at 0 is null tells us two possible issues: either the first element in your JSONArray is actually null, or you're trying to access it without checking if it exists first. Here's how to fix this:
First, always validate your JSON data before parsing:
- Double-check that your source JSON has the structure you expect (no unexpected nulls in the array).
- Add non-null checks for both the JSONArray itself and each element you want to access.
Here's a code snippet to prevent the error:
// Assume you've fetched your JSON string from network/local storage String jsonResponse = "..."; try { // If your array is nested inside a JSONObject, get it first JSONObject parentObj = new JSONObject(jsonResponse); JSONArray dataArray = parentObj.getJSONArray("your_array_key"); // Replace with your actual key // Check if the array exists and isn't empty if (dataArray == null || dataArray.length() == 0) { Log.e("JSONParse", "JSONArray is empty or null"); return; } // Check if the element at index 0 is NOT null before accessing it if (!dataArray.isNull(0)) { JSONObject item = dataArray.getJSONObject(0); // Use getString/int if it's a primitive type // Continue parsing... } else { Log.e("JSONParse", "Element at index 0 is null—check your source JSON!"); } } catch (JSONException e) { e.printStackTrace(); // Show a user-friendly error, like a Toast Toast.makeText(getApplicationContext(), "Failed to load data", Toast.LENGTH_SHORT).show(); }
The key here is using dataArray.isNull(index) to catch null elements before they cause exceptions, and validating the array itself to avoid NPEs.
Let's cover two common JSONArray scenarios: one with nested JSONObjects, and one with a plain string array.
Scenario 1: JSONArray contains JSONObjects
Suppose your JSON looks like this:
[ {"header": "Welcome!"}, {"description": "This is a demo text."}, {"footer": "Thanks for reading!"} ]
Here's how to parse it and assign to TextViews:
// Initialize your TextViews first TextView tvHeader = findViewById(R.id.tv_header); TextView tvDescription = findViewById(R.id.tv_description); TextView tvFooter = findViewById(R.id.tv_footer); try { JSONArray jsonArray = new JSONArray(jsonResponse); // Or get from parent JSONObject // Assign header text (check array length and element non-null first) if (jsonArray.length() >= 1 && !jsonArray.isNull(0)) { JSONObject headerObj = jsonArray.getJSONObject(0); // Use optString to get a default value if the key doesn't exist String headerText = headerObj.optString("header", "Default Header"); tvHeader.setText(headerText); } // Assign description text if (jsonArray.length() >= 2 && !jsonArray.isNull(1)) { JSONObject descObj = jsonArray.getJSONObject(1); String descText = descObj.optString("description", "No description available"); tvDescription.setText(descText); } // Assign footer text if (jsonArray.length() >= 3 && !jsonArray.isNull(2)) { JSONObject footerObj = jsonArray.getJSONObject(2); String footerText = footerObj.optString("footer", "Default Footer"); tvFooter.setText(footerText); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Data parsing failed", Toast.LENGTH_SHORT).show(); }
Scenario 2: JSONArray is a plain string array
If your JSON is just a list of strings:
["Hello World!", "This is TextView 2", "TextView 3 content"]
The parsing is simpler:
TextView tv1 = findViewById(R.id.tv_1); TextView tv2 = findViewById(R.id.tv_2); TextView tv3 = findViewById(R.id.tv_3); try { JSONArray jsonArray = new JSONArray(jsonResponse); if (jsonArray.length() >= 1 && !jsonArray.isNull(0)) { tv1.setText(jsonArray.optString(0, "Default Text 1")); } if (jsonArray.length() >= 2 && !jsonArray.isNull(1)) { tv2.setText(jsonArray.optString(1, "Default Text 2")); } if (jsonArray.length() >= 3 && !jsonArray.isNull(2)) { tv3.setText(jsonArray.optString(2, "Default Text 3")); } } catch (JSONException e) { e.printStackTrace(); }
- Prefer
optXXXmethods (likeoptString,optJSONObject) overgetXXX—they return a default value instead of throwing exceptions if the key/element doesn't exist. - Never assume your JSON data will always match your expected structure—always validate lengths and nulls.
- If parsing JSON from a network call, do it on a background thread (use AsyncTask, Coroutines, or Retrofit with Moshi/Gson) to avoid freezing the UI.
内容的提问来源于stack exchange,提问作者Andrew Miranda

