[英]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.