【问题标题】:Update the Progress Bar in the ListView when downloading下载时更新ListView中的进度条
【发布时间】:2015-11-01 02:25:43
【问题描述】:

我有一个显示数据库记录列表的活动。 在这个活动中有一个自定义的 ListView。 在自定义 ListView 中,有一个 Button 和一个 TextView 和一个 ProgressBar 。 我调用 AsyncTask 的按钮侦听器位于 CustomAdapter 类中。

DownloadTask downloadTask = new DownloadTask(getContext());
                downloadTask.execute(url[position].toString());

AsynkTask 工作得很好。 但我想在下载过程中更新进度条。 我已经在互联网上搜索了三天,但没有成功。 对不起我的英语

public class listanimals extends ActionBarActivity {
private MyDatabase MyDataBase;
String[]  listurl;
ProgressBar progressBar;
TextView url2;
CustomList adapter;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class DownloadTask extends AsyncTask<String, Integer, String> {
    private Context context;
    int myProgress;
    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected String doInBackground(String... sUrl) {

        InputStream input = null;
        final GlobalClass caches = (GlobalClass) context.getApplicationContext();
        OutputStream output = null;
        HttpURLConnection connection = null;

        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }


            input = connection.getInputStream();
            output = new FileOutputStream("/sdcard/"+caches.getName_cach()+".mp3");

            byte data[] = new byte[4096];
            long total = 0;
            int count;

            while ((count = input.read(data)) != -1) {
                total += count;

                myProgress = (int)(total*100/connection.getContentLength());

                output.write(data, 0, count);

            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... values) {
     //MY PROBLEM MAY HERE
        progressBar.setProgress(myProgress);
    }
    @Override
    protected void onPostExecute(String result) {
        final GlobalClass caches = (GlobalClass) context.getApplicationContext();

        if (result != null)
            Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();

        else{
            Toast.makeText(context,"File downloaded"+ "" + caches.getName_cach(), Toast.LENGTH_SHORT).show();

        }
    }

}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////AsynkTask end
///////////////////////////////////////////////////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listanimals);
    MyDataBase = new MyDatabase(this);
    final GlobalClass caches = (GlobalClass) getApplicationContext();
    final ListView listView=(ListView)findViewById(R.id.listView);


    SQLiteDatabase mydb = MyDataBase.getReadableDatabase();

    Cursor cursor = mydb.rawQuery("select * from animals", null);

    ArrayList<String> myList = new ArrayList<String>();
   final ArrayList<String> myListname = new ArrayList<String>();
    ArrayList<String> myListurl = new ArrayList<String>();

    try {
        while(cursor.moveToNext()) {

            myList.add(cursor.getString(cursor.getColumnIndex("_id")));
            myListname.add(cursor.getString(cursor.getColumnIndex("name")).trim());
            myListurl.add(cursor.getString(cursor.getColumnIndex("url")));

            String[] listname = new String[myListname.size()];
            listname = myListname.toArray(listname);

            listurl = new String[myListurl.size()];
            listurl = myListurl.toArray(listurl);

            String[] listid = new String[myList.size()];
            listid = myList.toArray(listid);

             adapter = new
                    CustomList(listanimals.this, listname,listurl);
            listView.setAdapter(adapter);

   }}  finally{
        mydb.close();
    }}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class CustomList extends ArrayAdapter<String> {

    private MyDatabase MyDataBase;

    private final Activity context;
    private final String[] web;
    private final String[] url;
    public CustomList(Activity context,
                      String[] web,String[] url) {
        super(context, R.layout.list_file, web);
        this.context = context;
        this.web = web;
        this.url = url;
    }



    @Override
    public View getView(final int position, View view, final ViewGroup parent) {
        final GlobalClass caches = (GlobalClass) context.getApplicationContext();

        MyDataBase = new MyDatabase(getContext());

        LayoutInflater inflater = context.getLayoutInflater();
        View rowView= inflater.inflate(R.layout.list_file, null, true);
        Typeface kamran= Typeface.createFromAsset(context.getAssets(), "IranNastaliq.ttf");
        progressBar=(ProgressBar)rowView.findViewById(R.id.progressBar);
        TextView txtTitle3 = (TextView) rowView.findViewById(R.id.textView);
        txtTitle3.setTypeface(kamran);
        url2=(TextView)rowView.findViewById(R.id.textView2);
        url2.setText(url[position]);
        txtTitle3.setText(web[position]);
        Button download=(Button)rowView.findViewById(R.id.button);



        download.setTag(position);// Any data associated with the button has to be added with          setTag()

        download.setOnClickListener(new View.OnClickListener() {/////////call AsynkTask
            @Override
            public void onClick(View arg0) {
            caches.setName_cach(web[position]);
                DownloadTask downloadTask = new DownloadTask(getContext());
                downloadTask.execute(url[position].toString());


            }
        });

        return rowView;

     }


 }

}

【问题讨论】:

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


    【解决方案1】:

    您需要从 doInBackground 方法中调用 publishProgress 来更新 ProgressBar:publishProgress docs

    这将调用 onProgressUpdate(Integer... values);

    您不需要 myProgress 实例变量;

    【讨论】:

    • 如果解决了您的问题,请标记为正确答案。
    • 谢谢老哥。我试过了。但是当进度条处于活动状态时,此方法有效。当进度条处于自定义列表布局时,这不起作用。解决办法是什么?
    • @AmirGheybi 您的 ProgressBar 是 listAnimals 类的实例变量。它应该在该类的 onCreate 方法中实例化。
    • 我疯了。四天来做,但我没有。您可以对我的代码进行必要的更改吗?谢谢
    • @AmirGheybi 我不会为你编写代码,但文档中有一个很好的例子:developer.android.com/reference/android/widget/ProgressBar.html
    【解决方案2】:

    查看此链接https://www.youtube.com/watch?v=5HDr9FdGIVg&list=PLonJJ3BVjZW6hmkEaYIvLLm5IEGM0kpwU&index=17

    你需要调用 - publishProgress((int) total*100/connection.getContentLength());

    在while循环中 更新您的进度条。希望对您有所帮助。

    【讨论】:

    • 谢谢兄弟。视频很不错。我尝试过这个 。但是当进度条处于活动状态时,此方法有效。当进度条处于自定义列表布局时,这不起作用。解决办法是什么?
    【解决方案3】:

    您在列表的每个项目中都有一个进度条,而您在活动中保留一个实例。这意味着您的进度视图将指向系统要求您绘制的最后一个列表项中的那个。这可能不是您按下按钮的列表项中的那个。我建议您拆分课程(将它们从活动中删除),您会更好地看到您的问题。但这只是您的第一个问题 - 因为您启动了异步任务,同时您可以将该项目滚动到屏幕外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 2012-03-16
      相关资源
      最近更新 更多