Search code examples
phpandroidandroid-asynctaskhttp-get

Httpget Null Error


I am trying to get json data of .php

  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)

It works very well when there is active internet . But I don't need Internet checking method. I've already done it and the error is where, Returning null when no internet while executing asynctask.

Please kindly help me how to check Null or stop task when no internet. The error caused force close app. Thank you for interesting my problem. And Hope it'll be solved soon .


Solution

  • If internet is null your method doinbackground return null. And in your method onPostExecute "result" is null.

    this code throw nullPointerException because you try to access on a null object.

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

    replace it with

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

    If you want to cancel your task you can call cancel(true) on your doInBackground method (or where you want ) and the method "onPostExecute" will not be call.