Issue
I am reading up on AsyncTask from this tutorial. And the following piece of code is given as an example:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
"Once created, a task is executed very simply:"
new DownloadFilesTask().execute(url1, url2, url3);
I have two questions from this:
What does the line
totalSize += Downloader.downloadFile(urls[i]);
do? I'm guessing that totalSize stores the size of the downloaded files, andDownloader.downloadFile(urls[i])
downloads the file from the URL passed in and returns the size of the file downloaded. Am I right?This question is about generic types in java. From , I think we are passing three different URL's (web addresses from which the files will be downloaded) to our parameterized class DownloadFilesTask. But the type arguments in the declaration of the class (
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
) are URL, Integer, and Long? Why? How can a url object be casted to an Integer? I think I am terribly wrong somewhere, please correct me and I'll be grateful.
Thank you.
Solution
If we will look on this line:
showDialog("Downloaded " + result + " bytes"); We can understand that
Downloader.downloadFile
return size of file in bytes. So you are right.Just take a look this code, and you will understand parameterization
public abstract class AsyncTask < Params, Progress, Result> { protected abstract Result doInBackground(Params... params); protected void onPostExecute(Result result) {} protected void onProgressUpdate(Progress... values) {} }
... (3 dots) - it means that you can pass here 1,2,3...∞ number of arguments with certain type.
Let me know if something is still not clear
Answered By - Divers
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.