android listview视频缩略图滚动问题

时间:2014-12-22 09:51:42

标签: android listview

我有一个包含三个视图的listview,一个用于视频,一个用于音频 在视频持有人我有listview,其中我显示视频的缩略图,如果它下载。它工作正常,但当我滚动然后该缩略图设置在另一个imageview上。

    mConvertView = convertView;
        chatMessage=chatMessages.get(position);

        final TextViewHolder mTextViewHolder;
        final ImageViewHolder mImageViewHolder;
        final AudioViewHolder mAudioViewHolder;

         Object object=chatMessages.get(position);
//      mHandler = new Handler();
        disply = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                .displayer(new RoundedBitmapDisplayer(20)).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).defaultDisplayImageOptions(disply).build();

        ImageLoader.getInstance().init(config);

        rd = new RecordBaseHandler(context);



    if(chatMessage.getAssetsId() != null)
      {

          if(chatMessage.getType().equalsIgnoreCase("audio"))

          {

              Log.d("Node", "Item position is "+chatMessages.get(position));

            mAudioViewHolder = getAudioViewHolder(mConvertView);
            mAudioViewHolder.mChatmessage=chatMessage;

            // TODO change below code
            if(chatMessage.getSenderId() != null)
                setAlignment(mAudioViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
            else
                setAlignment(mAudioViewHolder, false);


            mAudioViewHolder.play.setTag(position);

            mAudioViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));

            mycontent = chatMessage.getProperty("content-type");

            try {
                Cursor rs = rd.getData(chatMessage.getAssetsId());
                rs.moveToFirst();

                filepath = rs.getString(rs.getColumnIndex("file_path"));

                Log.d("Node", "FINALLY FILE PATH IS " + filepath);

                if (!rs.isClosed()) {
                    rs.close();
                }


                if (filepath != null) {

                    mAudioViewHolder.download.setVisibility(View.GONE);


                } else {
                    mAudioViewHolder.play.setVisibility(View.GONE);
                    mAudioViewHolder.download.setVisibility(View.VISIBLE);
                }
            } catch (Exception e) {
                // TODO: handle exception
                Log.d("Node", "EXECPTIOn " + e);
            }


              mAudioViewHolder.download.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Log.d("Node: ", "Reading all contacts..");
                    List<RecordModel> contacts = rd.getAllContacts();

                    for (RecordModel cn : contacts) {

                        String log = "Id: "+ cn.getId()+ " ,Name: "+ cn.getAttch_id()+ " ,Phone: " + cn.getFile_path();

                        Log.d("Node: ",log);

                    }



                    // File tempMp3 = File.createTempFile("record", ".mp3", f);

                    new Thread()
                    {
                        public void run() {
                            File tempMp3 = null;
                            try {
                                tempMp3 = File.createTempFile("record", ".mp3",Environment.getExternalStorageDirectory());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            //We are creating  folder first using mkdir 
                            File f =  new File(Environment.getExternalStorageDirectory()+ "/smbchat/");                         
                            if(!f.exists()){
                                f.mkdirs();
                            }

                            //then we want to store downloded file in that folder 
                            File output =  new File(f, "smb_" + System.currentTimeMillis() + "_audio.mp3");

                            Log.d("Node", "URL VALUE "+chatMessage.getUrl());
                            HttpRequest.get(chatMessage.getUrl()).receive(output);

                            audioFileName=String.valueOf(output);


                            Log.d("Node", "FILE SAVED SUCCESSFULLY"+tempMp3);
                            Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);
                            context.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    Toast.makeText(context, "file downloaded successfully", Toast.LENGTH_LONG).show();
                                    mAudioViewHolder.download.setVisibility(View.GONE);
                                }
                            });



                            rd.addContact(new RecordModel(chatMessage.getAssetsId(), audioFileName));

                        };

                    }.start();

                }
            });








            mAudioViewHolder.play.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {


                    mAudioViewHolder.play.setVisibility(View.GONE);
                    mAudioViewHolder.pause.setVisibility(View.VISIBLE);



                    Log.d("DATA", "currently playing " + position);
                    playingAudioPosition = position;


                    Object tag = mAudioViewHolder.play.getTag();

                    // Here we get the position that we have set for the checkbox using setTag.



                    String str=chatMessage.getAssetsId();

                    Cursor rs = rd.getData(str);
                    rs.moveToFirst();
                    try
                    {
                        filepath = rs.getString(rs.getColumnIndex("file_path"));
                    }
                    catch(Exception e)
                    {
                        Toast.makeText(mConvertView.getContext(), "File is not downloaded", Toast.LENGTH_LONG).show();
                    }

                    Log.d("Node", "file path for id "+  str  + "is "+ filepath);

                    if (!rs.isClosed()) {
                        rs.close();
                    }
                    if(filepath==null) //we check whether file is present or not 
                    {
                        Toast.makeText(mConvertView.getContext(), "File is Not downloaded", Toast.LENGTH_SHORT).show();

                        ((View)v.getParent()).findViewById(R.id.btndn).setVisibility(View.VISIBLE);
                        //                                      mAudioViewHolder.download.setVisibility(mConvertView.VISIBLE);
                    }
               else {
                                ((View) v.getParent()).findViewById(
                                        R.id.chat_audio_progress_bar)
                                        .setVisibility(View.VISIBLE);
                                // mAudioViewHolder.progressBar.setVisibility(mConvertView.VISIBLE);
                                mediaPlayer = new MediaPlayer();

                                String yofile = "file://" + filepath;
                                mediaPlayer
                                        .setAudioStreamType(AudioManager.STREAM_MUSIC);
                                try {

                                    mediaPlayer.setDataSource(yofile);

                                } catch (IllegalArgumentException
                                        | SecurityException
                                        | IllegalStateException | IOException e) {
                                    // TODO Auto-generated catch block
                                    Log.e("Node", "ERRORSS Part 1 is" + e);

                                    mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                                                @Override
                            public void onCompletion(MediaPlayer mp) 


                                                {
                                                    mAudioViewHolder.isPlaying = false;

                                                    /**
                                                     * since audio is stop
                                                     * playing, remove its
                                                     * position value
                                                     * */
                                                    playingAudioPosition = -1;
                                                }
                                            });
                                }
                                try {
                                    mediaPlayer.prepare();
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                    Log.e("Node", "ERRORSS is Part 2 " + e);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                mediaPlayer.start();
                                isMediaReleased = false;
                                mAudioViewHolder.progressBar.setMax(mediaPlayer.getDuration());
                                updateSeekBar();

                            }

                        }



                    });


            mAudioViewHolder.pause
                    .setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            mAudioViewHolder.play.setVisibility(View.VISIBLE);
                            mAudioViewHolder.pause.setVisibility(View.GONE);
                            mediaPlayer.stop();

                        }
                    });


        }

     if (chatMessage.getType().equalsIgnoreCase("image") || chatMessage.getType().equalsIgnoreCase("photo")) 
     {
         mImageViewHolder = getImageViewHolder(mConvertView);
         mImageViewHolder.mChatmessage=chatMessage;
         Log.d("Node", "this is Image position is "+chatMessages.get(position));

        // TODO change below code
        if(chatMessage.getSenderId() != null)
            setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
        else
            setAlignment(mImageViewHolder, false);

            mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));

            if (chatMessage.getProperty("localfile") != null) {

                imageUri1 = chatMessage.getProperty("localfile");
                String status = chatMessage.getProperty("isUpload");

                imageUri2 = "file://" + imageUri1;

                Log.d("Node", "This time from local");

                ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
                        mImageViewHolder.myimageview, disply);

                //
                // Log.d("Node", "IMAGEURI is : " + imageUri2
                // + "And  status is " + status);

            } else {

                Log.d("Node", "Here we are now else");
                ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
                        mImageViewHolder.myimageview, disply);
            }

            mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(context, "This is Image",
                            Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(context,
                            ShowImgActivity.class);

                    String urll = chatMessage.getUrl();

                    Bitmap bitmap = mImageViewHolder.myimageview.getDrawingCache();
                    intent.putExtra("URL", urll);

                    intent.putExtra("BitmapImage", bitmap);
                    context.startActivity(intent);
                }
            });
        }


        //if aatchmnet is video then do this 
        else if (chatMessage.getType().equalsIgnoreCase("video")) {



            mImageViewHolder = getImageViewHolder(mConvertView);
            mImageViewHolder.mChatmessage=chatMessage;

            // TODO change below code
            if(chatMessage.getSenderId() != null)
                setAlignment(mImageViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
            else
                setAlignment(mImageViewHolder, false);

            mImageViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));

            // Log.d("Node1", "This time from local videos");
            if (chatMessage.getVideo_thumb() != null) {

                Log.i("Node", "Yes this video has thumbnail");
                Bitmap bitmp = StringToBitMap(chatMessage.getProperty("video_thumb"));
                if (bitmp != null) {
                    mImageViewHolder.myimageview.setImageBitmap(bitmp);
                } else {
                    mImageViewHolder.myimageview
                    .setImageResource(R.drawable.vids);
                }

            } else {
                Log.i("Node", "Yes this dont have thumbanil");
                ImageLoader.getInstance().displayImage(chatMessage.getUrl(),
                        mImageViewHolder.myimageview, disply);
            }

            mImageViewHolder.myimageview.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    final ImageView imageThumbnail =  (ImageView)v;

                    final Handler handler=new Handler() {
                        public void handleMessage(Message msg) {

                            Log.e("", "handeler bmVideoThumbnail"+bmVideoThumbnail);

                            if (bmVideoThumbnail!=null) {
                                imageThumbnail.setImageBitmap(bmVideoThumbnail);
                            }

                        };
                    };

                    new Thread()
                    {
                        public void run() {
                            //We are creating  folder first using mkdir 
                            File f =  new File(Environment.getExternalStorageDirectory()+ "/smbchat/");                         
                            if(!f.exists()){
                                f.mkdirs();
                            }

                            //then we want to store downloded file in that folder 
                            File output =  new File(f, "VID_" + System.currentTimeMillis() + "_video.mp4");

                            Log.d("Node", "URL VALUE "+chatMessage.getUrl());
                            HttpRequest.get(chatMessage.getUrl()).receive(output);

                            audioFileName=String.valueOf(output);



                            Log.d("Node", "FILE SAVED SUCCESSFULLY AUDIOFILENAME " + audioFileName);

                            donloadedVideoUri= "file://" + audioFileName;

                            Log.e("Node", "donloadedVideoUri INSIDE THREAD------"+donloadedVideoUri);

                            bmVideoThumbnail=ThumbnailUtils.createVideoThumbnail(audioFileName, android.provider.MediaStore.Video.Thumbnails.MICRO_KIND);       

                            Log.e("Node",      "bmVideoThumbnail---------"+bmVideoThumbnail);
                            if(bmVideoThumbnail !=null)
                                handler.sendEmptyMessage(0);


                            };

                    }.start();























