android - Arraylist 在调用异步任务后返回空值

标签 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;
    }

}

最佳答案

在使用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
    }

}

关于android - Arraylist 在调用异步任务后返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303920/

相关文章:

java - 将 XML 添加到具有非重复模式 Java 的数组列表

android - 获取新保存数据的数据库 ID 并将其传递给之前的 Activity

android - 在批处理文件中解锁 adb logcat

android - Bonjour 服务发现未通过 Android 的 API 完成。我是不是遗漏了什么,或者我应该只使用 JmDNS?

android - 在应用程序对象中创建线程

java - 编辑后继续打印整个数组列表

android Listview删除一个项目并刷新列表

java - 如何将数组列表从适配器传递到 fragment ?

java - AsyncTask 更改 BaseAdapter (ListAdapter) 中的 ViewGroup 属性

java - 删除 UI 线程中已发送的消息