I am having problem getting the value of the ArrayList. When I debug the array list has a value but when it get out of the loop the ArrayList value is null. Please help me fix this issue. Async task might be the issue.
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;
}
}
The AsyncTask class:
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;
}
}