VideoView inside Fragment

11,258

You need to make sure you have set:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

in your AndroidManifest.xml

Also, i think you're not starting the video at all

In your VideoView initialisation you can access the MediaPlayer within the VideoView using:

VideoView video = (VideoView) rootView.findViewById(R.id.videoView);
video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    videoView.requestFocus();
                    videoView.start();
                }
  });
video.setVideoURI(Uri.parse(pathForTheFile));

EDIT: As it is a local video that your'e trying to play, you don't need to wait the MediaPlayer to be prepared, so this should work:

VideoView video = (VideoView) rootView.findViewById(R.id.videoView);               
video.setVideoURI(Uri.parse(pathForTheFile));
video.start();
video.requestFocus();

So, you wont need these lines:

MediaController mc=  new MediaController(getActivity());
                mc.setAnchorView(video);
                video.setMediaController(mc);
                video.requestFocus();

Let me know if it worked

Share:
11,258
niryo
Author by

niryo

Updated on July 25, 2022

Comments

  • niryo
    niryo almost 2 years

    Edit: i thought i had a problem with my implementation of the fragment that caused the videoView not to work, but it turned out that the implementation was correct and i just had a problem with the layout xml of the videoView. ill keep the code as an example of a correct implementation of a videoView inside a fragment using viewpager:)

    this is my Fragment:

    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.media.MediaPlayer;
    import android.media.ThumbnailUtils;
    import android.net.Uri;
    import android.os.Bundle;
    
    import android.provider.MediaStore;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.MediaController;
    import android.widget.TextView;
    import android.widget.VideoView;
    
    import uk.co.senab.photoview.PhotoView;
    import uk.co.senab.photoview.PhotoViewAttacher;
    
    
    public class ScreenSlidePageFragment extends Fragment {
    
        private Context context = null; //TODO MAKE SETTER
        private String fileName;
        private final String FILE_NAME = "FILE_name";
    
        /**
         * Factory method for this fragment class. Constructs a new fragment.
         */
        public static ScreenSlidePageFragment create(String fileName, Context context) {
            ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
            fragment.setFileName(fileName);
            fragment.setContext(context);
            return fragment;
        }
    
        public ScreenSlidePageFragment() {
    
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    //        fileName = getArguments().getString(FILE_NAME);
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout containing a title and body text.
            ViewGroup rootView = (ViewGroup) inflater
                    .inflate(R.layout.fragment_screen_slide_page, container, false);
    
            // Set the title view to show the page number.
            String name = this.fileName;
            if (name != null) {
                if (name.endsWith(".jpg")) {
                    Bitmap myBitmap = BitmapFactory.decodeFile(name);
                    ImageView view = (ImageView) rootView.findViewById(R.id.imageView);
                    view.setImageBitmap(myBitmap);
                    PhotoViewAttacher mAttacher = new PhotoViewAttacher(view);
                }
                if (name.endsWith(".mp4")) {
                    final VideoView video = (VideoView) rootView.findViewById(R.id.videoView);
    
                    video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            video.requestFocus();
                            video.start();
                        }
                    });
                    video.setVideoURI(Uri.parse(name));
    //                Bitmap bitmap = ThumbnailUtils.createVideoThumbnail("/storage/sdcard0/Android/data/huji.ac.il.test/files/savedFiles/150401015447.mp4", MediaStore.Video.Thumbnails.MICRO_KIND);
    //                ImageView view = (ImageView) rootView.findViewById(R.id.imageView);
    //                view.setImageBitmap(bitmap);
                }
    
            }
            return rootView;
        }
    
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
    
        public void setContext(Context context) {
            this.context = context;
        }
    }
    

    this is the layout "fragment_screen_slide_page.xml":

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        android:layout_gravity="center"
    
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="0dp"
    
            />
    
        <VideoView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/videoView"
            android:layout_gravity="center_horizontal" />
    
    
    </LinearLayout>
    

    here is the activity that usess the fragment:

    public class ScreenSlideActivity extends FragmentActivity {
    
    
        private ViewPager mPager;
        private PagerAdapter mPagerAdapter;
        private ArrayList<String> fileNameList;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View decorView = getWindow().getDecorView();
            // Hide the status bar.
            int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
    
            setContentView(R.layout.activity_screen_slide);
    
            fileNameList=getImagesFromStorage();
            // Instantiate a ViewPager and a PagerAdapter.
            mPager = (ViewPager) findViewById(R.id.pager);
            mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), fileNameList,this);
            mPager.setAdapter(mPagerAdapter);
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
    
            int id = item.getItemId();
    
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    
        public ArrayList<String> getImagesFromStorage()
        {
            ArrayList<String> fileNameList= new ArrayList<String>();
            File file= new File(getApplicationContext().getExternalFilesDir(null).getAbsolutePath()+ File.separator + "savedFiles");
    
            if (file.isDirectory())
            {
                File[] listOfFiles= file.listFiles();
                for (int i = 0; i <listOfFiles.length; i++)
                {
    
                    fileNameList.add(listOfFiles[i].getAbsolutePath());
                }
            }
            return fileNameList;
        }
    
    }
    

    I tried turning on GPU Acceleration as some post suggested but it didn't work. I tried playing the video on the main activity instead on the fragment and it worked, so im gussing that the problem is with my fragment. any suggestions?

    Edit:

    the adapter:

    public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        private ArrayList<String> fileNames;
        private Context context=null;
    
    
        public ScreenSlidePagerAdapter(FragmentManager fragmentManager, ArrayList<String> fileNameList,Context context) {
            super(fragmentManager);
            this.fileNames=fileNameList;
            this.context=context;
        }
    
    
        @Override
        public Fragment getItem(int position) {
    
            return ScreenSlidePageFragment.create(fileNames.get(position),this.context);
        }
    
        @Override
        public int getCount() {
            return fileNames.size();
        }
    }