//                  String uriString = chatMessage.getUrl();
//                  Uri intentUri = Uri.parse(uriString);
//
//                  Intent intent2 = new Intent();
//                  intent2.setAction(Intent.ACTION_VIEW);
//                  intent2.setDataAndType(intentUri, "video/*");
//                  context.startActivity(intent2);
                }
            });





     }




 }






        else {

                mTextViewHolder = getTextViewHolder(mConvertView);
                mTextViewHolder.mChatmessage=chatMessage;

                 Log.d("Node", "this is text position is "+chatMessages.get(position));
            //TODO redo following logic
            if(chatMessage.getSenderId() != null)
                setAlignment(mTextViewHolder, chatMessage.getSenderId().intValue() != ((SMBChatApp) context.getApplication()).getQbUser().getId().intValue());
            else
                setAlignment(mTextViewHolder, false);

            mTextViewHolder.txtInfo.setText(getTimeText(chatMessage.getDate_sent()));

            mTextViewHolder.txtMessage.setText(chatMessage.getBody());

            mTextViewHolder.message = chatMessage;


        }

    return mConvertView;

2 个答案:

答案 0 :(得分:0)

您可以在多个列表项中看到相同的缩略图,因为Android会重复使用列表项的视图。 需要注意使缩略图不可见或使用“暗示没有图像的图标”。如果您没有列出该列表项位置的正确图像。必须在列表适配器的getView方法中进行此检查。

答案 1 :(得分:0)

使用一个ViewHolder并定义三个字段并根据状态显示隐藏视图。 在列表中维护状态而不是适配器。 因为在列表视图上重新创建列表项滚动。