Android AsyncTask - doInBackground未运行

时间:2013-12-08 21:00:16

标签: java android json android-asynctask

我正在尝试使用AsyncTask发出HTTP请求并返回一些JSON,但由于某种原因,我的Async任务的doInBackground方法永远不会运行。 我已经在这个问题上看到了一些关于SO的解决方案,但似乎没有任何帮助 - 我也尝试使用常规线程而不是Async Task,但它似乎也有类似的问题。

我的片段类包含AsyncTask类:

public class ChallengeListFragment extends ListFragment {

    ...

    private ArrayList<Challenge> mChallenges;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.challenges_list_fragment_title);
        mChallenges = new ArrayList<Challenge>();


        new JSONRetriever().execute("URL_HERE");

        ...
    }


    // Async Task class to perform HTTP requests in a separate thread:
    private class JSONRetriever extends AsyncTask<String, Void, JSONObject>{

        JSONArray challengesJsonArray;
        JSONObject challengesJsonObject;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i(LOG_TAG, "onPreExecute()!!!");
        }

        @Override
        protected JSONObject doInBackground(String... url) {
            challengesJsonObject = jParser.getJSONFromUrl(url[0]);
            return challengesJsonObject;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
           super.onPostExecute(jsonObject);
           Log.i(LOG_TAG, jsonObject.toString());
        }
    }
}

...和我的JSONParser课程,取自常用的指南或答案:

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

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

            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, "iso-8859-1"), 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;

    }
}

我已多次执行该程序,并且在onPreExecute()运行时,doInBackground()从不运行。在发生这种情况时,我没有运行任何其他异步任务。

任何建议都非常感谢,谢谢。

更新 根据评论中的建议,我尝试删除doInBackground()中的代码,并在其中放置一个日志语句,看起来它实际上正在运行,尽管在我执行程序时似乎从未进入过该方法。

发生这种情况时,完整的LogCat是:

850-850/com.ethanml.proveit I/PROVEIT﹕ onPreExecute()!!!
12-08 19:01:45.952      850-850/com.ethanml.proveit D/AndroidRuntime﹕ Shutting down VM
12-08 19:01:45.952      850-878/com.ethanml.proveit D/PROVEIT﹕ DO IN BACKGROUND
12-08 19:01:45.962      850-850/com.ethanml.proveit W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41465700)
12-08 19:01:45.992      850-850/com.ethanml.proveit E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ethanml.proveit/com.ethanml.proveit.ChallengeListActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.ethanml.proveit.ChallengeListFragment.onCreate(ChallengeListFragment.java:55)
            at android.app.Fragment.performCreate(Fragment.java:1673)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:854)
            at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
            at android.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
            at android.app.Activity.performStart(Activity.java:5142)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

日志中引用的第55行的ChallengeListFragment上的NPE指的是我用来逐步执行JSON数组的for循环,该数组应该在异步任务的onPostExecute中填充 - 因为这似乎永远不会被执行, JSONArray为null,程序崩溃。

0 个答案:

没有答案