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

连接MySQL触发JSONException且应用崩溃,插入成功如何修复?

Fixing JSONException Crash While MySQL Insert Succeeds

Hey there, let's break down your problem and work through fixes step by step: you're hitting a JSONException at jObj = new JSONObject(json);, and updating the progress dialog with pDialog.setMessage("7777"); causes a crash—even though your data successfully makes it into MySQL. Here's how to resolve both issues:

1. Root Cause of the JSONException

The exception happens because the string you’re trying to parse as JSON (json variable) isn’t valid JSON. Since the insert works, your server is likely returning a non-JSON response (like plain text "Insert successful") or malformed JSON with extra characters (debug logs, HTML snippets, or invisible whitespace).

Fix Steps:

  • Log the raw response first: In your JSONParser.java, right before creating the JSONObject, add a log to see exactly what your server sends back:
    Log.d("RAW_SERVER_RESPONSE", json);
    
    Check logcat to confirm if the response is properly formatted JSON (e.g., {"success":1,"message":"Data inserted"} instead of just "success").
  • Fix the server-side output: Ensure your backend returns valid JSON every time, even on success. For example, in PHP:
    // Return clean JSON after insert
    echo json_encode(array("success" => 1, "message" => "Insert completed"));
    exit; // Stop any extra output after JSON
    
    Avoid echoing debug messages, HTML errors, or whitespace before/after the JSON—this breaks the structure.
  • Add a fallback for invalid JSON: If you can’t fix the server immediately, add a safety check in parsing code:
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON_ERROR", "Invalid JSON: " + json, e);
        // Create a dummy object to prevent further crashes
        jObj = new JSONObject();
        jObj.put("success", 1); // Match your app's success flag logic
    }
    

2. Fix the Progress Dialog Crash

The crash when calling pDialog.setMessage("7777"); almost always means the dialog is already dismissed, uninitialized, or you’re modifying it from a non-UI thread.

Fix Steps:

  • Check dialog state before updating: Verify the dialog exists and is still showing before changing its message:
    if (pDialog != null && pDialog.isShowing()) {
        pDialog.setMessage("7777");
    }
    
  • Update the dialog on the UI thread: Network operations run on background threads, so post the dialog update to the main thread:
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (pDialog != null && pDialog.isShowing()) {
                pDialog.setMessage("7777");
            }
        }
    });
    
  • Manage dialog lifecycle correctly: Don’t dismiss the dialog until you’ve fully handled the response (success and error cases). If you have pDialog.dismiss(); right after triggering the network request, move it to after parsing the response.

3. Extra Debug Tips

  • Clean the response string: Sometimes server responses have invisible UTF-8 BOM characters. Clean the string before parsing:
    json = json.trim().replaceFirst("^\\uFEFF", "");
    
  • Validate JSON online: Copy the raw response from logcat into a JSON validator tool to confirm if it’s properly formatted.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:06:01