Android 方法获取ingnored RecyclerView

Android 方法获取ingnored RecyclerView,android,android-recyclerview,Android,Android Recyclerview,我正在使用RecyclerView制作一个用于显示sd卡文件的应用程序,我还添加了一个删除文件的按钮。但问题是RecyclerView被删除了,但原始文件没有。它之所以这么说是因为文件.delete()被忽略了。任何帮助都将不胜感激 具体代码: holder.Delbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v)

我正在使用RecyclerView制作一个用于显示sd卡文件的应用程序,我还添加了一个删除文件的按钮。但问题是RecyclerView被删除了,但原始文件没有。它之所以这么说是因为文件.delete()被忽略了。任何帮助都将不胜感激

具体代码:

holder.Delbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(String.valueOf(trackuri));

                    file.delete();


                Toast.makeText(mContext,"Deleted the file : " , Toast.LENGTH_SHORT).show();

                mContext.getContentResolver().delete(trackuri, null,null);
                mMusic.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,mMusic.size());


            }
        });
适配器类的整个代码:

public class MusicAdapter  extends RecyclerView.Adapter<MusicAdapter.MusicViewHolder>  {

    Context mContext;
    List<Music> mMusic;
    BitmapDrawable mPlaceholder;
    LruCache<Long, Bitmap> mBitmapCache;
    public Uri track;

    private int selectedPosition;


