如何处理执行doInBackground()

时间:2017-03-26 17:02:51

标签: java android android-asynctask httpurlconnection

我在我的应用中使用Asynctask从服务器检索数据。 当我的应用程序连接到Internet时,它工作正常,但是当我断开连接时,它会突然停止。

这是我的代码:

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();
    }
}

我收到了错误:

  

-FATAL EXCEPTION:AsyncTask#3                                                                                    流程:kuldeep.mourya.com.smartcollege,PID:10617                                                                                    java.lang.RuntimeException:执行时发生错误   doInBackground()                                                                                        在android.os.AsyncTask $ 3.done(AsyncTask.java:309)                                                                                        在   java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)                                                                                        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)                                                                                        在java.util.concurrent.FutureTask.run(FutureTask.java:242)                                                                                        在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:234)                                                                                        在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)                                                                                        在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:588)                                                                                        在java.lang.Thread.run(Thread.java:818)                                                                                     引起:java.lang.NullPointerException:尝试调用虚拟   null对象上的方法'void java.io.BufferedReader.close()'   参考                                                                                        在   kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment $ JsonTask.doInBackground(CollegeNewsFragment.java:223)                                                                                        在   kuldeep.mourya.com.smartcollege.FragmentProfessor.CollegeNewsFragment $ JsonTask.doInBackground(CollegeNewsFragment.java:148)                                                                                        在android.os.AsyncTask $ 2.call(AsyncTask.java:295)

有谁知道我收到此错误的原因?

WOOW !!!我在分离异常尝试捕获块时得到了答案!

//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 个答案:

答案 0 :(得分:0)

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

在上面的代码行中,您在哪里声明并初始化BufferedReader?

当连接可用时,您很可能肯定会将数据导入流中。但是当你没有连接到互联网时,流是空的。

我的建议是对代码进行一些小改动:

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

将它放在一个单独的try..catch中并首先执行此操作。如果成功,请继续阅读流的代码。

还有一个变化是,然后声明BufferredReader以及每次使用的位置(这通常是一种很好的做法)。就像下面的代码片段一样:

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