无法在Android中获取和显示JSON

时间:2013-03-30 15:00:13

标签: java android json web http-get

我正在构建一个复杂的应用程序但是我遇到了一个孤立的问题。我的Android应用程序类UserPage.java应该能够从网页中获取一个String,然后将其传递给布局并相应地显示它。

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


}

布局 - 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>

从网络上提取的内容

[{"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}]

我得到的错误是非常通用的,我似乎无法在任何地方找到信息

   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'

任何帮助或指示都将受到高度赞赏, d

2 个答案:

答案 0 :(得分:1)

您正在主线程上运行http调用,这会导致错误。

response = client.execute(request);

上面的代码应该在新的Thread上运行。

你应该有类似的东西:

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

如果您想对UI组件进行更新,您应该将代码运行到:

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

您应该阅读有关threads on android

的更多信息

答案 1 :(得分:1)

如上所述,您当前的代码在uiThread上运行。考虑使用asynctask或扩展Thread的类。关于这一点有很多问题,通过快速Google搜索,所以我觉得一个例子太多了。