    public MusicAdapter(Context context, List<Music> music) {
        mMusic = new ArrayList<>();
        if(music != null) {
            mMusic.addAll(music);
        }
        mContext = context;
        mPlaceholder = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.ic_music_note_black_48dp);
        // Get the maximum size of byte we are allowed to allocate on the VM head and convert it to bytes.
        int maxSize = (int) (Runtime.getRuntime().maxMemory() / 1024);
        // Divide the maximum size by eight to get a adequate size the LRU cache should reach before it starts to evict bitmaps.
        int cacheSize = maxSize / 8;
        mBitmapCache = new LruCache<Long, Bitmap>(cacheSize) {

            @Override
            protected int sizeOf(Long key, Bitmap value) {
                // returns the size of bitmaps in kilobytes.
                return value.getByteCount() / 1024;
            }
        };
    }
    /**
     * Adds a {@link Music} item to the Adapter.
     * @param
     */
    /**
     * Adds a {@link List} of {@link Music} to the adapters.
     * This method replaces the current music items inside of the adapter with the specified music items.
     * @param
     */
    public void clearItem() {
        mMusic.clear();
    }
    public void addItems(List<Music> music) {
        // Clear the old items. I only do this so that I don't have to do duplicating checks on the music items.
        mMusic.clear();
        // Add the new music list.
        mMusic.addAll(music);
        notifyItemRangeInserted(0, music.size());
    }
    /**
     * Clears the {@link Music} items inside of this adapter.
     */
    @Override
    public MusicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.list_item, parent, false);
        MusicViewHolder musicViewHolder = new MusicViewHolder(v);
        return musicViewHolder;
    }

    @Override
    public void onBindViewHolder(MusicViewHolder holder, final int position) {
        final Music music = mMusic.get(position);
        holder.itemView.setLongClickable(true);
        // Check the Bitmap cache for the album art first..
        final Bitmap bitmap = mBitmapCache.get(music.getAlbumId());
        // If the bitmap is not null, then use the cached images.
        if(bitmap != null){
            holder.icon.setImageBitmap(bitmap);
        }
        else {
            // No album art could be found in the cache try reloading it.
            // In a real work example you should check that this value is not some junk value indicating that their is no album artwork.
            loadAlbumArt(holder.icon, music.getAlbumId());
        }

        holder.artist.setText(music.getArtist());
        holder.title.setText(music.getTitle());
        final Uri trackuri= ContentUris.withAppendedId(
                android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, music.getId());
        final Uri turi= ContentUris.withAppendedId(
                android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, music.getId());


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

                                                Intent intent = new Intent(mContext, Playrecord.class);

                                                intent.setData(trackuri);
                                                mContext.startActivity(intent);


                                            }
                                            });
        holder.button9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(String.valueOf(trackuri));

                    file.delete();


                Toast.makeText(mContext,"Deleted the file : " , Toast.LENGTH_SHORT).show();

                mContext.getContentResolver().delete(trackuri, null,null);
                mMusic.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,mMusic.size());


            }
        });




    }




    /**
     * Helper method for asynchronously loading album art.
     * @param icon
     * @param albumId
     */
    public void loadAlbumArt(ImageView icon, long albumId) {
        // Check the current album art task if any and cancel it, if it is loading album art that doesn't match the specified album id.
        if(cancelLoadTask(icon, albumId)) {
             // There was either no task running or it was loading a different image so create a new one to load the proper image.
            LoadAlbumArt loadAlbumArt = new LoadAlbumArt(icon, mContext);
            // Store the task inside of the async drawable.
            AsyncDrawable drawable = new AsyncDrawable(mContext.getResources(), mPlaceholder.getBitmap(),loadAlbumArt);
            icon.setImageDrawable(drawable);
            loadAlbumArt.execute(albumId);
        }
    }

    /**
     * Helper method cancelling {@link LoadAlbumArt}.
     *
     * @param icon
     * @param albumId
     * @return
     */
    public boolean cancelLoadTask(ImageView icon, long albumId) {
        LoadAlbumArt loadAlbumArt = (LoadAlbumArt) getLoadTask(icon);
        // If the task is null return true because we want to try and load the album art.
        if(loadAlbumArt == null) {
            return true;
        }
        if(loadAlbumArt != null) {
            // If the album id differs cancel this task because it cannot be recycled for this imageview.
            if(loadAlbumArt.albumId != albumId) {
                loadAlbumArt.cancel(true);
                return true;
            }
        }
        return false;
    }

    /**
     * Helper method for extracting an {@link LoadAlbumArt}.
     * @param icon
     * @return
     */
    public AsyncTask getLoadTask(ImageView icon) {
        LoadAlbumArt task = null;
        Drawable drawable = icon.getDrawable();
        if(drawable instanceof AsyncDrawable) {
            task = ((AsyncDrawable) drawable).getLoadArtworkTask();
        }
        return task;
    }

    public void remove(long itemId) {
    }




    private class LoadAlbumArt extends AsyncTask<Long, Void, Bitmap> {

        // URI that points to the AlbumArt database.
        private final Uri albumArtURI = Uri.parse("content://media/external/audio/albumart");
        public WeakReference<ImageView> mIcon;
        // Holds a publicly accessible albumId to be checked against.
        public long albumId;
        public Context mContext;
        int width, height;

        public LoadAlbumArt(ImageView icon, Context context) {
            // Store a weak reference to the imageView.
            mIcon = new WeakReference<ImageView>(icon);
            // Store the width and height of the imageview.
            // This is necessary for properly scalling the bitmap.
            width = icon.getWidth();
            height = icon.getHeight();
            mContext = context;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if(isCancelled() || bitmap == null){
                return;
            }
            // Check to make sure that the imageview has not been garbage collected as well as the
            // LoadArtworkTask is the same as this one.
            if(mIcon != null && mIcon.get() != null) {
                ImageView icon = mIcon.get();
                Drawable drawable = icon.getDrawable();
                if(drawable instanceof AsyncDrawable) {
                    LoadAlbumArt task = ((AsyncDrawable) drawable).getLoadArtworkTask();
                    // Make sure that this is the same task as the one current stored inside of the ImageView's drawable.
                    if(task != null && task == this) {
                        icon.setImageBitmap(bitmap);
                    }
                }
            }
            mBitmapCache.put(albumId, bitmap);
            super.onPostExecute(bitmap);
        }

        @Override
        protected Bitmap doInBackground(Long... params) {
            // AsyncTask are not guaranteed to start immediately and could be cancelled somewhere in between calling doInBackground.
            if(isCancelled()){
                return null;
            }
            albumId = params[0];
            // Append the albumId to the end of the albumArtURI to create a new Uri that should point directly to the album art if it exist.
            Uri albumArt = ContentUris.withAppendedId(albumArtURI, albumId);
            Bitmap bmp = null;

            return bmp;
        }
    }
    /**
     * Custom drawable that holds a LoadArtworkTask
     */

    private static class AsyncDrawable extends BitmapDrawable {
        WeakReference<LoadAlbumArt> loadArtworkTaskWeakReference;

        public AsyncDrawable(Resources resources, Bitmap bitmap, LoadAlbumArt task) {
            super(resources, bitmap);
            // Store the LoadArtwork task inside of a weak reference so it can still be garbage collected.
            loadArtworkTaskWeakReference = new WeakReference<LoadAlbumArt>(task);
        }

        public LoadAlbumArt getLoadArtworkTask() {
            return loadArtworkTaskWeakReference.get();
        }
    }

    @Override
    public int getItemCount() {
        return mMusic.size();
    }

    /**
     * Custom ViewHolder that represents the List Item.
     */
    public static class MusicViewHolder extends RecyclerView.ViewHolder {

        ImageView icon;
        TextView title;
        TextView artist;
        Button button8;
        Button button9;

        public MusicViewHolder(View itemView) {
            super(itemView);
            icon = (ImageView) itemView.findViewById(R.id.icon);
            title = (TextView) itemView.findViewById(R.id.title);
            artist = (TextView)itemView.findViewById(R.id.subtitle);
            button8 = (Button) itemView.findViewById(R.id.button8);
            Delbutton = (Button) itemView.findViewById(R.id.button9);
        }


    }
}
公共类MusicAdapter扩展了RecyclerView.Adapter{ 语境; 音乐列表; 位图可绘制模板持有者; LruCache-mBitmapCache; 公共轨道; 私人int-selectedPosition; 公共音乐播放器(上下文、列表音乐){ mMusic=newarraylist(); 如果(音乐!=null){ mMusic.addAll(音乐); } mContext=上下文; mPlaceholder=(BitmapDrawable)mContext.getResources().getDrawable(R.drawable.ic\u music\u note\u black\u 48dp); //获取允许在VM头上分配的最大字节大小,并将其转换为字节。 int maxSize=(int)(Runtime.getRuntime().maxMemory()/1024); //将最大大小除以8,以获得LRU缓存在开始逐出位图之前应达到的足够大小。 int cacheSize=maxSize/8; mBitmapCache=新的LruCache(缓存大小){ @凌驾 受保护的int sizeOf(长键、位图值){ //返回位图的大小(以KB为单位)。 返回值。getByteCount()/1024; } }; } /** *将{@link Music}项添加到适配器。 *@param */ /** *将{@link Music}的{@link List}添加到适配器。 *此方法使用指定的音乐项替换适配器内的当前音乐项。 *@param */ 公共无效clearItem(){ mMusic.clear(); } 公共无效附加项(列表音乐){ //清除旧项目。我这样做只是为了不必重复检查音乐项目。 mMusic.clear(); //添加新的音乐列表。 mMusic.addAll(音乐); notifyItemRangeInserted(0,music.size()); } /** *清除此适配器中的{@link Music}项。 */ @凌驾 public MusicView文件夹onCreateViewHolder(视图组父级,int-viewType){ LayoutFlater充气机=LayoutFlater.from(mContext); 视图v=充气机。充气(R.layout.list_项,父项,false); MusicView文件夹MusicView文件夹=新的MusicView文件夹(v); 返回音乐文件夹; } @凌驾 BindViewHolder上的公共无效(MusicViewHolder,最终int位置){ 最终音乐=mMusic.get(位置); holder.itemView.setLongClickable(true); //首先检查相册艺术的位图缓存。。 最终位图位图=mbitMacache.get(music.getAlbumId()); //如果位图不为空,则使用缓存的图像。 if(位图!=null){ holder.icon.setImageBitmap(位图); } 否则{ //在缓存中找不到相册艺术,请尝试重新加载它。 //在一个实际的工作示例中,您应该检查该值是否为垃圾值,以指示其没有相册艺术品。 loadAlbumArt(holder.icon,music.getAlbumId()); } holder.artist.setText(music.getArtist()); holder.title.setText(music.getTitle()); 最终Uri trackuri=ContentUris.withAppendedId( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,music.getId()); final Uri turi=ContentUris.withAppendedId( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,music.getId()); holder.button8.setOnClickListener(新视图.OnClickListener(){ @凌驾 公共void onClick(视图v){ 意图=新意图(mContext,Playrecord.class); intent.setData(trackuri); mContext.startActivity(意图); } }); holder.button9.setOnClickListener(新视图.OnClickListener(){ @凌驾 公共void onClick(视图v){ File File=新文件(String.valueOf(trackuri)); delete(); Toast.makeText(mContext,“删除文件:”,Toast.LENGTH_SHORT.show(); mContext.getContentResolver().delete(trackuri,null,null); mMusic.remove(位置); 已移除(位置)的项目; notifyItemRangeChanged(位置,mMusic.size()); } }); } /** *用于异步加载相册艺术的助手方法。 *@param图标 *@param-albumId */ public void loadAlbumArt(图像视图图标,长albumId){ //如果正在加载与指定的相册id不匹配的相册艺术任务,请检查当前的相册艺术任务(如果有),并将其取消。 if(取消加载任务(图标,相册ID)){ //要么没有运行任务,要么正在加载其他映像,因此请创建一个新映像以加载正确的映像。 LoadAlbumArt LoadAlbumArt=新的LoadAlbumArt(图标,mContext); //将任务存储在异步drawable中。 AsyncDrawable drawable=新的AsyncDrawable(mContext.getResources(),mPlaceholder.getBitmap(),loadAlbumArt); icon.setImageDrawable(可绘制); loadAlbumArt.execute(albumId); } } /** *助手方法正在取消{@link LoadAlbumArt}。 * *@param图标 *@param-albumId *@返回 */ 公共布尔cancelLoadTask(图像视图图标,长albumId){ LoadAlbumArt LoadAlbumArt=(LoadAlbumArt)ge
if(file.exists)
{
 file.delete();
}
 holder.Delbutton.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {


                mContext.getContentResolver().delete(trackuri, null,null);
                mMusic.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position,mMusic.size());
                File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath()+"/Voico/"+music.getTitle()+".mp3");
                if(file.exists()) {
                    file.delete();

                    Toast.makeText(mContext,"Deleted the file : " , Toast.LENGTH_SHORT).show();

                }
            }
        });