I have a code that downloads videos from a URL. I am using AsyncTask. Now, what I want to do is notify the user via progress dialog of what video is being downloaded, or something like “Downloading Video 2 of 10”. I am using the following code:
//DOWNLOAD VIDEOS
private class downloadVideosAsync extends AsyncTask <String, String, String>{
protected void onPreExecute(){
super.onPreExecute();
MyActivity.this.mProgressDialog.setMessage("Downloading Videos...");
}
@Override
protected String doInBackground(String... strings){
try{
ArrayList<String> VideoNames = VideosM.getVideoNames();
ArrayList<String> VideoUrls = VideosM.getVideoUrls();
File vidFile = null;
int videoNamesLenght = VideoNames.size();
int x;
for(x = 0; x < videoNamesLenght; x++) {
//download video
String[] videoName = VideoNames.get(x).split("/");
String currentFile = videoName[0] + "." + videoName[1];
String currentFileURL = VideoUrls.get(x) + VideoNames.get(x);
vidFile = new File(Environment.getExternalStorageDirectory()
+ "/Engagia/Downloads/Videos/", currentFile);
if( !vidFile.exists() ){
int curr_vid = x + 1;
String ui_msg = "Downloading Videos " + curr_vid + " of " + videoNamesLenght + "...";
MyActivity.this.mProgressDialog.setMessage( ui_msg );
VideosC.downloadVideoFile(currentFile, currentFileURL, vidFile);
}
}
}catch (NullPointerException e){
Log.e(LOG_TAG, e.toString());
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
return null;
}
@Override
protected void onPostExecute(String lenghtOfFile) {
new downloadSlideshowsAsync().execute();
}
}
The code above give me an error:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
EDIT:
I also tried:
runOnUiThread(new Runnable() {
public void run() {
String ui_msg = "Downloading Videos " + curr_vid + " of " + videoNamesLenght + "...";
Engagia.this.mProgressDialog.setMessage( ui_msg );
Log.v("VideosController.java", ui_msg );
}
});
but gives me the same error…
Only a special thread, often called the “UI thread”, can modify UI elements. You can have specific code run on the UI thread by running things inside the
runOnUiThreadfunction that’s part of Activity class. For example: