【问题标题】:Item deleting from listview affecting asynctask从影响异步任务的列表视图中删除项目
【发布时间】:2016-04-11 11:46:56
【问题描述】:

我正在制作一个多视频下载器。我已经创建了一个列表视图,并且对于列表视图中的每个项目,都会调用一个异步任务,它会在后台下载文件。一切都很完美。但是,如果我想从列表视图中删除一个项目,例如从位置 2,位置 3 的项目(当前都在运行)出现在位置 2 上,之前附加到位置 2 的异步任务继续运行,它显示异步任务的进度之前附加到位置 2。如何将位置 3 的 asynctask 移动到位置 2。

这是我调用 asynctask 类的适配器类:

public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
    public static TextView progpercent;
    // Simple class to make it so that we don't have to call findViewById frequently
    //  private static final String    TAG = FileDownloadTask.class.getSimpleName();
    public static Integer result;
    LayoutInflater inflater5;
    ImageView delete;
    Activity activity1;
    int mvalue;
    ContextWrapper cw1;
    int flag=0;
    int status=0;
    GlobalDownload downloadList;
    ArrayList downloadState;
    FileDownloadTask task;



    private static class ViewHolder {
        TextView textView;
        ProgressBar progressBar;
        ImageView delete;
        DownloadInfo info;
        TextView size;
        TextView prog;
        public TextView progpercent;
    }


    private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();

    public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
                                    List<DownloadInfo> objects, ContextWrapper cw, Activity DownloadScreen) {
        super(context, textViewResourceId, objects);
        cw1=cw;
        activity1=DownloadScreen;
    }



    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
      final DownloadInfo info = getItem(position);
            ViewHolder holder = null;
        if(null == row) {
            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             row = inflater.inflate(R.layout.file_download_row, parent, false);

            holder = new ViewHolder();
            holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
            holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
            holder.size=(TextView) row.findViewById(R.id.downloadFileSize);
            holder.progpercent=(TextView) row.findViewById(R.id.downloadFileProgress);
            holder.delete=(ImageView) row.findViewById(R.id.deletebutton);
            //  holder.button = (Button)row.findViewById(R.id.downloadButton);
          //  holder.info = info;

            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();


        }

        holder.textView.setText(info.getFilename());





        holder.progpercent.setText(info.getDownloadState().toString());
       if(info.getStatus()== null)
       {
           Log.e("DATABASE1", "null ");
           status=3;
           info.setLastState(2);

       }
        else if(info.getStatus()== DownloadInfo.State.DONE)
       {
           if(info.getLastState()==1)
           {
               Log.e("DATABASE", "LS " + 1);
               info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
               status=1;

           }
           else if(info.getLastState()==0)
           {
               Log.e("DATABASE", "LS " + 2);
               info.setDownloadState(DownloadInfo.DownloadState.FAILED);

               status=1;

           }

        else
           {
               status=2;
           }
       }




        Log.e("DATABASE", "DOWNLOAD STATE " + info.getDownloadState().toString());

        if(info.getDownloadState()== DownloadInfo.DownloadState.NOT_STARTED)
        {
            if(status==3) {

                    holder.progressBar.setProgress(info.getProgress());
                    holder.progressBar.setMax(100);
                    holder.progpercent.setText("DOWNLOADING");

            }
        }


        holder.size.setText(info.getFileSize());

        info.setProgressBar(holder.progressBar);



      if(info.getDownloadState()==DownloadInfo.DownloadState.NOT_STARTED){                              info.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
            if (MainScreen.settingsvalue==0) {

                    Log.e("DATABASE", " " + 0);
                    mvalue = 0;
                     task = new FileDownloadTask(info, cw1, activity1, mvalue);
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

            }






         if(info.getDownloadState()== DownloadInfo.DownloadState.COMPLETE) {

                 Log.e("DATABASE", "UPDATE COMPLETE " + info.getDownloadState());
             info.setStatus(DownloadInfo.State.DONE);


                 info.setLastState(1);
                 holder.progressBar.setProgress(R.drawable.download_bar);
             holder.progpercent.setText(info.getDownloadState().toString());
             cancelstatus=0;

         }

        if(info.getDownloadState()== DownloadInfo.DownloadState.FAILED) {

            info.setStatus(DownloadInfo.State.DONE);
               MainScreen.newDB.execSQL("update " + DatabaseHelper.TABLE_NAME + " set " + DatabaseHelper.COL_6 + " = '" + info.getStatus() + "', " + DatabaseHelper.COL_7 + " =0 where " + DatabaseHelper.COL_1 + " = " + info.getFileid());
                       Log.e("DATABASE", "UPDATED ");
               info.setLastState(0);
            holder.progpercent.setText(info.getDownloadState().toString());
            cancelstatus=0;



        }



        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Integer index = (Integer) v.getTag();
                Log.e("POSITION", "TAG " + index);
                Log.e("POSITION", "POSITION " + position);
               downloadList = ((GlobalDownload) activity1.getApplicationContext());
               downloadState = (ArrayList) downloadList.getDownloadInfo();
               CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
                CustomDialogClass2.customfilename2= info.getFilename() + "." + info.getFileType();
                Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
                CustomDialogClass2 cdd = new CustomDialogClass2(MainScreen.activity1);
                cdd.show();
                CustomDialogClass2.mPosition=position;
                CustomDialogClass2.id=info.getFileid();
              //  downloadState.remove(position);

            Log.e("STATUS", "Status before stopping  " + info.getDownloadState());
             if((info.getDownloadState()== DownloadInfo.DownloadState.DOWNLOADING)) {
                 info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
                 cancelstatus=1;
                task.cancel(true);

             }


       }
        });



        return row;
    }

}

