如何在android中使用json和aync任务解析这些数据?

时间:2022-12-01 18:27:24

The below data is in a url: How do i parse it using JSon to read Course Code: COMPSCI 101, Semesters offered: Summer School, Semester 1, Semester 2 Course title: Principles of Programming.............and so on??

下面的数据是在一个url中:我如何使用JSon解析它来读课程代码:COMPSCI 101, Semesters提供的:Summer School,学期1,第二学期课程名称:编程的原则,等? ?

[{"codeField":"COMPSCI 101","semesterField":"Summer School; Semester 1; Semester 2","titleField":"Principles of Programming"},{"codeField":"COMPSCI 105","semesterField":"Summer School; Semester 1; Semester 2","titleField":"Principles of Computer Science"},{"codeField":"COMPSCI 111/111G","semesterField":"Summer School; Semester 1; Semester 2","titleField":"Mastering Cyberspace: An Introduction to Practical Computing"}]

[{“codeField”:“COMPSCI 101”,“semesterField”:“暑期学校;学期1;第2学期,“titleField”:“编程原理”,{“codeField”:“COMPSCI 105”,“semesterField”:“Summer School;学期1;“计算机科学原理”},{“codeField”:“COMPSCI 111/111G”,“semesterField”:“暑期学校”;学期1;第2学期,“titleField”:“掌握网络空间:实用计算入门”}

I tried this code but it throws me an excetion at runtime on the emulator saying "unfortunately JsonParsing has stopped working". Please forgive my naive mistakes since i am new to android: package com.example.jsonparsing;

我尝试了这段代码,但它在运行时在模拟器上抛出了一个异常,说“不幸的是,json解析停止了工作”。请原谅我幼稚的错误,因为我是android的新手:package com. example.json解析;

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

}

Also this is my logcat:

这是我的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 个解决方案

#1


0  

Even if you could dislike to use external libs when not strictly necessary as I try to do I recommend you to use gson library for Jason manipulation

即使您不喜欢使用外部的libs,但我建议您使用gson库来进行Jason操作。

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

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

With this library you can convert any Json to the relative pojo without any effort only with a line of code.

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

And of course you must put the network operations at least into an asynctask or a runnable object.

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

#2


0  

This is the root of your current error

这是当前错误的根源。

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

When using ListActivity you need a ListView with this id. So in your activity_json.xml you need a ListView like

在使用ListActivity时,需要使用该id的ListView,所以在activity_json中。xml需要一个列表视图。

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

Also, your next problem will be trying to do network stuff on the UI but that is a separate issue. Here is a SO answer of mine that covers the basic of AsyncTask. Give it a try and post when you have a specific problem with it. Just remember not to put UI stuff in doInBackground()

另外,您的下一个问题将是尝试在UI上进行网络操作,但这是一个单独的问题。下面是我的一个答案,它涵盖了AsyncTask的基本内容。当你有一个特定的问题时,试一试。记住不要把UI放到doInBackground()中

#3


0  

I have resolved this. Here is my Code. Thanks people. I also managed to convert the parsed output into a listview :)

我已经解决了这个问题。这是我的代码。感谢的人。我还设法将解析后的输出转换为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));
        }
        }
}

#1


0  

Even if you could dislike to use external libs when not strictly necessary as I try to do I recommend you to use gson library for Jason manipulation

即使您不喜欢使用外部的libs,但我建议您使用gson库来进行Jason操作。

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

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

With this library you can convert any Json to the relative pojo without any effort only with a line of code.

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

And of course you must put the network operations at least into an asynctask or a runnable object.

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

#2


0  

This is the root of your current error

这是当前错误的根源。

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

When using ListActivity you need a ListView with this id. So in your activity_json.xml you need a ListView like

在使用ListActivity时,需要使用该id的ListView,所以在activity_json中。xml需要一个列表视图。

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

Also, your next problem will be trying to do network stuff on the UI but that is a separate issue. Here is a SO answer of mine that covers the basic of AsyncTask. Give it a try and post when you have a specific problem with it. Just remember not to put UI stuff in doInBackground()

另外,您的下一个问题将是尝试在UI上进行网络操作,但这是一个单独的问题。下面是我的一个答案,它涵盖了AsyncTask的基本内容。当你有一个特定的问题时,试一试。记住不要把UI放到doInBackground()中

#3


0  

I have resolved this. Here is my Code. Thanks people. I also managed to convert the parsed output into a listview :)

我已经解决了这个问题。这是我的代码。感谢的人。我还设法将解析后的输出转换为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));
        }
        }
}