在我们的Android应用程序中加载mp4视频

时间:2017-04-26 04:31:05

标签: android android-studio android-cursoradapter android-cursor android-videoview

我正在编写代码,因为它正在收集.mp4格式的视频,它工作正常。但是,问题是当我从网格中选择视频时,它正在选择另一个视频。例如,我选择了第15个视频,但它正在访问12个视频位置,请检查是什么问题。

公共类MainUploadFragment扩展了Fragment {

private Cursor videocursor;
private int video_column_index;
GridView gv_upload_videos;

int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 200;
VideoAdapter mAdapter;
int count;
Context Ucontext;
String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
        MediaStore.Video.Thumbnails.VIDEO_ID};


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.upload_videos, container, false);

    gv_upload_videos = (GridView) view.findViewById(R.id.gv_upload_videos);

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(getActivity(),
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                200);
    } else {

        new LoadAsync().execute();
    }


    return view;
}

private class LoadAsync extends AsyncTask<Void, Void, Void> {
    ProgressDialog progressBar;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar = new ProgressDialog(getActivity());
        progressBar.setMessage("Loading");
        progressBar.setProgress(100);
        progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressBar.setIndeterminate(true);
        progressBar.show();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        String[] proj = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.SIZE};

        String selectedVideoPath = null;
        Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

        videocursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                proj, null, null, null);

        getActivity().getContentResolver().query(MediaStore.Video.Media.INTERNAL_CONTENT_URI,
                proj, null, null, null);

        count = videocursor.getCount();
        init_phone_video_grid();


        mAdapter = new VideoAdapter(getContext());


        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        progressBar.hide();
        gv_upload_videos.setAdapter(mAdapter);




        gv_upload_videos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                System.gc();


                video_column_index = videocursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);


                String path = videocursor.getString(MediaStore.Video.Thumbnails.MINI_KIND);

                String images = path;
                Bitmap thumb = ThumbnailUtils.createVideoThumbnail(images,
                        MediaStore.Images.Thumbnails.MINI_KIND);
                Log.e("Images", "" + thumb);
                videocursor.moveToPosition(position);
                String filename = videocursor.getString(video_column_index);

            }
        });


        gv_upload_videos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                System.gc();
                video_column_index = videocursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);


                videocursor.moveToPosition(position);
                String filename = videocursor.getString(video_column_index);
                Intent intent = new Intent(getContext(),
                        UploadActivity.class);
                intent.putExtra("videofilename", filename);
                startActivity(intent);
            }
        });

    }
}

private boolean isAllPermissionGranted() {

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        return false;
    }
    return true;
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    Log.e("requestcode", "" + requestCode);
    if (requestCode == Activity.RESULT_OK)
        switch (requestCode) {
            case 200:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    String[] proj = {MediaStore.Video.Media._ID,
                            MediaStore.Video.Media.DATA,
                            MediaStore.Video.Media.DISPLAY_NAME,
                            MediaStore.Video.Media.SIZE};

                    videocursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                            proj, null, null, null);
                    count = videocursor.getCount();

                    init_phone_video_grid();


                    mAdapter = new VideoAdapter(getContext());

                    gv_upload_videos.setAdapter(mAdapter);



                    gv_upload_videos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                            System.gc();
                            video_column_index = videocursor
                                    .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);

                            String path = videocursor.getString(MediaStore.Video.Thumbnails.MINI_KIND);

                            String images = path;
                            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(images,
                                    MediaStore.Images.Thumbnails.MINI_KIND);
                            Log.e("Images", "" + thumb);


                            videocursor.moveToPosition(position);
                            String filename = videocursor.getString(video_column_index);
                            Intent intent = new Intent(getContext(),
                                    UploadActivity.class);
                            intent.putExtra("videofilename", filename);
                            startActivity(intent);
                        }
                    });

                    gv_upload_videos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                            System.gc();
                            video_column_index = videocursor
                                    .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                            String path = videocursor.getString(MediaStore.Video.Thumbnails.MINI_KIND);

                            String images = path;
                            Bitmap thumb = ThumbnailUtils.createVideoThumbnail(images,
                                    MediaStore.Images.Thumbnails.MINI_KIND);
                            Log.e("Images", "" + thumb);
                            videocursor.moveToPosition(position);
                            String filename = videocursor.getString(video_column_index);
                        }
                    });

                } else {
                    Toast.makeText(getActivity(), "Please grant camera permission to use the QR Scanner", Toast.LENGTH_SHORT).show();
                }
                return;
        }
}


