Android:显示进度对话框

发布于 2024-12-11 16:23:54 字数 3441 浏览 0 评论 0 原文

我正在制作一个更新的 Android 应用程序。为此,我需要一个简单的函数,可以下载文件并在 ProgressDialog 中显示当前进度。我知道如何下载文件,但我不知道如何显示当前进度。我使用以下方法下载图像。

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;

}

以下是我的异步任务类:

    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]);
}

}

我正在调用以下适配器类中的方法:

    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;
    }
}

我需要下载 9 个图像,但我面临的问题是它只显示最后一个图像,并且进度对话框进入无限循环。

谁能告诉我如何解决 thios 问题。

谢谢

I am making an android application that gets updated. For this I need a simple function that can download a file and show the current progress in a ProgressDialog. I know how to do the download the file, but I'm not sure how to display the current progress.I am using the following method for downloading images.

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;

}

And following is my async task class :

    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]);
}

}

and i am calling the method in the following adapter class :

    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;
    }
}

I need to download 9 images but the problem i am facing is that it only shows the last image and progress dialog goes into infinite loop.

Can anyone tell me over how to resolve thios issue.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏末的微笑 2024-12-18 16:23:54

如果您还记得的话,我已经建议您之前使用 AsyncTask 来解决您的问题。

  1. onPreExecute() - 显示进度对话框
  2. doInBackground() - 在 doInBackground() 中调用 DownloadFile() 方法,
  3. 关闭进度对话框。

浏览这个示例并理解它并以您的方式实现它: 带有进度对话框的AsyncTask

I have already suggested you to use AsyncTask previously for your problems if you remember.

  1. onPreExecute() - show proress dialog
  2. doInBackground() - call your DownloadFile() method inside the doInBackground()
  3. dismiss the progress dialog.

Go through this example and understand it and implement it in your way: AsyncTask with Progress Dialog

久隐师 2024-12-18 16:23:54

我通过研究得到了解决方案,以下应该是解决方案:

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);
        }
    }
}

I got the solution by working on it and the following should be the solution for this:

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);
        }
    }
}
无力看清 2024-12-18 16:23:54

您必须使用 AssyncTask 才能轻松地将进度传达给用户界面线程。

对于对话框,使用 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();
   }
}

对于 AssycTask,使用内部您的活动中的课程:

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();
   }
 }

You have to use an AssyncTask to be able to easily communicate progress to the UI thread.

For the dialog, use 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();
   }
}

And for the AssycTask, use an inner class in your Activity:

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();
   }
 }
荆棘i 2024-12-18 16:23:54

好的,我在这里看到两个潜在的问题..

  1. 您必须为您的适配器使用支架类型的结构。

  2. 在 asyncTask 中,imageView 对于 listView 中的每个项目应该是不同的。基本上,您必须将 imageView 作为参数传递给 asyncTask。

我换了你的适配器,你看一下。

    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;
    }

还有这里的 asyncTask。我创建了一个构造函数并传递 imageView 作为参数。

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]);
          }

         }

但我仍然不能保证无限循环的解决方案,但解决其他一些问题总是好的:)

HTH。

ok, i see 2 potential problems here ..

  1. you have to use holder kind of structure for your adapter.

  2. in asyncTask, the imageView, should be different for each item in the listView. basically, you have to pass imageView as an argument to asyncTask.

I changed your adapter, have a look at it.

    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;
    }

And also the asyncTask here. I made a constructor and passed imageView as 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]);
          }

         }

but i still can't guarantee the solution to infinite loop, but it is always good to fix some other problems :)

HTH.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文