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

Android新手求助:从MySQL取数据并显示到TextView失败

解决Android解析JSON并显示到TextView的问题

嘿,别慌!既然已经成功拿到JSON数据了,那咱们离搞定问题就差两步:正确解析JSON + 在UI线程安全更新TextView。我来帮你一步步捋清楚:

核心注意点

你用的是AsyncTask,而doInBackground是后台线程,绝对不能直接在这个方法里操作TextView——Android的UI组件只能在主线程更新,这是新手最容易踩的坑!咱们得把解析和更新UI的逻辑放到onPostExecute方法里,这个方法是在主线程执行的。

完整示例代码

我帮你补全并优化了你的AsyncTask,你可以参考调整:

// 定义一个AsyncTask子类来处理网络请求和数据解析
private class FetchJsonDataTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        InputStream is = null;
        String jsonResult = "";
        
        try {
            // 初始化网络连接
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET"); // 根据你的接口请求方式调整
            is = new BufferedInputStream(httpURLConnection.getInputStream());
            
            // 将输入流转换成JSON字符串
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            jsonResult = sb.toString();
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭输入流,避免资源泄漏
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        return jsonResult; // 将JSON字符串传递给onPostExecute
    }

    @Override
    protected void onPostExecute(String jsonResult) {
        super.onPostExecute(jsonResult);
        
        // 这里是主线程,可以安全操作TextView
        TextView targetTextView = findViewById(R.id.your_textview_id); // 替换成你的TextView ID
        
        try {
            // ********** 这里根据你的实际JSON结构调整解析逻辑 **********
            // 示例1:如果JSON是单个对象,比如 {"message":"Hello from MySQL"}
            JSONObject jsonObject = new JSONObject(jsonResult);
            String displayContent = jsonObject.getString("message"); // 替换成你的JSON键名
            
            // 示例2:如果JSON是数组,比如 [{"id":1,"content":"第一条数据"},{"id":2,"content":"第二条数据"}]
            // JSONArray jsonArray = new JSONArray(jsonResult);
            // StringBuilder contentBuilder = new StringBuilder();
            // for (int i = 0; i < jsonArray.length(); i++) {
            //     JSONObject item = jsonArray.getJSONObject(i);
            //     contentBuilder.append("第").append(i+1).append("条:").append(item.getString("content")).append("\n");
            // }
            // String displayContent = contentBuilder.toString();
            
            // 更新TextView内容
            targetTextView.setText(displayContent);
            
        } catch (JSONException e) {
            e.printStackTrace();
            // 解析出错时给用户提示
            targetTextView.setText("数据解析失败:" + e.getMessage());
        }
    }
}

额外提醒

  • 别忘了在AndroidManifest.xml里添加网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 先打印jsonResult看看实际的JSON格式,确保解析时的键名和结构完全匹配,不然会抛出JSONException。
  • 如果你用的是Android 9及以上版本,默认禁止明文HTTP请求,要么改用HTTPS,要么在AndroidManifest.xml的<application>标签里添加android:usesCleartextTraffic="true"。

内容的提问来源于stack exchange,提问作者A.Mootaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:09:04