从 URL 获取 JSON,选择值并将其存储到 textView

Getting JSON from URL, pick value and store it into the textView

我开始学习 Android,我遇到了我无法解决的问题:我有 URL 和 JSON object:http://jsonplaceholder.typicode.com/todos 我正在尝试在 java-androidstudio 中连接 URL,然后选择确切的值,假设我想要 id=1 的标题值并将其放入我的 textView(textview id 是 'com1')

我已经看到这段代码,它应该至少将 id 值放入文本视图....但它并没有真正做任何事情

            String sURL = "http://jsonplaceholder.typicode.com/todos";
            URL url = new URL(sURL);
            URLConnection request = url.openConnection();
            request.connect();
JsonParser jp = new JsonParser(); //from gson
            JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
            JsonObject rootobj = root.getAsJsonObject();
            String idcko = rootobj.get("id").getAsString();

            TextView textElement = (TextView) findViewById(R.id.com1);
            textElement.setText(idcko);

阅读 volley 是一个不错的起点,它是一个帮助您管理请求的库。

这里有一个关于如何使用 volley 的教程 Android Volley Tutorial

可以找到一个很好的例子

您的代码未按预期运行的原因有多种。

首先:确保您已通过启用 INTERNET 权限并允许明文流量正确配置 Android 清单。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.sandbox"
            android:targetSandboxVersion="1">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        andoird:useCleartextTraffix="true"
        ... />

其次:确保您在 AsyncTask 中执行您的请求。 Android 不允许在主线程上向 运行 发出 HTTP 请求。为了克服这个问题,创建一个扩展 AsyncTask 抽象 class.

的新任务
class UrlRequestTask extends AsyncTask<Void, Void, Void> {
    protected void doInBackground() {
        String sURL = "http://jsonplaceholder.typicode.com/todos";
            URL url = new URL(sURL);
            URLConnection request = url.openConnection();
            request.connect();
            JsonParser jp = new JsonParser(); //from gson
            JsonElement root = jp.parse(new InputStreamReader((InputStream) 
            request.getContent()));
            JsonObject rootobj = root.getAsJsonObject();
            String idcko = rootobj.get("id").getAsString();

            TextView textElement = (TextView) findViewById(R.id.com1);
            textElement.setText(idcko);
    }
}

然后您可以在任何 activity 的 onCreate 中调用您的任务,如下所示: new UrlRequestTask().execute();

试试这些东西,看看会发生什么。 Post 错误消息,以帮助我自己和其他人确定到底出了什么问题。我 运行 在第一次做的时候也遇到了问题,这些解决方案对我有帮助。

干杯!

编辑:格式化