Arraylist在调用Async任务后返回null值

时间:2016-02-09 23:03:46

标签: android arraylist android-asynctask

我在获取ArrayList的值时遇到问题。当我调试时,数组列表有一个值,但当它离开循环时,ArrayList值为null。请帮我解决这个问题。异步任务可能是问题。

private List testDownloadSpeed(DownloadTestInformation download) throws IOException {

    List<DownloadTestResult> results = new ArrayList<>();

    if (download.downloadUrls != null && download.downloadUrls.size() > 0) {
        for (String urlString : download.downloadUrls) {

            Double throughput = null;

                downloadSpeedTestTask  = new DownloadSpeedTestTask();
                String[] params = new String[2];
                params[0] = urlString;
                params[1] = download.timeboxInSeconds;
                try {
                    throughput = downloadTestTask.execute(params).get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

            results.add(new DownloadTestResult(urlString, throughput));
        }
    }

    if (!results.isEmpty()) {
        return results;
    } else {
        return null;
    }
}

AsyncTask类:

protected class DownloadTestTask extends AsyncTask<String, Void, Double> {

    @Override
    protected Double doInBackground(String... URLSting) {

        try {
            URL url = new URL(URLSting[0]);
            Long timeout = Long.valueOf(URLSting[1]);

            if (url != null) {
                int totalSize = 0;
                HttpURLConnection connection = null;
                try {
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout((int) (timeout * 1000));
                    connection.connect();

                    int status = connection.getResponseCode();
                    if (status >= 400) {
                        throw new RuntimeException("Invalid status from server: " + status);
                    }
                    totalSize = connection.getContentLength();

                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        try {
                            connection.disconnect();

                            return Double.valueOf(totalSize);
                        } catch (Exception ex) {
                            logger.log(Level.WARNING, "Unable to close connection", ex);
                        }
                    }
                }

            } else {
                logger.log(Level.WARNING, "Unable to parseURL:", URLSting);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

}

1 个答案:

答案 0 :(得分:2)

在使用结果值时,不得使用execute方法。您应该将所有必须在AsyncTask之后执行的代码放在重写方法onPostExecute中。

doInBackground返回值并调用onPostExecute回调。

但在您的情况下,您可以在doInBackground

中执行所有操作
protected class DownloadTestTask extends AsyncTask<DownloadTestInformation, Void, List<DownloadTestResult>> {

    @Override
    protected Double doInBackground(String... params) {

        List<DownloadTestResult> results = new ArrayList<>();
        DownloadTestInformation download = params[0];

        if (download.downloadUrls != null && download.downloadUrls.size() > 0) {
            for (String urlString : download.downloadUrls) {

                Double throughput = null;

                downloadSpeedTestTask  = new DownloadSpeedTestTask();

                URL url = new URL(urlString);
                Long timeout = Long.valueOf(download.timeboxInSeconds);

                if (url != null) {
                    int totalSize = 0;
                    HttpURLConnection connection = null;
                    try {
                        connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("GET");
                        connection.setConnectTimeout((int) (timeout * 1000));
                        connection.connect();

                        int status = connection.getResponseCode();
                        if (status >= 400) {
                            throw new RuntimeException("Invalid status from server: " + status);
                        }
                        totalSize = connection.getContentLength();

                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (connection != null) {
                            try {
                                connection.disconnect();

                                return Double.valueOf(totalSize);
                            } catch (Exception ex) {
                                logger.log(Level.WARNING, "Unable to close connection", ex);
                            }
                        }
                    }

                } else {
                    logger.log(Level.WARNING, "Unable to parseURL:", URLSting);
                }

                results.add(new DownloadTestResult(urlString, throughput));
            }
        }

        if (!results.isEmpty()) {
            return results;
        } else {
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<DownloadTestResult> result) {
        //Whatever you need to do afterwards
    }

}