0

我是 android 新手,我想使用json. 运行代码时出现异常,并且我的应用程序说不幸的是 myapp 已停止运行。我也发布了我的logcat. 我想阅读
课程代码:101,
课程名称:“blahblah”
提供的学期:第 1 学期、第 2 学期、第 3 学期

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Compsci734MainActivity extends ListActivity {

    AsyncTask<Void, Void, Void> mTask;
    String jsonString;

    //String url = "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=50cent&count=2";

    String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";

    //Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compsci734_main);
        //getActionBar().setDisplayHomeAsUpEnabled(true);

        Button button = (Button) findViewById(R.id.btnFetch);
        final TextView tv = (TextView) findViewById(R.id.txtView);

        mTask = new AsyncTask<Void, Void, Void> () {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    jsonString = getJsonFromServer(url);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);

                tv.setText(jsonString);

            }
        };

//      Button button =(Button) findViewById(R.id.btnFetch);
//        TextView tv =(TextView) findViewById(R.id.txtView);
        button.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                try {
                    String url = "http://redsox.tcs.auckland.ac.nz
                                                  /734A/CSService.svc/courses";
                    HttpPost httppost = new HttpPost(url);
                    try {
                        HttpParams p = new BasicHttpParams();
                        HttpClient httpclient = new DefaultHttpClient(p);
                        ResponseHandler<String> responseHandler = new
                                                        BasicResponseHandler();
                        String responseBody = httpclient.execute(httppost,
                                responseHandler);
                        JSONArray jArray = new JSONArray(responseBody);
                        String text="";
                        for (int i = 0; i < jArray.length(); i++) {
                            JSONObject e = jArray.getJSONObject(i);
                                text = text + "Course ID :
                                        "+e.getString("courseField")+"\n";
                                text = text + "Course name :
                                         "+e.getString("titleField")+"\n";
                                text = text + "Semesters offered:
                                      "+e.getString("semesterField")+"\n";
                                //text = text + "Birthyear :
                                //        "+e.getString("birthyear")+"\n";
                        }
                        Log.i(responseBody, text);
                        tv.setText(text);
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } catch (Throwable t) {
                    Toast.makeText(getBaseContext(), "Request failed: " +
                                        t.toString(), Toast.LENGTH_LONG).show();
                    t.printStackTrace();
                }    


                //tv.setText(result);
            }
        });
    }


    public static String getJsonFromServer(String url) throws IOException {

        BufferedReader inputStream = null;

        URL jsonUrl = new URL(url);
        URLConnection dc = jsonUrl.openConnection();

        dc.setConnectTimeout(5000);
        dc.setReadTimeout(5000);

        inputStream = new BufferedReader(new InputStreamReader(
                dc.getInputStream()));

        // read the JSON results into a string
        String jsonResult = inputStream.readLine();
        return jsonResult;
    }

    }

这是我的日志:

05-13 16:27:16.375: I/dalvikvm(1040): threadid=3: reacting to signal 3
05-13 16:27:16.585: E/dalvikvm(1040): Unable to open stack trace file '/data/anr/traces.txt': Is a directory
05-13 16:27:16.585: D/AndroidRuntime(1040): Shutting down VM
05-13 16:27:16.595: W/dalvikvm(1040): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-13 16:27:16.605: E/AndroidRuntime(1040): FATAL EXCEPTION: main
05-13 16:27:16.605: E/AndroidRuntime(1040): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.compsci_734p/com.example.compsci_734p.Compsci734MainActivity}: java.lang.RuntimeException: Binary XML file line #7: You must supply a layout_width attribute.
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.os.Looper.loop(Looper.java:137)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.main(ActivityThread.java:4424)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at java.lang.reflect.Method.invokeNative(Native Method)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at java.lang.reflect.Method.invoke(Method.java:511)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at dalvik.system.NativeStart.main(Native Method)
05-13 16:27:16.605: E/AndroidRuntime(1040): Caused by: java.lang.RuntimeException: Binary XML file line #7: You must supply a layout_width attribute.
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.content.res.TypedArray.getLayoutDimension(TypedArray.java:491)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.ViewGroup$LayoutParams.setBaseAttributes(ViewGroup.java:5318)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:5439)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.widget.LinearLayout$LayoutParams.<init>(LinearLayout.java:1776)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:1700)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.widget.LinearLayout.generateLayoutParams(LinearLayout.java:56)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:741)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.Activity.setContentView(Activity.java:1835)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at com.example.compsci_734p.Compsci734MainActivity.onCreate(Compsci734MainActivity.java:50)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.Activity.performCreate(Activity.java:4465)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-13 16:27:16.605: E/AndroidRuntime(1040):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-13 16:27:16.605: E/AndroidRuntime(1040):     ... 11 more
05-13 16:27:16.885: I/dalvikvm(1040): threadid=3: reacting to signal 3
05-13 16:27:16.885: I/dalvikvm(1040): Wrote stack traces to '/data/anr/traces.txt'
05-13 16:27:17.155: I/dalvikvm(1040): threadid=3: reacting to signal 3
05-13 16:27:17.165: I/dalvikvm(1040): Wrote stack traces to '/data/anr/traces.txt'
4

