Httpget Null Error

时间:2015-08-17 15:43:37

标签: php android android-asynctask http-get

我正在尝试获取.php

的json数据
  class RequestTask2 extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;

        try {

            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.


                response.getEntity().getContent().close();
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..

        } catch (IOException e) {
            //TODO Handle problems..

        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(result.equals(null)){

        }else{
       Title=result;}
    }
}

 new RequestTask2().execute("http://www.****.com/test/***.php"); (With handler)

当有活跃的互联网时,它运作良好。但我不需要互联网检查方法。我已经完成了它并且错误是在哪里,当执行asynctask时没有互联网时返回null。

请帮助我在没有互联网的情况下检查Null或停止任务。该错误导致强制关闭app。谢谢你有趣的我的问题。希望它能很快得到解决。

1 个答案:

答案 0 :(得分:0)

如果internet为null,则您的方法doinbackground返回null。 在你的方法onPostExecute中,“result”为空。

此代码抛出nullPointerException,因为您尝试访问空对象。

if(result.equals(null)) {
 ...
}

替换为

if(result != null) {
  Title=result;
}

如果你想取消你的任务,你可以在doInBackground方法(或你想要的地方)上调用cancel(true),并且不会调用方法“onPostExecute”。