@SuppressWarnings("deprecation")
private void init_phone_video_grid() {


}

private class VideoDetail {
    String id;
    String size;
    Bitmap bitmap;

    public VideoDetail(String id, String size, Bitmap bitmap) {
        this.id = id;
        this.size = size;
        this.bitmap = bitmap;
    }
}

public class VideoAdapter extends BaseAdapter {
    private Context vContext;
    List<VideoDetail> videoDetails;

    public VideoAdapter(Context c) {


        vContext = c;
        videoDetails = new ArrayList<>();


        if (videocursor.moveToFirst()) {
            do {
                String id = videocursor.getString(videocursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME));
                String size = videocursor.getString(videocursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
                if (id != null) {
                    String filetype = id.substring(id.lastIndexOf("."));


                    String[] proj = {MediaStore.Video.Media._ID,
                            MediaStore.Video.Media.DISPLAY_NAME,
                            MediaStore.Video.Media.DATA};
                    @SuppressWarnings("deprecation")
                    Cursor cursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj,
                            MediaStore.Video.Media.DISPLAY_NAME + "= ?",
                            new String[]{id}, null);
                    cursor.moveToFirst();
                    long ids = cursor.getLong(cursor
                            .getColumnIndex(MediaStore.Video.Media._ID));
                    ContentResolver contentResolver = vContext.getContentResolver();
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 1;
                    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
                            contentResolver, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
                            options);

                    cursor.close();


                    if (filetype.equals(".mp4")) {
                        videoDetails.add(new VideoDetail(id, size, curThumb));
                    }
                    Log.v("DISPLAY_NAME", "" + id);
                    Log.v("id", "" + size);

                }
            } while (videocursor.moveToNext());
        }


    }

    public int getCount() {
        return videoDetails.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        convertView = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(vContext).inflate(
                    R.layout.upload_grid, parent, false);
            holder = new ViewHolder();
            convertView.setTag(holder);
        } else {

            holder = (ViewHolder) convertView.getTag();
        }
        holder.thumbImage = (ImageView) convertView.findViewById(R.id.iv_uploaded_grid_images);
   holder.thumbImage.setImageBitmap(videoDetails.get(position).bitmap);

        return convertView;
    }
}

static class ViewHolder {

    TextView txtTitle;
    TextView txtSize;
    ImageView thumbImage;
}


private class LoadThumbnail extends AsyncTask<Void, Void, Bitmap> {

    String id;
    Context vContext;
    ImageView imageView;

    public LoadThumbnail(
            String id,
            Context vContext,
            ImageView imageView) {

        this.id = id;
        this.vContext = vContext;
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(Void... voids) {
        String[] proj = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DATA};
        @SuppressWarnings("deprecation")
        Cursor cursor = getActivity().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj,
                MediaStore.Video.Media.DISPLAY_NAME + "= ?",
                new String[]{id}, null);
        cursor.moveToFirst();
        long ids = cursor.getLong(cursor
                .getColumnIndex(MediaStore.Video.Media._ID));
        ContentResolver crThumb = vContext.getContentResolver();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
                crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
                options);

        //    curThumb = null;
        cursor.close();
        return curThumb;
    }

    @Override
    protected void onPostExecute(Bitmap curThumb) {
        super.onPostExecute(curThumb);
        imageView.setImageBitmap(curThumb);
    }
}

class MyGridView extends GridView {

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

1 个答案:

答案 0 :(得分:0)

您需要更改gv_upload_videos.setOnItemClickListener,如下所示

              gv_upload_videos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                        System.gc();
                        videocursor.moveToPosition(position);
                        video_column_index = videocursor
                                .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                        String path = videocursor.getString(MediaStore.Video.Thumbnails.MINI_KIND);

                        String images = path;
                        Bitmap thumb = ThumbnailUtils.createVideoThumbnail(images,
                                MediaStore.Images.Thumbnails.MINI_KIND);
                        Log.e("Images", "" + thumb);
                        String filename = videocursor.getString(video_column_index);
                    }
                });