3 回答 3

0

谢谢大家!!!:) 我已经解决了它并从中制作了一个列表视图。这是我的工作代码:

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;





import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;



public class People extends Activity{

        ArrayList<String> items = new ArrayList<String>();
        static InputStream is = null;
        //private static String url = "";
        //private static String url = "http:...";
        private static String url = "http....";
        //URL requestUrl = new URL(url);
        JSONArray people = null;
        private static final String TAG_COURSES = "Courses";
        static JSONObject jObj = null;
        static String json = "";

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.people);
            new MyTasks().execute();
        }


        private class MyTasks extends AsyncTask<URL, Void, JSONObject> {

            @Override
            protected JSONObject doInBackground(URL... urls) {
               // return loadJSON(url);
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    //HttpPost httpPost = new HttpPost(url);
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);

                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
              try {
                /*BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "UTF-8"), 8);*/
                InputStream inputStream = is;
                GZIPInputStream input = new GZIPInputStream(inputStream);
                InputStreamReader reader = new InputStreamReader(input);
                BufferedReader in = new BufferedReader(reader);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                   //System.out.println(line);
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object

            try {

                JSONArray people = new JSONArray(json);
                //JSONArray people = new JSONArray(json);

                for (int i = 0; i < people.length(); i++) {
                    //System.out.println(courses.getJSONObject(i).toString());
                    JSONObject p = people.getJSONObject(i);

                    // Storing each json item in variable
                    String person_id = p.getString("someString1");


                    items.add(person_id);

                    /*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
                }


                //jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            } 

            // return JSON String
            return jObj;
            }

            protected void onPostExecute(JSONObject json) {
                ListView myListView = (ListView)findViewById(R.id.peopleList);
                myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
        }
        }
于 2013-05-21T06:57:49.393 回答
0

你的 xml 中有一些没有 layout_width 的东西。一切都必须有一个 layout_width 和 layout_height。

另外,我看到了你的下一个问题——NetworkOnMainthreadException。您正在 onClick 中执行 HTTP 请求。你不能这样做——你需要在另一个线程或 AsyncTask 中进行。

于 2013-05-13T04:28:43.620 回答
0

只需在单个不同的线程中进行 onClick .. 如下主线程异常的网络。

button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            new Thread(new Runnable(

try {

String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";
                HttpPost httppost = new HttpPost(url);
                try {
                    HttpParams p = new BasicHttpParams();
                    HttpClient httpclient = new DefaultHttpClient(p);
                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    String responseBody = httpclient.execute(httppost,
                            responseHandler);
                    JSONArray jArray = new JSONArray(responseBody);
                    String text="";
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject e = jArray.getJSONObject(i);
                            text = text + "Course ID : "+e.getString("courseField")+"\n";
                            text = text + "Course name : "+e.getString("titleField")+"\n";
                            text = text + "Semesters offered: "+e.getString("semesterField")+"\n";
                            //text = text + "Birthyear : "+e.getString("birthyear")+"\n";
                    }
                    Log.i(responseBody, text);
                    tv.setText(text);
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (Throwable t) {
                Toast.makeText(getBaseContext(), "Request failed: " + t.toString(),
                        Toast.LENGTH_LONG).show();
                t.printStackTrace();
            }    


            //tv.setText(result);
        }));

    });
于 2013-05-13T04:40:45.117 回答