NullPointer Exception in onPostExecute in AsyncTask


NullPointer Exception in onPostExecute in AsyncTask

我正在处理我的Web服务,我遇到了一个奇怪的问题。我无法解决这个问题,因为我是安卓开发的新手。我在异步任务的 onPostExecute() 方法中收到空指针异常。当我将结果与字符串进行比较时,就会发生这种情况。

if (result.contains("Duplicate"))           or 
if (result.equals("Duplicate"))             or
if (result.equalsIgnoreCase("Duplicate"))   or

这三个都给出了错误。我已经通过System.out.println(result)打印了结果的值;它显示

为了使我的问题更奇怪,这种情况只会偶尔发生,尤其是当我的老板测试它时。其他时候它工作得很好。设备和网络都保持不变。早些时候,它曾经只发生在模拟器上。我曾经重新启动日食,问题曾经得到解决。

请帮帮我!

法典

private void startDownload() {
    new AddTask().execute(FILENAME);
}
public class AddTask extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(ContactDetails.this, "Loading",
                "Please Wait...");
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

            if (result.contains("Duplicate")) { //---- here error comes
                int ecolor = -16777216; // whatever color you want
                String estring = "Account with this email already exists!!";
                ForegroundColorSpan fgcspan = new ForegroundColorSpan(
                        ecolor);
                SpannableStringBuilder ssbuilder = new SpannableStringBuilder(
                        estring);
                ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
                et2.setError(ssbuilder);
                dialog.dismiss();
            } else {
                Toast.makeText(ContactDetails.this, "Account Created!",
                        Toast.LENGTH_LONG).show();
                dialog.dismiss();
                myDialog = new Dialog(ContactDetails.this);
                myDialog.setContentView(R.layout.email_alert);
                myDialog.setTitle("Confirmation");
                myDialog.setCancelable(true);
                // for OK
                Button ok = (Button) myDialog.findViewById(R.id.alertOk);
                ok.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        Intent intent = new Intent(ContactDetails.this,
                                Login.class);
                        startActivity(intent);
                    }
                });
                myDialog.show();
            }
        }
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }
    @Override
    protected String doInBackground(String... params) {
        is = null;
            individual();

        return is;
    }

    public void individual() {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://website.com/contact.php");
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    10);
            nameValuePairs.add(new BasicNameValuePair("Name", str1));
            nameValuePairs.add(new BasicNameValuePair("Email", str2));
            nameValuePairs.add(new BasicNameValuePair("Password", str3));
            nameValuePairs.add(new BasicNameValuePair("Address", str5));
            nameValuePairs.add(new BasicNameValuePair("Pin", str11));
            nameValuePairs.add(new BasicNameValuePair("City", spt1));
            nameValuePairs.add(new BasicNameValuePair("State", str12));
            nameValuePairs.add(new BasicNameValuePair("phone_visibility",
                    str_radio));
            nameValuePairs.add(new BasicNameValuePair("No", str7));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // httpclient.execute(httppost);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = EntityUtils.toString(entity);
            JSONArray jArray = new JSONArray(is);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject jObject = jArray.getJSONObject(i);
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

---编辑---

结果获得空值的原因可能是什么?是网络问题吗?有没有办法确保我不会得到空结果?如果我得到空,我的应用程序将无法正常运行

检查您是否从结果中获取数据...

if(result!=null){
// here check  the things you need

}

它对我有用

在结果上添加对 NPE 的检查

@Override
protected void onPostExecute(String result)
{
    if(result == null)
    {
        // handle null result, debug or whatever
        return;
    }
    .... 
    //rest of your code
}

编辑我相信这是你的问题

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);

响应可能会获得空值,以便response.getEntity();引发异常,并且将达到is = EntityUtils.toString(entity);,因此它将具有空值并在您的 doInBackground 中返回is这是空:)因此,您需要处理该空值并接受有时您会得到空值的事实。干杯

检查result是否null。如果没有,则仅执行您的操作。像下面一样..

if(result!=null){
if (result.contains("Duplicate"))           or 
if (result.equals("Duplicate"))             or
if (result.equalsIgnoreCase("Duplicate"))   or
}

您在individual()中捕获了许多异常。当其中一个发生时,您的result可能仍然为空,但您不会知道。

您应该:

  1. 更改异常捕获代码并存储发生异常的其他信息,并在 onPostExecute 中使用该信息。

  2. 只需接受result可以为 null 并在 onPostExecute 中正确处理它(检查 null 并执行一些适当的操作)。

protected String doInBackground

返回字符串

您返回的是空值。

onPostExecute(String result) 

处理该字符串

不能在空值上调用"包含"。

修复:

    @Override
    protected String doInBackground(String... params) {
    is = individual();
    return is;
}
public String individual() {

。将您的 JSON 数据放入字符串中...