AsyncTask的doInBackground()方法中的NullPointer异常

时间:2015-02-06 14:57:52

标签: java android android-asynctask

我试图将我从Facebook api获得的用户详细信息存储到使用php的数据库中。我使用JSONParser类来执行返回JSON对象的POST。当我在JSONParser类中调用makeHttpRequest方法时AsyncTask在另一个类中,我得到一个空指针异常。我检查我传递的任何参数是否为空,但它们不是,并且无法理解为什么我无法得到响应。我试过从SO中提出的类似问题中找到答案,但这是徒劳的。请帮助我。谢谢

这是尝试在JSONparser类中调用makeHTTPRequest方法的类中的AsyncTask:

private class CreateUser extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

          //  Log.d("email", email);
            pDialog = new ProgressDialog(FbProfileActivity.this);
            pDialog.setMessage("Creating User...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
            // TODO Auto-generated method stub
             // Check for success tag
            int success;

           try {
                // Building Parameters
       //       Log.d("param_username", username);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
            //    params.add(new BasicNameValuePair("age", age));
               params.add(new BasicNameValuePair("gender",gender));
                params.add(new BasicNameValuePair("email", email));
               // params.add(new BasicNameValuePair("location", location));
                Log.d("params","params" + params);


              Log.d("JsonParser's URL", "params" +REGISTER_URL );
                Log.d("request!", "starting",new Exception());                  //Posting user data to script 
                JSONObject json = jsonParser.makeHttpRequest(REGISTER_URL, "POST", params);

                // full json response
              //  Log.d("Registering attempt", json.toString());

                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Created", json.toString());                 
                    finish();
                    return json.getString(TAG_MESSAGE);
                }else{
                    Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
                    return json.getString(TAG_MESSAGE);

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

            return null;

        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if (file_url != null){
                Toast.makeText(FbProfileActivity.this, file_url, Toast.LENGTH_LONG).show();
            }

}
}

这是我得到nullpointer异常的行:

JSONObject json = jsonParser.makeHttpRequest(REGISTER_URL, "POST", params);

这是JSONParser类的makeHttpRequest方法:

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {
  Log.d(TAG,"makeHttpRequest() is called");
    // 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, "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;

}

堆栈追踪:

02-06 19:28:13.720: D/request!(2247): starting
02-06 19:28:13.720: D/request!(2247): java.lang.Exception
02-06 19:28:13.720: D/request!(2247):   at       com.example.letschatindia.FbProfileActivity$CreateUser.doInBackground(FbProfileActivity.java:448)
02-06 19:28:13.720: D/request!(2247):   at com.example.letschatindia.FbProfileActivity$CreateUser.doInBackground(FbProfileActivity.java:1)
02-06 19:28:13.720: D/request!(2247):   at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-06 19:28:13.720: D/request!(2247):   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-06 19:28:13.720: D/request!(2247):   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-06 19:28:13.720: D/request!(2247):   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-06 19:28:13.720: D/request!(2247):   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-06 19:28:13.720: D/request!(2247):   at java.lang.Thread.run(Thread.java:841)
02-06 19:28:13.721: W/dalvikvm(2247): threadid=19: thread exiting with uncaught exception (group=0x4165fd40)
02-06 19:28:13.723: E/AndroidRuntime(2247): FATAL EXCEPTION: AsyncTask #5
02-06 19:28:13.723: E/AndroidRuntime(2247): Process: com.example.letschatindia, PID: 2247
02-06 19:28:13.723: E/AndroidRuntime(2247): java.lang.RuntimeException: An error occured while executing doInBackground()
02-06 19:28:13.723: E/AndroidRuntime(2247):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.lang.Thread.run(Thread.java:841)
02-06 19:28:13.723: E/AndroidRuntime(2247): Caused by: java.lang.NullPointerException
02-06 19:28:13.723: E/AndroidRuntime(2247):     at com.example.letschatindia.FbProfileActivity$CreateUser.doInBackground(FbProfileActivity.java:449)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at com.example.letschatindia.FbProfileActivity$CreateUser.doInBackground(FbProfileActivity.java:1)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-06 19:28:13.723: E/AndroidRuntime(2247):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)

2 个答案:

答案 0 :(得分:1)

我认为jsonParser为null,必须在使用它之前进行实例化。

答案 1 :(得分:0)

您的jsonParser为空。我无法看到你在哪里实例化它,所以检查你的代码以避免在创建对象之前使用它。