这里是 Asynctask 类

public class FileDownloadTask extends AsyncTask<String, Integer, Integer> {
    private static final String    TAG = FileDownloadTask.class.getSimpleName();
    final DownloadInfo  mInfo;
    TextView display;
    public int progress;
    public  String encodedurl;
    PopupWindow popupWindow;
    Activity activity;
   // ListView listview1;
 //  Context context;
    LayoutInflater layoutInflater;
    static int i=0;
    int Mvalue;
    ContextWrapper cw;
    File file;
    String nameoffile;
    PowerManager mgr;
    PowerManager.WakeLock wakeLock;
    public static int cancelstatus =0;
    int a=0;

    //  DownloadInfoArrayAdapter mAdapter;

    public FileDownloadTask(DownloadInfo info, ContextWrapper cw1, Activity activity1, int mvalue) {
        mInfo = info;
        cw=cw1;
        activity=activity1;
        this.Mvalue=mvalue;

     //   listView1 = (ListView) listview.findViewById(R.id.downloadListView);
     //   mAdapter = new DownloadInfoArrayAdapter(, R.id.downloadListView,mInfo);
    }

    // @Override
    protected void onProgressUpdate(Integer... values) {
        mInfo.setProgress(values[0]);
        mInfo.setFilePercent(values[0]);
        //  Log.e("FILE PERCENT", String.valueOf(mInfo.getFilePercent()));
        //  mAdapter.notifyDataSetChanged();
        // mAdapter.setNotifyOnChange(true);

        // display = (TextView) row.findViewById(R.id.downloadFileProgress);
        ProgressBar bar = mInfo.getProgressBar();
        // Integer percent=mInfo.getFilePercent();

        if (bar != null) {
            bar.setProgress(mInfo.getProgress());
            // percent(mInfo.getFilePercent());
            // display.setText(mInfo.getProgress());

            //  bar.invalidate();
        }

//        DownloadScreen.adapter.notifyDataSetChanged();
//        DownloadScreen.listView.setAdapter(DownloadScreen.adapter);


    }

    @Override
    protected void onCancelled() {
        super.onCancelled();


         mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);

        File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");


        File file = new File(rootdirectory, CustomDialogClass2.customfilename2);
         Log.e("FILE", " name" + file.toString());


        file.delete();
        DownloadScreen.adapter.notifyDataSetChanged();


    }


    @Override

    protected Integer doInBackground(String... params) {
        int count;



            try {
                String state = Environment.getExternalStorageState();
                    String root = Environment.getExternalStorageDirectory().toString();



                    URL url = new URL(mInfo.getFileUrl().toString());
                    Log.e("URL", "" + url);
                    HttpURLConnection conection = (HttpURLConnection) url.openConnection();
                    conection.connect();
                    Log.e("connection", " " + 0);

                    int lenghtOfFile = conection.getContentLength();


                    Log.e("length", "" + lenghtOfFile);

                String nameoffile = mInfo.getFilename() + "." + mInfo.getFileType();

                    if (Environment.MEDIA_MOUNTED.equals(state)) {
                        File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
                        if (!rootdirectory.exists()) {
                            rootdirectory.mkdirs();
                        }


                        File file = new File(rootdirectory, nameoffile);
                        file.createNewFile();
                        Log.e("name of file", "" + nameoffile);



                        InputStream input = new BufferedInputStream(url.openStream(), 8192);

                        OutputStream output = new FileOutputStream(file);
                        byte data[] = new byte[1024];
                        mInfo.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
                        long total = 0;
                        while ((count = input.read(data)) != -1) {

                            if(!isCancelled()) {
                                total += count;
                                progress = (int) ((total * 100) / lenghtOfFile);
                                publishProgress(progress);
                                //   Log.e("PROGRESS", "" + mInfo.getFileType() + progress);
                                mInfo.setFilePercent(progress);




                                output.write(data, 0, count);
                                i = 1;
                            }
                        }

                           mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
                           mInfo.setStatus(DownloadInfo.State.COMPLETE);

                           output.flush();


                           output.close();
                           input.close();
                           Log.e("Download Complete", "" + 0);
                           Log.e("DEVICE SDCARD", " " + Mvalue);

                    }



        return progress;
    }



    protected void onPostExecute(Integer progress) {




           mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);

           DownloadScreen.adapter.notifyDataSetChanged();
           DownloadScreen.listView.setAdapter(DownloadScreen.adapter);

           Uri contentUri = Uri.fromFile(file);
           Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
           activity.sendBroadcast(mediaScanIntent);

           CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
           CustomDialogClass.customfilename=mInfo.getFilename() + "." + mInfo.getFileType();
           Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
           CustomDialogClass cdd = new CustomDialogClass(MainScreen.activity1);
           cdd.show();



        }


    @Override
    protected void onPreExecute() {



    }



}

【问题讨论】:

    标签: android listview android-asynctask


    【解决方案1】:

    您应该覆盖适配器的 remove 方法,以便正确取消与您的项目关联的 asyncTask。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      相关资源
      最近更新 更多