简体   繁体   English

无法在Android中获取和显示JSON

[英]Unable to fetch and display JSON in Android

I am building a complex application however I am having an isolated problem. 我正在构建一个复杂的应用程序但是我遇到了一个孤立的问题。 My Android application class UserPage.java should be able to fetch a String from a webpage and then pass that over to the layout and display it accordingly. 我的Android应用程序类UserPage.java应该能够从网页获取一个String,然后将其传递给布局并相应地显示它。

UserPage.java UserPage.java

package com.example.ams;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;

public class UserPage extends Activity {
        HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs;
        ProgressDialog dialog = null;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.userpage);
            String json = getStudents();
            //System.out.println(json);
            TextView datazer = (TextView) findViewById(R.id.data);
            datazer.setText(json);

        }

public String getStudents(){
    HttpResponse response = null;
    //String classID = "CSD2334";
    try {        
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI("http://localhost:8080/de.vogella.jersey.first/resources/hello/ids/CSD2334"));
            response = client.execute(request);
            System.out.println(response.toString());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
        return response.toString();
    }


}

The layout - userpage.xml 布局 - userpage.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
    <TextView  
        android:id="@+id/data"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"     
    />
</LinearLayout>

The content fetched from the web 从网络上获取的内容

[{"student_id":3,"student_name":"Dite Gashi","w1mo":"1","w1tue":"0","w1wed":0,"w1thu":0,"w1fri":1},{"student_id":4,"student_name":"Vullnet Dyla","w1mo":"2","w1tue":"2","w1wed":1,"w1thu":0,"w1fri":0},{"student_id":5,"student_name":"Edon Ymeri","w1mo":"0","w1tue":"0","w1wed":0,"w1thu":0,"w1fri":2},{"student_id":6,"student_name":"Ilir Kelmendi","w1mo":"2","w1tue":"0","w1wed":2,"w1thu":0,"w1fri":0}]

The error I am getting is quite generic and I can't seem to find information anywhere 我得到的错误是非常通用的,我似乎无法在任何地方找到信息

   03-30 17:36:15.074: E/AndroidRuntime(1458): FATAL EXCEPTION: main
03-30 17:36:15.074: E/AndroidRuntime(1458): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ams/com.example.ams.UserPage}: android.os.NetworkOnMainThreadException
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.os.Looper.loop(Looper.java:137)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.ActivityThread.main(ActivityThread.java:4424)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at java.lang.reflect.Method.invokeNative(Native Method)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at java.lang.reflect.Method.invoke(Method.java:511)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at dalvik.system.NativeStart.main(Native Method)
03-30 17:36:15.074: E/AndroidRuntime(1458): Caused by: android.os.NetworkOnMainThreadException
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at com.example.ams.UserPage.getStudents(UserPage.java:44)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at com.example.ams.UserPage.onCreate(UserPage.java:31)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.Activity.performCreate(Activity.java:4465)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-30 17:36:15.074: E/AndroidRuntime(1458):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
03-30 17:36:15.074: E/AndroidRuntime(1458):     ... 11 more
03-30 17:36:15.363: I/dalvikvm(1458): threadid=3: reacting to signal 3
03-30 17:36:15.434: I/dalvikvm(1458): Wrote stack traces to '/data/anr/traces.txt'
03-30 17:36:15.814: I/dalvikvm(1458): threadid=3: reacting to signal 3
03-30 17:36:15.834: I/dalvikvm(1458): Wrote stack traces to '/data/anr/traces.txt'

Any help or pointers would be highly appreciated, D 任何帮助或指示都将受到高度赞赏,D

You are running a http call on the main thread and that causes the error. 您正在主线程上运行http调用,这会导致错误。

response = client.execute(request);

The above code should run on a new Thread. 上面的代码应该在新的Thread上运行。

Your should have something like: 你应该有类似的东西:

new Thread( new Runnable() {
        @Override
        public void run() {
            HttpResponse response = null;
            //String classID = "CSD2334";
            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI("http://localhost:8080/de.vogella.jersey.first/resources/hello/ids/CSD2334"));
                response = client.execute(request);
                System.out.println(response.toString());
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return response.toString();
        }
    }).start();

And if you want to make updates to a UI component you should run the code into: 如果要对UI组件进行更新,则应将代码运行到:

    runOnUiThread(new Runnable() {
            @Override
            public void run() {
// runs on the UI thread so update UI here
            }
        });

You should read more about threads on android 你应该阅读更多关于android的线程

Your current code runs, as mentioned, on the uiThread . 如上所述,您当前的代码在uiThread运行 Consider using either an asynctask or a class which extends Thread . 考虑使用asynctask或扩展Thread的类。 There is a lot of questions regarding this, by doing a quick Google search, so I feel that an example would be too much. 关于这一点有很多问题,通过快速谷歌搜索,所以我觉得一个例子太多了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM