在listview android中滚动期间Textview值会发生变化

时间:2015-10-16 17:36:50

标签: android listview handler timertask

我正在开发多个文件下载应用。其中,如果开关打开则开始下载,如果开关关闭,则取消下载。我正在使用带有处理程序的timertask更新项目值。下面是我的适配器代码。一切正常,但是当我滚动列表视图时,项目值(百分比计数)与其他文件下载进度的其他值冲突。

代码:

public class DownloadAdapter extends ArrayAdapter<AudioSubModel> {

    private static final String PDF_MIME_TYPE = "application/pdf";
    private LayoutInflater lf;
    Context mContext;
    private List<ListContent> lstHolders;
    private Handler mHandler = new Handler();
    private Runnable updateRemainingTimeRunnable = new Runnable() {
        @Override
        public void run() {
            synchronized (lstHolders) {
                for (ListContent holder : lstHolders) {
                    holder.updateTimeRemaining();

                }
            }
        }
    };

    AudioSubModel getAlarm(int position){
        return ((AudioSubModel) getItem(position));
    }

    public DownloadAdapter(Context context, int resource, List<AudioSubModel> objects) {
        super(context, resource, objects);
        lf = LayoutInflater.from(context);
        lstHolders = new ArrayList<ListContent>();
        mContext = context;
        Log.e("ADAPTER", "CONSTR");
        startUpdateTimer();
    }

    private void startUpdateTimer() {
        Timer tmr = new Timer();
        tmr.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(updateRemainingTimeRunnable);
            }
        }, 1000, 1000);
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ListContent holder = null;
        if (view == null) {
            view = lf.inflate(R.layout.row_audio_desc_layout, null);
            holder = new ListContent();

            holder.ivImg = (CircleImageView)view.findViewById(R.id.row_audio_desc_ivImg);
            holder.tvTitle = (TextView) view
                    .findViewById(R.id.row_audio_desc_tvTitle);

            holder.tvDesc = (TextView) view
                    .findViewById(R.id.row_audio_desc_tvDesc);

            holder.llDownload = (LinearLayout)view.findViewById(R.id.row_audio_desc_llDownload);
            holder.PBDownload = (RoundCornerProgressBar)view.findViewById(R.id.row_audio_desc_PBDownload);
            holder.tvReadPdf = (TextView)view.findViewById(R.id.row_audio_desc_tvReadPdf);
            holder.tvMakeOffline = (TextView)view.findViewById(R.id.row_audio_desc_tvMakeOffline);
            holder.swtchDownload = (Switch)view.findViewById(R.id.row_audio_desc_swtchDownloadOn);
            holder.tvDownload = (TextView)view.findViewById(R.id.row_audio_desc_tvDownload);
            holder.tvDownloadPercent = (TextView)view.findViewById(R.id.row_audio_desc_tvDownloadPercent);
            holder.ivCancel = (ImageView)view.findViewById(R.id.row_audio_desc_ivCancel);
            holder.ivPlay = (ImageView)view.findViewById(R.id.row_audio_desc_ivPlay);

            holder.tvTitle.setTypeface(MyApplication.app_bold);
            holder.tvDesc.setTypeface(MyApplication.app_light);
            holder.tvReadPdf.setTypeface(MyApplication.app_bold);
            holder.tvMakeOffline.setTypeface(MyApplication.app_bold);
            holder.swtchDownload.setTypeface(MyApplication.app_bold);
            holder.tvDownload.setTypeface(MyApplication.app_bold);
            holder.tvDownloadPercent.setTypeface(MyApplication.app_bold);


            view.setTag(holder);
            synchronized (lstHolders) {
                lstHolders.add(holder);
            }
        } else {
            holder = (ListContent) view.getTag();
        }


        holder.setData(getAlarm(position));

