3
votes

I am using Asynctask in my app to retrieve data from a server. When my app is connected to the Internet it works fine, but when I disconnect, it suddenly force-stops.

Here's my code:

try {
    URL url = new URL("http://javalovers.net16.net/showdata.php");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.connect();
    switch (connection.getResponseCode()) {
        case HttpURLConnection.HTTP_OK:
            InputStream stream = connection.getInputStream(); //here getting response
            br = new BufferedReader(new InputStreamReader(stream));
            String line = "";
            while ((line = br.readLine()) != null) {
                // buffer.append(line);
                str = str + line;
            }
            break; // fine, go on
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
            break; // retry
        case HttpURLConnection.HTTP_UNAVAILABLE:
            break; // retry, server is unstable
        default:
            break; // abort
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
    try {
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I'm getting the error:

-FATAL EXCEPTION: AsyncTask #3 Process: kuldeep.mourya.com.smartcollege, PID: 10617 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference at kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment$JsonTask.doInBackground(CollegeNewsFragment.java:223) at kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment$JsonTask.doInBackground(CollegeNewsFragment.java:148) at android.os.AsyncTask$2.call(AsyncTask.java:295)

Does anyone know why I am getting this error?

woow!!! i got answer while separating exception try catch block!

//URL url=new URL("http://javalovers.net16.net/showdata.php");
        URL url = null;// this api link
        try {
            url = new URL("http://vcetsmart.netne.net/showdata.php");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            connection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        try {
            connection.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try{
            if(connection.getResponseCode()==200)
            {
                //Toast.makeText(getBaseContext(),"Everything is right",Toast.LENGTH_SHORT).show();
                InputStream stream=connection.getInputStream(); //here getting response
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                String line = "";
                while ((line = br.readLine()) != null) {
                    // buffer.append(line);
                    str=str+line;
                }
            }
            else {
                Toast toast= Toast.makeText(getActivity(),"Something goes wrong", Toast.LENGTH_LONG);
                toast.show();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return str;
1

1 Answers

0
votes
br = new BufferedReader(new InputStreamReader(stream));

In the above line of code, where did you declare and initialize the BufferedReader ?

When the connection is available, there is high probability that you will definitely get the data into your stream. But when you are not connected to internet the stream is a null.

What i advice you is a small change in your code:

URL url = new URL("http://javalovers.net16.net/showdata.php");
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.connect();

Put this in a separate try..catch and do it first. If this is successful, proceed to the code of reading the stream.

Also one more change is, declare the BufferredReader then and where you are using every time(this is generally a good practice). Like the code snippet below:

BufferredReader br = new BufferedReader(new InputStreamReader(stream));