有时在AsyncTask中返回值为null

时间:2018-01-01 20:45:58

标签: android android-asynctask

我通过调用简单的选择查询来接收JSON格式的值。 我正在使用AsyncTask。 问题是它有时候工作正常,但有时response_value为空而没有任何变化。 我该怎么办? 我错过了什么?

代码 doInBackground(String... strings)

URL url = new URL(GetUrl.URL_MAIN_CATEGORIES_DATA);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String response_value = "";
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    response_value += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return response_value;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

1 个答案:

答案 0 :(得分:2)

尝试在catch块中记录异常,而不是打印堆栈跟踪。

Log.e("Yourtag","Exception occurred",e);

你必须得到一个异常,但你无法在android上看到堆栈跟踪。这是它有时可以工作的唯一方式,有时则不会。