java.lang.RuntimeException:在android.os.AsyncTask执行doInBackground()时发生错误

时间:2014-10-29 18:06:34

标签: android

我初学者在android开发中,在下面的代码中得到错误。我已经看过和其他相关的帖子,我明白错误是在doInBackground方法而且理解和发生错误,但我无法理解哪个地方代码我必须改变

我的班级

public class FetchDrugTask extends AsyncTask<String, Void, JSONArray> {

    public ItemListScreen listScreen = null;
    private static final String TAG_DRUGS = "drugs";
    private static final String KEY_DRUGID = "id";
    private static final String KEY_DESCRIPTION = "description";
    private static final String KEY_PRESCRIPTION= "prescription";
    static final String KEY_NAME= "name";
    JSONArray drugs = null;

    @Override
    protected JSONArray doInBackground(String... urls) {

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(urls[0]);
        String responseBody = "{}";
        try {
            HttpResponse response = client.execute(get);
            responseBody = getResponseBody(response);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }

        try {

            JSONObject json = new JSONObject(responseBody);
            drugs = json.getJSONArray(TAG_DRUGS);
            return drugs;           
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONArray todoJsonArray) {
        //List<BusItem> routeItems = new ArrayList<BusItem>();
        ArrayList<HashMap<String, String>> drugList = new ArrayList<HashMap<String, String>>();

        for (int i = 0; i < todoJsonArray.length(); i++) {
            try {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject jsonObject = todoJsonArray.getJSONObject(i);
                map.put(getKeyDrugid(), jsonObject.getString(getKeyDrugid()));
                map.put(getKeyDescription(), jsonObject.getString(getKeyDescription()));
                map.put(getKeyPrescription(), jsonObject.getString(getKeyPrescription()));
                map.put(getKeyName(), jsonObject.getString(getKeyName()));

             // adding HashList to ArrayList
                drugList.add(map);

          //      routeItems.add(new BusItem(jsonObject.getString("bus_id"),jsonObject.getString("latitude"),jsonObject.getString("longitude")));
                Log.i("FETCHING DATA", jsonObject.getString(getKeyDrugid()));

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        listScreen.displayList(drugList);
    }

    public static String getKeyName() {
        return KEY_NAME;
    }

    private String getResponseBody(HttpResponse response) {
        StringBuilder builder = new StringBuilder();
        try {
            InputStream body = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(body));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "{}";
        }
    }

    public static String getKeyDrugid() {
        return KEY_DRUGID;
    }

    public static String getKeyDescription() {
        return KEY_DESCRIPTION;
    }

    public static String getKeyPrescription() {
        return KEY_PRESCRIPTION;
    }
}

我的JSOn

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            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);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                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);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            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 {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

错误

 10-29 18:42:09.857: E/AndroidRuntime(24733): FATAL EXCEPTION: AsyncTask #1
10-29 18:42:09.857: E/AndroidRuntime(24733): Process: com.drugfinder, PID: 24733
10-29 18:42:09.857: E/AndroidRuntime(24733): java.lang.RuntimeException: An error occured while executing doInBackground()
10-29 18:42:09.857: E/AndroidRuntime(24733):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.lang.Thread.run(Thread.java:841)
10-29 18:42:09.857: E/AndroidRuntime(24733): Caused by: java.lang.RuntimeException: org.json.JSONException: End of input at character 0 of 
10-29 18:42:09.857: E/AndroidRuntime(24733):    at com.drugfinder.library.FetchStoreTask.doInBackground(FetchStoreTask.java:57)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at com.drugfinder.library.FetchStoreTask.doInBackground(FetchStoreTask.java:1)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-29 18:42:09.857: E/AndroidRuntime(24733):    ... 4 more
10-29 18:42:09.857: E/AndroidRuntime(24733): Caused by: org.json.JSONException: End of input at character 0 of 
10-29 18:42:09.857: E/AndroidRuntime(24733):    at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at org.json.JSONTokener.nextValue(JSONTokener.java:97)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at org.json.JSONObject.<init>(JSONObject.java:155)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at org.json.JSONObject.<init>(JSONObject.java:172)
10-29 18:42:09.857: E/AndroidRuntime(24733):    at com.drugfinder.library.FetchStoreTask.doInBackground(FetchStoreTask.java:50)
10-29 18:42:09.857: E/AndroidRuntime(24733):    ... 7 more

Thnx提前

0 个答案:

没有答案