[英]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);
您的代碼沒有按預期運行的原因有幾個。
第一:確保通過啟用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.