android.view.ViewRoot $ CalledFromWrongThreadException: solo el hilo original que creó una jerarquía de vistas puede tocar sus vistas.
Estoy desarrollando una aplicación de Android en la que necesito mostrar imágenes después de descargarlas del servidor y cuando la descarga continúa, se muestra un cuadro de diálogo de progreso. Para eso estoy usando una clase asynctask. Estoy usando el siguiente código fuente para ello.
private void startDownload() {
new DownloadFileAsync().execute(imageUrl);
image.setImageBitmap(bitmap);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
dialog = new ProgressDialog(this);
dialog.setTitle("Loading");
dialog.setMessage("Please wait...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();
return dialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
int count;
URL myFileUrl;
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
try {
myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
int lenghtOfFile = conn.getContentLength();
//conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl)
.getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
byte data[] = new byte[1024];
System.out.println("mmmmmmmmmmmm");
long total = 0;
System.out.println("nnnnnnnnnn");
while ((count = ((InputStream) new URL(imageUrl)
.getContent()).read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
for(int l=0;l<4;l++){
if(listObject.get(l).getImage()!="")
image.setImageBitmap(bitmap);
}}
}
catch(Exception e){
System.out.println(e);}
return null;
}
protected void onProgressUpdate(String... progress) {
dialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
image.setImageBitmap(bitmap);
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
Pero dando la siguiente excepción
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
No puedo resolver el problema. ¿Alguien puede ayudarme con esto? Gracia