1

运行此代码时出现异常。我想解析一个 json 对象数组的 url:

package com.example.compsci_734t;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class UoaCompsciActivity extends Activity {

    private static String url = " http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";
    //URL requestUrl = new URL(url);
    JSONArray courses = null;
    private static final String TAG_COURSES = "Courses";

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


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

        @Override
        protected JSONObject doInBackground(URL... urls) {
            loadJSON(url);
            return null;
        }

        protected void onPostExecute(JSONObject json) {

            try {
                courses = json.getJSONArray(TAG_COURSES);

                // looping through all courses
                for (int i = 0; i < courses.length(); i++) {
                    JSONObject c = courses.getJSONObject(i);

                    // Storing each json item in variable
                    String course_id = c.getString("courseField:");
                    String course_name = c.getString("titleField:");
                    String course_semester = c.getString("semesterField:");



                    Log.v("--", "Course: \n" + " " + course_id + " " + course_name
                            + " " + course_semester);
                }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    }


    public JSONObject loadJSON(String url) {
        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
         JSONObject json = jParser.getJSONFromUrl(url);

        return json;
    }

}

这也是我的logcat:

05-13 20:29:05.118: I/dalvikvm(770): threadid=3: reacting to signal 3
05-13 20:29:05.128: I/dalvikvm(770): Wrote stack traces to '/data/anr/traces.txt'
05-13 20:29:05.418: D/gralloc_goldfish(770): Emulator without GPU emulation detected.
05-13 20:31:46.128: I/dalvikvm(842): threadid=3: reacting to signal 3
05-13 20:31:46.218: I/dalvikvm(842): Wrote stack traces to '/data/anr/traces.txt'
05-13 20:31:46.408: D/gralloc_goldfish(842): Emulator without GPU emulation detected.
05-13 22:06:17.298: I/dalvikvm(918): threadid=3: reacting to signal 3
05-13 22:06:17.389: I/dalvikvm(918): Wrote stack traces to '/data/anr/traces.txt'
05-13 22:06:17.549: D/gralloc_goldfish(918): Emulator without GPU emulation detected.
05-13 22:06:17.829: W/dalvikvm(918): threadid=11: thread exiting with uncaught exception (group=0x409c01f8)
05-13 22:06:17.839: E/AndroidRuntime(918): FATAL EXCEPTION: AsyncTask #1
05-13 22:06:17.839: E/AndroidRuntime(918): java.lang.RuntimeException: An error occured while executing doInBackground()
05-13 22:06:17.839: E/AndroidRuntime(918):  at android.os.AsyncTask$3.done(AsyncTask.java:278)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-13 22:06:17.839: E/AndroidRuntime(918):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.lang.Thread.run(Thread.java:856)
05-13 22:06:17.839: E/AndroidRuntime(918): Caused by: java.lang.IllegalArgumentException: Illegal character in scheme at index 0:  http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.net.URI.create(URI.java:727)
05-13 22:06:17.839: E/AndroidRuntime(918):  at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
05-13 22:06:17.839: E/AndroidRuntime(918):  at com.example.compsci_734t.JSONParser.getJSONFromUrl(JSONParser.java:36)
05-13 22:06:17.839: E/AndroidRuntime(918):  at com.example.compsci_734t.UoaCompsciActivity.loadJSON(UoaCompsciActivity.java:78)
05-13 22:06:17.839: E/AndroidRuntime(918):  at com.example.compsci_734t.UoaCompsciActivity$MyTask.doInBackground(UoaCompsciActivity.java:42)
05-13 22:06:17.839: E/AndroidRuntime(918):  at com.example.compsci_734t.UoaCompsciActivity$MyTask.doInBackground(UoaCompsciActivity.java:1)
05-13 22:06:17.839: E/AndroidRuntime(918):  at android.os.AsyncTask$2.call(AsyncTask.java:264)
05-13 22:06:17.839: E/AndroidRuntime(918):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-13 22:06:17.839: E/AndroidRuntime(918):  ... 5 more

更新的logcat:

05-13 22:15:01.438: I/dalvikvm(968): threadid=3: reacting to signal 3
05-13 22:15:01.598: I/dalvikvm(968): Wrote stack traces to '/data/anr/traces.txt'
05-13 22:15:01.718: D/gralloc_goldfish(968): Emulator without GPU emulation detected.
05-13 22:15:02.288: E/JSON Parser(968): Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
05-13 22:15:02.288: D/AndroidRuntime(968): Shutting down VM
05-13 22:15:02.288: W/dalvikvm(968): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-13 22:15:02.298: E/AndroidRuntime(968): FATAL EXCEPTION: main
05-13 22:15:02.298: E/AndroidRuntime(968): java.lang.NullPointerException
05-13 22:15:02.298: E/AndroidRuntime(968):  at com.example.compsci_734t.UoaCompsciActivity$MyTask.onPostExecute(UoaCompsciActivity.java:49)
05-13 22:15:02.298: E/AndroidRuntime(968):  at com.example.compsci_734t.UoaCompsciActivity$MyTask.onPostExecute(UoaCompsciActivity.java:1)
05-13 22:15:02.298: E/AndroidRuntime(968):  at android.os.AsyncTask.finish(AsyncTask.java:602)
05-13 22:15:02.298: E/AndroidRuntime(968):  at android.os.AsyncTask.access$600(AsyncTask.java:156)
05-13 22:15:02.298: E/AndroidRuntime(968):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
05-13 22:15:02.298: E/AndroidRuntime(968):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 22:15:02.298: E/AndroidRuntime(968):  at android.os.Looper.loop(Looper.java:137)
05-13 22:15:02.298: E/AndroidRuntime(968):  at android.app.ActivityThread.main(ActivityThread.java:4424)
05-13 22:15:02.298: E/AndroidRuntime(968):  at java.lang.reflect.Method.invokeNative(Native Method)
05-13 22:15:02.298: E/AndroidRuntime(968):  at java.lang.reflect.Method.invoke(Method.java:511)
05-13 22:15:02.298: E/AndroidRuntime(968):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-13 22:15:02.298: E/AndroidRuntime(968):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-13 22:15:02.298: E/AndroidRuntime(968):  at dalvik.system.NativeStart.main(Native Method)
05-13 22:15:02.889: I/dalvikvm(968): threadid=3: reacting to signal 3
05-13 22:15:02.919: I/dalvikvm(968): Wrote stack traces to '/data/anr/traces.txt'

完整的logcat:05-13 22:15:01.438:I/dalvikvm(968):threadid = 3:对信号3做出反应05-13 22:15:01.598:I/dalvikvm(968):将堆栈跟踪写入'/data /anr/traces.txt' 05-13 22:15:01.718: D/gralloc_goldfish(968): 没有检测到 GPU 仿真的仿真器。05-13 22:15:02.288: E/JSON Parser(968): 解析数据时出错 org.json.JSONException: 值

4

5 回答 5

2

该错误本身就是解释性的:

java.lang.IllegalArgumentException:索引 0处的方案中的非法字符

您需要删除 URL 中的起始空格字符:

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

更新:

更新问题后,现在问题出现在这一行:

courses = json.getJSONArray(TAG_COURSES);

因为您尚未初始化或设置它的值,courses这就是它给出NullPointerException错误的原因。

于 2013-05-13T10:12:32.530 回答
0
  1. 我已经解决了......试试它真的有效

package com.example.json_test;

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.client.ClientProtocolException;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity
{

        ArrayList<String> items = new ArrayList<String>();
        static InputStream is = null;
        private static String url = "http://redsox.tcs.auckland.ac.nz/734A/CSService.svc/courses";
        JSONArray people = null;
        private static final String TAG_COURSES = "codeField";
        private static final String TAG_SEMESTER="semesterField";
        static JSONObject jObj = null;
        static String json = "";

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


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

            @Override
            protected JSONObject doInBackground(URL... urls) 
            {
                try 
                {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    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 
              {
                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);
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) 
            {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
            try 
            {

                JSONArray people = new JSONArray(json);

                for (int i = 0; i < people.length(); i++) 
                {
                    JSONObject p = people.getJSONObject(i);
                    String Courses = p.getString(TAG_COURSES);
                    String semester=p.getString(TAG_SEMESTER);

                    items.add(Courses);
                    items.add(semester);
                }

            } catch (JSONException e) 
            {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            } 
            return jObj;
            }

            @SuppressWarnings({ "unchecked", "rawtypes" })
            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-10-01T12:47:34.920 回答
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-21T07:01:43.737 回答
0

嗨,它是由于网络服务中的一些问题,可能是由于编码问题而不是您或 android 的问题。就像您在该字符串中获得响应一样,只需将您获得的字符替换为“”。

response= response.replace("","");

然后在此之后进行解析。它对我有用。我希望它也适用于你......

于 2013-05-13T10:45:58.143 回答
0

它与 JSON 解析无关。

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

您必须从 url 字符串中删除初始空间

于 2013-05-13T10:12:48.597 回答