1

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

    In the View Inflation process of ListView. (This is also not working)

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

    package com.example.testhopelist;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;

public class TestHopeList extends Activity {
    ListView lv;
    // ArrayList<String> list = new ArrayList<String>();
    ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
    MyListAdapter adtf;

    public static String prf_date_view = "";

    String str_start;
    Button all_detail;
    Button accepted_all;
    Button not_shown;
    public static SQLiteDatabase db;
    String name;
    File download;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_hope_list);


        list = DBAdapter.getUrl_Detail();
        Log.v("log_tag","list  :: "+list.size());
        lv = (ListView) findViewById(R.id.main_list_meet);
        adtf = new MyListAdapter(this);
        lv.setAdapter(adtf);

        SqliteAdpter dba = SqliteAdpter.getAdapterInstance(getApplicationContext());
        dba.createdatabase();
        db = dba.openDataBase();
    }



    public class MyListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MyListAdapter(Context context) {
            mInflater = LayoutInflater.from(context);

        }

        public int getCount() {
            return list.size();
        }

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

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

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

                convertView = mInflater
                        .inflate(R.layout.custome_list_view, null);


                Button cl = (Button) convertView.findViewById(R.id.cancle_sedual);
                final ProgressBar pr=(ProgressBar)convertView.findViewById(R.id.listprogressbar);

                //pr.setProgress(getItem(position));
                cl.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        str_start=list.get(position).url_video;
                        Log.v("log_tag","str_start  "+ str_start);

                        //
                        //new DownloadFileFromURL().execute(str_start);
                        new DownloadFileFromURL().execute(pr,str_start);
                    }
                });


            return convertView;
        }
    }


    class DownloadFileFromURL extends AsyncTask<Object, String, String> {


        int count = 0;
        ProgressDialog dialog;
        ProgressBar progressBar;
        int myProgress;
        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
             ProgressBar progressBar;

        }


        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(Object... params) {

            int count;
            progressBar= (ProgressBar) params[0];
            try {
                //URL url = new URL(f_url[0]);
                URL url = new URL((String)params[1]);
                Log.v("log_tag","name  ::: "+url);
                name = ((String) params[1]).substring(((String) params[1]).lastIndexOf("/") + 1);
                Log.v("log_tag","name Substring ::: "+name);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                  download = new File(Environment
                            .getExternalStorageDirectory()
                            + "/download/");
                          if (!download.exists()) {
                              download.mkdir();
                          }
                String strDownloaDuRL = download+"/" + name;
                Log.v("log_tag"," down url   " + strDownloaDuRL);
                FileOutputStream output = new FileOutputStream(strDownloaDuRL);


                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... values) {
            progressBar.setProgress(0);
            super.onProgressUpdate(values);
            Log.v("log_tag","progress :: "+values);
            // setting progress percentage
            // pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {

            Log.v("log", "login  ::: 4::: "
                    + download);
            String videoPath =download +"/"+ name;
            String chpName = name;
            Log.v("log_tag","chpName  ::::"+ chpName +  "  videoPath " +videoPath);
            db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\"" + chpName + "\",\"" + videoPath + "\" )");

        }



    }


}
4

3 回答 3

3

我已经在 GridView 中实现了这种类型的功能。在该应用程序中,我使用 VO(值对象)管理进度条的状态。

我使用以下来执行 AsnchTask。

新的uploadTask(holder.progressBar, vo, this).execute();

在 GridView 的 getView() 方法中,

