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

Android Studio中解析URL返回JSON并单独显示字段到TextView

完整实现:Android Studio中从URL获取JSON并解析到TextView

我来给你梳理一个完整的实现方案,刚好匹配你现有的aFragment代码结构,一步步来:


1. 先准备Fragment布局文件(fragment_a.xml)

首先需要在布局里添加对应JSON字段的TextView,每个设置唯一ID,方便后续绑定数据:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/tv_s"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"/>

    <TextView
        android:id="@+id/tv_code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="8dp"/>

    <TextView
        android:id="@+id/tv_c"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="8dp"/>

    <TextView
        android:id="@+id/tv_y"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="8dp"/>

    <TextView
        android:id="@+id/tv_i"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="8dp"/>

    <TextView
        android:id="@+id/tv_x"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_marginTop="8dp"/>

</LinearLayout>

2. 完整的aFragment代码实现

这里补全你现有的代码,包括控件初始化、异步网络请求、JSON解析和UI更新:

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class aFragment extends Fragment {

    // 声明需要绑定的TextView
    private TextView tvS, tvCode, tvC, tvY, tvI, tvX;
    // 替换成你的目标JSON接口URL
    private static final String JSON_REQUEST_URL = "你的实际接口URL";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_a, container, false);
        // 初始化所有TextView控件
        initViews(view);
        // 执行异步任务获取并解析数据
        new TransTask().execute(JSON_REQUEST_URL);
        return view;
    }

    private void initViews(View view) {
        tvS = view.findViewById(R.id.tv_s);
        tvCode = view.findViewById(R.id.tv_code);
        tvC = view.findViewById(R.id.tv_c);
        tvY = view.findViewById(R.id.tv_y);
        tvI = view.findViewById(R.id.tv_i);
        tvX = view.findViewById(R.id.tv_x);
    }

    // 自定义AsyncTask处理异步网络请求(注意:AsyncTask已标记为Deprecated,后面会补充现代替代方案)
    private class TransTask extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... strings) {
            String urlString = strings[0];
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            JSONObject resultJson = null;

            try {
                URL url = new URL(urlString);
                // 建立HTTP连接
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // 读取服务器返回的输入流
                InputStream inputStream = urlConnection.getInputStream();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder buffer = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
                if (buffer.length() == 0) {
                    return null;
                }
                // 将字符串解析为JSONObject
                resultJson = new JSONObject(buffer.toString());

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接和流资源
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return resultJson;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            super.onPostExecute(jsonObject);
            if (jsonObject != null) {
                try {
                    // 提取JSON中的每个字段并设置到对应TextView
                    boolean s = jsonObject.getBoolean("s");
                    int code = jsonObject.getInt("code");
                    String c = jsonObject.getString("c");
                    String y = jsonObject.getString("y");
                    String i = jsonObject.getString("i");
                    String x = jsonObject.getString("x");

                    tvS.setText("s: " + s);
                    tvCode.setText("code: " + code);
                    tvC.setText("c: " + c);
                    tvY.setText("y: " + y);
                    tvI.setText("i: " + i);
                    tvX.setText("x: " + x);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3. 必要的配置

  • 添加网络权限:在AndroidManifest.xml的<manifest>标签内添加:
<uses-permission android:name="android.permission.INTERNET" />
  • 处理Android 9+明文请求:如果你的接口是HTTP而非HTTPS,需要在<application>标签内添加:
android:usesCleartextTraffic="true"

4. 现代替代方案(推荐)

因为AsyncTask已被官方废弃,更推荐用Executor + Handler(Java)或Kotlin协程来处理异步任务,这里给一个Java的简化示例:

// 替换aFragment中AsyncTask的调用代码
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(() -> {
    // 后台执行网络请求和解析
    JSONObject jsonObject = fetchJsonData(JSON_REQUEST_URL);
    // 回到主线程更新UI
    handler.post(() -> {
        if (jsonObject != null) {
            try {
                boolean s = jsonObject.getBoolean("s");
                int code = jsonObject.getInt("code");
                String c = jsonObject.getString("c");
                String y = jsonObject.getString("y");
                String i = jsonObject.getString("i");
                String x = jsonObject.getString("x");

                tvS.setText("s: " + s);
                tvCode.setText("code: " + code);
                tvC.setText("c: " + c);
                tvY.setText("y: " + y);
                tvI.setText("i: " + i);
                tvX.setText("x: " + x);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
});

// 把网络请求逻辑抽成单独方法
private JSONObject fetchJsonData(String urlString) {
    // 这里的逻辑和之前AsyncTask的doInBackground完全一致,复制过来即可
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;
    JSONObject jsonObject = null;

    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream == null) return null;
        reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line).append("\n");
        }
        if (buffer.length() == 0) return null;
        jsonObject = new JSONObject(buffer.toString());

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) urlConnection.disconnect();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return jsonObject;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:42:40