我如何在android中使用json和asynctask解析这些数据

时间:2013-05-11 00:17:41

标签: android json parsing android-asynctask

以下数据在网址中:我如何使用JSon解析课程代码:COMPSCI 101,提供的学期:暑期学校,第一学期,第二学期 课程名称:编程原理.............等等?

[{“codeField”:“COMPSCI 101”,“semesterField”:“暑期学校;第一学期;第二学期”,“titleField”:“编程原理”},{“codeField”:“COMPSCI 105”, “semesterField”:“暑期学校;第一学期;第二学期”,“titleField”:“计算机科学原理”},{“codeField”:“COMPSCI 111 / 111G”,“semesterField”:“暑期学校;第一学期;第2学期“,”titleField“:”掌握网络空间:实用计算概论“}]

我尝试了这段代码,但它在运行时在模拟器上抛出了一个例外,说“不幸的是JsonParsing已停止工作”。请原谅我天真的错误,因为我是android的新手: package com.example.jsonparsing;

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.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.widget.ArrayAdapter;

public class JsonActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        setListAdapter(new ArrayAdapter(
                this,android.R.layout.simple_list_item_1,
                this.populate()));
    }

    private ArrayList<String> populate() {
        ArrayList<String> items = new ArrayList<String>();

        try {
            URL url = new URL
            ("http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses");
            HttpURLConnection urlConnection =
                (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
                        // gets the server json data
            BufferedReader bufferedReader =
                new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream()));

            String next;
            while ((next = bufferedReader.readLine()) != null){
                JSONArray ja = new JSONArray(next);

                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    items.add(jo.getString("text"));

                }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return items;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_json, menu);
        return true;
    }

}

这也是我的logcat:

05-11 12:25:34.151: I/Process(77): Sending signal. PID: 722 SIG: 3
05-11 12:25:34.161: I/dalvikvm(722): threadid=3: reacting to signal 3
05-11 12:25:34.231: I/dalvikvm(722): Wrote stack traces to '/data/anr/traces.txt'
05-11 12:25:34.281: D/AndroidRuntime(722): Shutting down VM
05-11 12:25:34.281: W/dalvikvm(722): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-11 12:25:34.291: E/AndroidRuntime(722): FATAL EXCEPTION: main
05-11 12:25:34.291: E/AndroidRuntime(722): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonparsing/com.example.jsonparsing.JsonActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.os.Looper.loop(Looper.java:137)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.main(ActivityThread.java:4424)
05-11 12:25:34.291: E/AndroidRuntime(722):  at java.lang.reflect.Method.invokeNative(Native Method)
05-11 12:25:34.291: E/AndroidRuntime(722):  at java.lang.reflect.Method.invoke(Method.java:511)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-11 12:25:34.291: E/AndroidRuntime(722):  at dalvik.system.NativeStart.main(Native Method)
05-11 12:25:34.291: E/AndroidRuntime(722): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ListActivity.onContentChanged(ListActivity.java:243)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:254)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.Activity.setContentView(Activity.java:1835)
05-11 12:25:34.291: E/AndroidRuntime(722):  at com.example.jsonparsing.JsonActivity.onCreate(JsonActivity.java:26)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.Activity.performCreate(Activity.java:4465)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-11 12:25:34.291: E/AndroidRuntime(722):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-11 12:25:34.291: E/AndroidRuntime(722):  ... 11 more
05-11 12:25:34.301: W/ActivityManager(77):   Force finishing activity com.example.jsonparsing/.JsonActivity
05-11 12:25:34.301: W/WindowManager(77): Failure taking screenshot for (180x300) to layer 21010
05-11 12:25:34.574: I/Process(77): Sending signal. PID: 722 SIG: 3
05-11 12:25:34.574: I/dalvikvm(722): threadid=3: reacting to signal 3
05-11 12:25:34.581: I/dalvikvm(722): Wrote stack traces to '/data/anr/traces.txt'
05-11 12:25:34.825: W/ActivityManager(77): Activity pause timeout for ActivityRecord{41b22010 com.example.jsonparsing/.JsonActivity}
05-11 12:25:34.831: I/Process(77): Sending signal. PID: 722 SIG: 3
05-11 12:25:34.831: I/dalvikvm(722): threadid=3: reacting to signal 3
05-11 12:25:34.851: I/dalvikvm(722): Wrote stack traces to '/data/anr/traces.txt'
05-11 12:25:35.041: W/NetworkManagementSocketTagger(77): setKernelCountSet(10040, 0) failed with errno -2
05-11 12:25:45.058: W/ActivityManager(77): Activity destroy timeout for ActivityRecord{41b22010 com.example.jsonparsing/.JsonActivity}

3 个答案:

答案 0 :(得分:0)

这是您当前错误的根

Your content must have a ListView whose id attribute is 'android.R.id.list'

使用ListActivity时,ListView需要id。因此,在您的activity_json.xml中,您需要ListView喜欢

<ListView
     android:id="@android:id/list"

此外,您的下一个问题是尝试在UI上进行网络搜索,但这是一个单独的问题。 Here is a SO answer of mine涵盖AsyncTask的基本内容。试一试并在遇到特定问题时发布。请记住,不要将UI内容放入doInBackground()

答案 1 :(得分:0)

即使您不喜欢在我没有严格要求的情况下使用外部库,我建议您使用gson库进行Jason操作

https://code.google.com/p/google-gson/

使用这个库,您可以将任何Json转换为相对的pojo,而无需使用一行代码。

当然,您必须将网络操作至少放入asynctask或runnable对象。

答案 2 :(得分:0)

我已经解决了这个问题。这是我的代码。谢谢大家。我还设法将解析后的输出转换为listview:)

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://blahblah";
        //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");
                    //String course_name = c.getString("someString2");
                    //String course_semester = c.getString("someString3");

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