2011-10-24 5 views
3

Je crée une application Android qui est mise à jour. Pour cela, j'ai besoin d'une fonction simple qui peut télécharger un fichier et montrer la progression actuelle dans un ProgressDialog. Je sais comment faire pour télécharger le fichier, mais je ne suis pas sûr de savoir comment afficher la progression actuelle. J'utilise la méthode suivante pour télécharger des images.Android: affichage de la boîte de dialogue de progression

public Bitmap DownloadFile(String url){ 
URL myFileUrl; 
Bitmap bitmap=null; 
try { 
myFileUrl = new URL(imageUrl); 
    HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); 
    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,80 , 80, true); 
    System.out.println("name of butmap"+bitmap.toString()); 

} catch (Exception e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
return bitmap; 

} 

Et voici ma async classe de tâche:

public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> { 

    int myProgress; 

    @Override 

    protected void onPostExecute(Bitmap result) { 
    dialog.dismiss(); 
    iv.setVisibility(View.VISIBLE); 
    iv.setImageBitmap(result); 
    System.out.println("bbbbbbbbb"); 
    System.out.println("post execute"); 
    } 

@Override 
protected void onPreExecute() { 
    System.out.println("pre execute"); 
    dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait..."); 

} 

@Override 
protected Bitmap doInBackground(String...paths) { 
    System.out.println(imageUrl+" imageurl"); 
    return DownloadFile(imageUrl); 

    } 
@Override 
protected void onProgressUpdate(Integer... values) { 
    // TODO Auto-generated method stub 
     progressBar.setProgress(values[0]); 
} 

} 

et je vous appelle la méthode dans la classe d'adaptateur suivant:

public class ImageAdapter extends BaseAdapter { 
     Context mContext; 
    public String[] stringOnTextView; 

    public ImageAdapter(Context c) { 
     mContext = c; 
    } 

public ImageAdapter(Context Context, 
    String[] stringOnTextView) { 
    this.mContext=Context; 
    this.stringOnTextView=stringOnTextView; 
} 

public int getCount() { 
     return stringOnTextView.length; 
    } 


public Object getItem(int position) { 
     return null; 
    } 

    public long getItemId(int position) { 
     return position; 
    } 


    public View getView(int position, View convertView, ViewGroup parent) { 
     View v = null; 
     if(convertView==null){ 

      try{ 

      { 
        LayoutInflater li = getLayoutInflater(); 
        v = li.inflate(R.layout.icon, null); 
        TextView tv = (TextView)v.findViewById(R.id.text); 
        tv.setText("Profile Image "+(position+1)); 
        iv= (ImageView)v.findViewById(R.id.image); 

        imageUrl = "http://ondamove.it/English/images/users/"; 
        imageUrl=imageUrl+stringOnTextView[position]; 
        new BackgroundAsyncTask().execute(imageUrl); 


        } 
      }catch (Exception e) { 
      e.printStackTrace(); 
      System.out.println(e); 
     } 
     } 
     else 
     { 
      try{ 
      v = convertView;} 
      catch(Exception e){ 
       System.out.println(e); 
      } 
     } 
     return v; 
    } 
} 

je télécharger 9 images, mais le problème Je fais face est qu'il montre seulement la dernière image et le dialogue de progrès va dans la boucle infinie. Quelqu'un peut-il me dire comment résoudre ce problème thios.

Merci

Répondre

3

J'ai obtenu la solution en travaillant sur elle et ce qui suit devrait être la solution pour cela:

class DownloadFileAsync extends AsyncTask<String, String, String> 
{ 
    int count; 
    URL myFileUrl; 
    ImageView imageview; 
    Bitmap bp; 

    public DownloadFileAsync(ImageView iv, URL uu) 
    { 
     this.imageview = iv; 
     this.myFileUrl = uu; 
    } 

    @Override 
    protected void onPreExecute() 
    { 
     super.onPreExecute(); 
     showDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

    @Override 
    protected String doInBackground(String... aurl) 
    { 
     for (int i = 0; i < aurl.length; i++) 
      System.out.println("----------" + i + "------" + aurl[i]); 

     try 
     { 
      HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); 
      conn.setConnectTimeout(10000); 
      conn.setReadTimeout(10000); 
      conn.connect(); 
      InputStream is = conn.getInputStream(); 
      bmImg = BitmapFactory.decodeStream(is); 
      bp = BitmapFactory.decodeStream((InputStream) (myFileUrl).getContent()); 
      bp = Bitmap.createScaledBitmap(bp, 70, 70, true); 

     } 
     catch (Exception e) 
     { 
      System.out.println(e); 
      e.printstacktrace(); 
     } 

     return null; 
    } 

