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

如何解析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.

1. Fixing the JSONException & Null Pointer Exception (NPE)

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.

2. Parsing JSONArray & Assigning Values to TextViews

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();
}
Pro Tips to Avoid Future Issues
  • Prefer optXXX methods (like optString, optJSONObject) over getXXX—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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:13