【问题标题】:Updating Progress bar in listview while downloading a file下载文件时更新列表视图中的进度条
【发布时间】:2011-10-27 09:33:45
【问题描述】:

我们如何更新 ListView 中的进度条。当每个进度条与文件的下载相关联并且通过 AsyncTask 完成时。

  • 那么在哪里更新 ProgressBar
    1. 正在更新中(我试过这不起作用)
    2. 在 ListView 的 View Inflation 过程中。 (这也行不通)

基本上,每当我在浏览器中获得类似 .mp3 的文件时,我都会调用此异步任务,因此可以有 n 个异步任务实例。然后如何使用特定的 Aysnctask 任务更新特定的进度条。

            public class CopyOfDownloadsListActivity extends ListActivity {
            /** Called when the activity is first created. */

            //  static ArrayList<String> pthreads = new ArrayList<String>();
            static ImageView bt;
            static ProgressBar pb;
            static ListView allList;
            static TextView tv;
            String fileName;
            String mp3URL;
            URL url2;
            int myProgress;
            static int filecount  = 0;
            MyCustomAdapter adapter;

            private class DownloadFile extends AsyncTask<String, Integer, Void>{
                int count = 0;
                ProgressDialog dialog;
                int myProgess = 0;
                ProgressBar progressBar;

                @Override
                protected Void doInBackground(String... u) {

                    try {                   
                        URL ul = new URL(u[0]);
                        Log.i("UI",ul.toString());
                   //   int len = CopyOfMusicDownloader.mp3urls.size();
                   //   URL url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                        HttpURLConnection c = (HttpURLConnection) ul.openConnection();
                        c.setRequestMethod("GET");
                        c.setDoOutput(true);
                        c.connect();

                        int lengthOfFile = c.getContentLength();

                        String PATH = Environment.getExternalStorageDirectory()
                                + "/download/";
                        Log.v("", "PATH: " + PATH);
                        File file = new File(PATH);
                        file.mkdirs();

                        fileName = "Track";
                        filecount++;

                        fileName =  fileName + Integer.toString(filecount) + ".mp3";


                        File outputFile = new File(file, fileName);
                        FileOutputStream fos = new FileOutputStream(outputFile);
                        InputStream is = c.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len1 = 0;      
                        while ((len1 = is.read(buffer)) != -1) {
                            myProgress = (int)(len1*100/lengthOfFile);
                            //myProgress = (int)(len1);

                            Log.i("My Progress", Integer.toString(myProgress));
                            publishProgress(myProgress);
                            //  publishProgress((int)(len1*100/lengthOfFile));
                            fos.write(buffer, 0, len1);
                        }
                        fos.close();
                        is.close();

                        }catch (IOException e) {
                               e.printStackTrace();
                        }
                    return null;
                }

                protected void onPostExecute() {

                }

                @Override
                protected void onPreExecute() {
                      setListAdapter(new MyCustomAdapter(CopyOfDownloadsListActivity.this, R.layout.row, CopyOfMusicDownloader.mp3urls));

                }



                @Override
                protected void onProgressUpdate(Integer... values) {
                     pb.setProgress(count);// HERE IS THE PROBLEM

                     count++;
                     Log.i("Values", Integer.toString(values[0]));
                }
             }  

            @Override
            public void onCreate(Bundle savedInstanceState) {
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                super.onCreate(savedInstanceState);

                int len = CopyOfMusicDownloader.mp3urls.size();
                try {
                    url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                    new DownloadFile().execute(url2.toString());
                    Log.i("url",url2.toString());
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                 MenuInflater myMenuInflater = getMenuInflater();
                 myMenuInflater.inflate(R.menu.menu, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                 switch(item.getItemId()){
                 case(R.id.browsermenu):
                 Intent i = new Intent(CopyOfDownloadsListActivity.this, MusicDownloader.class);  
                 startActivity(i);
                 break;
                 case(R.id.downloaderrmenu):      
                 break; 
                 case(R.id.playermenu):
                 Intent j = new Intent(CopyOfDownloadsListActivity.this, Players.class);  
                 startActivity(j);
                break;
          }
             return true;
            }


            public class MyCustomAdapter extends ArrayAdapter<String> {     
                public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<String> pthreads) {
                super(context, textViewResourceId, pthreads);
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        LayoutInflater inflater = getLayoutInflater();
                        View row = inflater.inflate(R.layout.row, parent, false);
                        bt =(ImageView)row.findViewById(R.id.cancel_btn);
                        tv =(TextView)row.findViewById(R.id.filetext);
                        pb = (ProgressBar)row.findViewById(R.id.progressbar_Horizontal);
                        return row;
                    }
                }


        }

【问题讨论】:

    标签: android listview download progress-bar android-asynctask


    【解决方案1】:

    列表视图的子视图由适配器构建。这个适配器有一些底层数据,这些数据在 getView() 方法中被“转换”为视图。这意味着您必须在异步任务的更新进度方法中更改该数据并调用 adapter.notifyDataSetChanged()。您的 getView 方法应该只是将数据“转换”为列表视图子视图。

    异步任务:

    protected void onProgressUpdate(final int... values) {
      data[i].progress = values[0];
      adapter.notifyDataSetChanged();
    }
    

    适配器:

    public View getView(final int position, final View convertView, final ViewGroup parent) {
      ...
      progress.setProgress(getItem(position).progress);
      ...
    }
    

    【讨论】:

    • 嗨 Romnan,我这两天一直在寻找这个答案,这对我有帮助,但是 data[i] 属于什么?
    • 数据是适配器后面的一些结构(数组或列表)。通常,您在适配器的 getItem 实现中返回 data[i]: public SomeObject getItem(position) { return data[position]; }
    猜你喜欢
    • 2014-01-12
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多