    protected void onProgressUpdate(String... progress) 
    { 
     dialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    @Override 
    protected void onPostExecute(String unused) 
    { 
     try 
     { 
      imageview.setImageBitmap(bp); 
      System.out.println("this is" + this); 
      // dialog.dismiss(); 
      dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 

     } 
     catch (Exception e) 
     { 
      System.out.println(e); 
     } 
    } 
} 
4

Je vous ai déjà suggéré d'utiliser AsyncTask précédemment pour vos problèmes si vous vous rappelez.

  1. OnPreExecute() - Afficher proress dialogue
  2. doInBackground() - méthode appelez votre DownloadFile() à l'intérieur du doInBackground()
  3. rejeter la boîte de dialogue de progression.

Passez par cet exemple et le comprendre et l'appliquer sur votre chemin: AsyncTask with Progress Dialog

+0

je l'ai fait, mais le problème que je suis face est que la boîte de dialogue de progression passe en boucle infinie. – ekjyot

+0

pourquoi infini? Vérifiez simplement if (dialog.isShowing()) {dialog.dismiss(); } à l'intérieur du onPostExecute() –

+0

Oui, il est à l'intérieur de la méthode onPostExecute() – ekjyot

0

Vous devez utiliser un AssyncTask pour être en mesure de communiquer facilement les progrès au fil de l'interface utilisateur.

Pour la boîte de dialogue, utilisez ProgressDialog:

private void downloadFile(URL fileUrl) { 
    if (myProgressDialog == null) { 
     new DownloadFilesTask().execute(fileUrl); 
     myProgressDialog = ProgressDialog.show(this, "Downloading file " + fileUrl.toString(), "Wait patiently, your download is in progress.", true /*You wont have a time estimate*/, false /*Download cannot be canceled*/); 
    } else { 
     Log.e(LOG_TAG, "A download is already in progress"); 
    } 
} 

private void hideDialog() { 
    if (myProgressDialog != null) { 
     myProgressDialog.cancel(); 
    } 
} 

Et pour la AssycTask, utilisez une classe interne dans votre activité:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> { 
    protected Long doInBackground(URL... urls) { 
     // TODO Download file here 
     return true; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     // TODO nothing to do here, you don't have download details 
    } 

    protected void onPostExecute(Boolean result) { 
     MyActivity.this.hideProgressDialog(); 
    } 
} 
0

ok, je vois 2 problèmes potentiels ici ..

  1. vous devez utiliser le type de structure de support pour votre adaptateur.

  2. Dans asyncTask, l'imageView doit être différent pour chaque élément de listView. Fondamentalement, vous devez passer imageView comme argument à asyncTask.

J'ai changé d'adaptateur, regardez-le.

static class ViewHolder { 

      TextView tv; 
      ImageView iv; 

    } 


    public View getView(int position, View convertView, ViewGroup parent) { 

     ViewHolder vh; 
     View v = null; 

     if(convertView==null){ 

        vh = new ViewHolder(); 
        LayoutInflater li = getLayoutInflater(); 
        v = li.inflate(R.layout.icon, null); 
        vh.tv = (TextView)v.findViewById(R.id.text); 
        vh.iv= (ImageView)v.findViewById(R.id.image); 
        v.setTag(vh); 
     } 
     else 
     { 
      vh = (ViewHolder) convertView.getTag(); 
      v = convertView; 
     } 

     vh.tv.setText("Profile Image "+(position+1)); 
     imageUrl = "http://ondamove.it/English/images/users/"; 
     imageUrl=imageUrl+stringOnTextView[position]; 
     new BackgroundAsyncTask(vh.iv).execute(imageUrl); 

     return v; 
    } 

Et aussi le asyncTask ici. J'ai fait un constructeur et ai passé imageView comme argument.

public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> { 

      int myProgress; 
      ImageView iv; 

      public BackgroundAsyncTask (ImageView imageView) { 
       iv = imageView; 
      } 

      @Override 
      protected void onPostExecute(Bitmap result) { 
       dialog.dismiss(); 
       iv.setVisibility(View.VISIBLE); 
       iv.setImageBitmap(result); 
       System.out.println("bbbbbbbbb"); 
       System.out.println("post execute"); 
      } 

      @Override 
      protected void onPreExecute() { 
       System.out.println("pre execute"); 
      dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait..."); 

      } 

      @Override 
      protected Bitmap doInBackground(String...paths) { 
       System.out.println(imageUrl+" imageurl"); 
       return DownloadFile(imageUrl); 

     } 
      @Override 
      protected void onProgressUpdate(Integer... values) { 
      // TODO Auto-generated method stub 
      progressBar.setProgress(values[0]); 
      } 

     } 

mais je ne peux toujours pas garantir la solution à boucle infinie, mais il est toujours bon de corriger d'autres problèmes :)

HTH.

+1

désolé de le dire, mais il n'a pas aidé .. – ekjyot

+0

oui, peut-être, mais certains points méritent d'être notés comme passant imageView comme argument. –

+0

Alors quoi d'autre devrait être passé – ekjyot

Questions connexes