//        convertView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ((MainActivity)mContext).ItemClickFetch(getItem(position).getId());
//            }
//        });
        return view;
    }

    class ListContent {

        LinearLayout llDownload;
        RoundCornerProgressBar PBDownload;
        CircleImageView ivImg;
        ImageView ivCancel, ivPlay;
        TextView tvTitle, tvDesc, tvReadPdf, tvMakeOffline, tvDownload, tvDownloadPercent;
        Switch swtchDownload;
        private AudioSubModel aItem;
        DownloadFileFromURL dwnldFileUrl;

        public void setData(AudioSubModel item) {
            aItem = item;

            dwnldFileUrl = new DownloadFileFromURL();


            if(item.isPlaying()){
                ivPlay.setImageResource(R.drawable.pausebtn);
            }else{
                ivPlay.setImageResource(R.drawable.playbtn);
            }


            if(aItem.isDownloading()){
                swtchDownload.setOnCheckedChangeListener(null);
                swtchDownload.setChecked(true);
                tvDownloadPercent.setText(aItem.getPercent() + "");
            }else{
                swtchDownload.setOnCheckedChangeListener(null);
                swtchDownload.setChecked(false);
                tvDownloadPercent.setText("0");
            }

//          holder.tvDownloadPercent.setText(data.get(position).getPercent()+" %");
            tvDownload.setText(aItem.getDwnLbl());
            tvTitle.setText(aItem.getTitle());
            tvDesc.setText(aItem.getDesc());

            Bitmap bmp = BitmapFactory.decodeFile(aItem.getImage());
            ivImg.setImageBitmap(bmp);
//            Log.e("MAIN", "IS DONE: " + aItem.isOn());


            tvReadPdf.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    if(isPDFSupported(mContext)){
                        Uri path = Uri.fromFile(new File(aItem.getPdf()));
                          Intent objIntent = new Intent(Intent.ACTION_VIEW);
                          objIntent.setDataAndType(path, "application/pdf");
                          objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                          mContext.startActivity(objIntent);
                    }else{
                        if(GeneralClass.getConnectivityStatusString(mContext)){
                            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://docs.google.com/gview?embedded=true&url="+aItem.getPdfurl()));
                            mContext.startActivity(browserIntent);
                        }else{
                            GeneralClass.showToast("Check internet connection to view pdf file", mContext);
                        }

                    }
                }
            });

            ivPlay.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub

                    if(aItem.isPlaying()){
                        aItem.setPlaying(false);
                        ((MainActivity)mContext).stopAudioFile();

                    }else{
                        aItem.setPlaying(true);
                        ((MainActivity)mContext).playAudioFile(aItem);

                    }



                }
            });

            swtchDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                    // TODO Auto-generated method stub
//                  updateView(position, arg1);
                    Log.e("Audio ADAPTER", "file: " + arg1);

                    if(arg1){
                        aItem.setDownloading(true);
                        aItem.setDwnLbl("Downloading");
                        dwnldFileUrl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aItem.getAudiourl());
                    }else if(!arg1){
                        aItem.setDownloading(false);
                        aItem.setDwnLbl("Download");
                        dwnldFileUrl.cancel(true);

                    }


                }
            });

            ivCancel.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    aItem.setDownloading(false);
                    aItem.setDwnLbl("Download");
                    dwnldFileUrl.cancel(true);

//                  updateView(position, false);
//                  new DownloadFileFromURL(holder, position).execute(data.get(position).getAudiourl());
                }
            });



            updateTimeRemaining();
        }

        public void updateTimeRemaining() {

//            Log.e("MAIN", "GET TIME: " + aItem.getTimeStamp());

            if(aItem.isDownloading()){
                llDownload.setVisibility(View.VISIBLE);
                tvDownloadPercent.setVisibility(View.VISIBLE);
                tvDownloadPercent.setText(aItem.getPercent()+"");
//              PBDownload.setProgress(aItem.getPercent());
                tvDownload.setText(aItem.getDwnLbl());
            }else{
                llDownload.setVisibility(View.INVISIBLE);
                tvDownloadPercent.setVisibility(View.INVISIBLE);
                tvDownloadPercent.setText("0");
//              PBDownload.setProgress(0);
                tvDownload.setText(aItem.getDwnLbl());
            }
//                if(aItem.isOn()){
//                    tvTitle.setText(aItem.getPercent()+"");
//                }else{
//                    tvTitle.setText("0");
//                }

        }


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

             private volatile boolean running = true;
            String finalFilePath="";

            /**
             * Before starting background thread
             * Show Progress Bar Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            /**
             * Downloading file in background thread
             * */
            @Override
            protected String doInBackground(String... f_url) {
                int count;

                try {
//                  URL url = new URL(f_url[0]);
                    URL url = new URL("http://www.robtowns.com/music/blind_willie.mp3");


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

                    // Output stream to write file
                    String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
                    String outputFile = extStorageDirectory+"/"+GeneralClass.FILE_PATH;
                    finalFilePath = outputFile+"/audio"+aItem.getId()+".mp3";
                    OutputStream output = new FileOutputStream(finalFilePath);

                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = input.read(data)) != -1 && running) {

                        if(isCancelled()){
                            Log.e("ADAPTER", "Async break");
                            break;
                        }
                        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;
            }

            @Override
            protected void onCancelled() {
                running = false;
                Log.e("ADAPTER", "Async cancelled");
            }
            /**
             * Updating progress bar
             * */
            @Override
            protected void onProgressUpdate(String... progress) {
                // setting progress percentage
                aItem.setPercent(Integer.parseInt(progress[0]));

           }

            /**
             * After completing background task
             * Dismiss the progress dialog
             * **/
            @Override
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after the file was downloaded
//              dismissDialog(progress_bar_type);
                Log.e("ADAPTER", "DONE ID: " + aItem.getId());
                ((MainActivity)mContext).updateAudioFileDownload(aItem.getId(), finalFilePath);
                ivCancel.setVisibility(View.INVISIBLE);
            }

        }
    }

    public static boolean isPDFSupported(Context context) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}

帮我解决这个重大问题。

0 个答案:

没有答案