簡體   English   中英

從URL獲取JSON,選擇值並將其存儲到textView中

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

我開始學習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);

一個好的起點是閱讀排球 ,它是一個幫助您管理請求的庫。

這是一個關於如何使用排球Android Volley教程的教程

這里可以找到一個很好的例子

您的代碼沒有按預期運行的原因有幾個。

第一:確保通過啟用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();

嘗試這些東西,看看會發生什么。 發布錯誤消息以幫助自己和其他人確切地確定錯誤。 當我第一次做這個問題時遇到了問題,這些解決方案對我有幫助。

干杯!

編輯:格式化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM