【问题标题】:Getting JSON from URL, pick value and store it into the textView从 URL 获取 JSON,选择值并将其存储到 textView
【发布时间】:2019-10-21 00:40:25
【问题描述】:

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

我来到了这段代码,它应该至少将 id 值放入 textview....但它并没有真正做任何事情

            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);

【问题讨论】:

    标签: java android url connection database-connection


    【解决方案1】:

    您的代码未按预期运行有几个原因。

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

    <?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 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);
        }
    }
    

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

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

    干杯!

    编辑:格式化

    【讨论】:

      【解决方案2】:

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

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

      可以找到一个很好的例子here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-19
        • 2018-01-28
        • 2018-03-20
        • 1970-01-01
        • 2021-10-21
        • 2021-10-07
        • 2018-11-11
        相关资源
        最近更新 更多