switch(data.getStateOfProgress())
     {
         case Constants.START_DOWNLOADING:
            holder.transBlackImage.setVisibility(View.VISIBLE);
             System.out.println("Downloading Starts........");
             holder.progressBar.setVisibility(View.VISIBLE);
             new DownloadToDeviceTask(holder.progressBar, data, this).execute();
             break;
         case Constants.STOP_DOWNLOADING:
            holder.transBlackImage.setVisibility(View.GONE);
             System.out.println("Downloading Stops..........");
             holder.progressBar.setVisibility(View.INVISIBLE);
             break;
         case Constants.DOWNLOADING:
             holder.transBlackImage.setVisibility(View.VISIBLE);
             holder.progressBar.setVisibility(View.VISIBLE);
             System.out.println("Downloading................");
             break;
         case Constants.START_UPLOADING:
            holder.transBlackImage.setVisibility(View.VISIBLE);
            holder.progressBar.setVisibility(View.VISIBLE);
             new UploadToStorageTask(holder.progressBar, data, this, isStoredOnBoth).execute();
             break;
         case Constants.STOP_UPLOADING:
            holder.transBlackImage.setVisibility(View.GONE);
             holder.progressBar.setVisibility(View.INVISIBLE);
             break;
         case Constants.UPLOADING:
            holder.transBlackImage.setVisibility(View.VISIBLE);
             holder.progressBar.setVisibility(View.VISIBLE);
             break;
     }

VO如下,

public class BookInfoVO {
private ArrayList<BookInfoVO> bookInfoVO;
private String bookTitle;
private String bookPublicInfo;
private float bookSize;
private int bookImage;
private int bookState;
private int typeOfData;
private String folderName;
private boolean checked;
private int stateOfProgress;

public void setBookTitle(String bookTitle) {
    this.bookTitle = bookTitle;
}
public String getBookTitle() {
    return bookTitle;
}
public void setBookPublicInfo(String bookPublicInfo) {
    this.bookPublicInfo = bookPublicInfo;
}
public String getBookPublicInfo() {
    return bookPublicInfo;
}
public void setBookSize(float bookSize) {
    this.bookSize = bookSize;
}
public float getBookSize() {
    return bookSize;
}
public void setBookImage(int bookImage) {
    this.bookImage = bookImage;
}
public int getBookImage() {
    return bookImage;
}
public void setBookState(int bookState) {
    this.bookState = bookState;
}
public int getBookState() {
    return bookState;
}
public void setTypeOfData(int typeOfData) {
    this.typeOfData = typeOfData;
}
public int getTypeOfData() {
    return typeOfData;
}
public void setBookInfoVO(ArrayList<BookInfoVO> bookInfoVO) {
    this.bookInfoVO = bookInfoVO;
}
public ArrayList<BookInfoVO> getBookInfoVO() {
    return bookInfoVO;
}
public void setFolderName(String folderName) {
    this.folderName = folderName;
}
public String getFolderName() {
    return folderName;
}
public void setChecked(boolean checked) {
    this.checked = checked;
}
public boolean isChecked() {
    return checked;
}
public void setStateOfProgress(int stateOfProgress) {
    this.stateOfProgress = stateOfProgress;
}
public int getStateOfProgress() {
    return stateOfProgress;
}

}

尝试这个。

于 2013-02-19T08:42:28.570 回答
3

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

让 AsyncTask 接受对象参数数组,将您ProgressBar的每一行传递给您asyncTask并完成。

现在onProgressUpdate更新您发送到 asyncTask 的引用 progressBar 的值

简单示例

class DownloadFileFromURL extends AsyncTask<Object, String, String> {

        ProgressBar progressBar;
        @Override
        protected String doInBackground(Object... params) {
            .....
            progressBar= (ProgressBar) params[0];

            try {
                 URL url = new URL((String)params[1]);
                }
           catch (MalformedURLException e) {}
           return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            ....
            progressBar.setProgress(0);
            super.onProgressUpdate(values);
        }

    }

现在您可以按如下方式调用 AsyncTask:

  new DownloadFileFromURL().execute(pr,str_start);
于 2013-02-19T07:04:14.410 回答
2

尝试使用此while循环更改可能会起作用

    while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
               // publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                progressBar.setProgress((int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }

享受..>!!

于 2013-02-19T09:41:24.317 回答