Access videos both in internal storage and external SD card - Android

11.5k views Asked by At

I've developed a simple android app, which will pull videos from path="storage/MicroSD/Videos" and present them in a list view, upon selecting the video, selected video will be played. The videos located in Storage/MicroSD/Videos are played. But videos in other path are not fetched. Please give some idea, how to get videos from all paths(Internal storage and external storage). Additionally if I run the same app on different phones, the SD card path differs like Storage/SD Card o/videos. Now is my question: How can I get a File-object pointing to the default video-directory of any device programmatically?

Main activity

    public class MainActivity extends Activity {

    private ListView mListView;
    private List<String> fileNameList;
    public  String path="storage/MicroSD/Videos";
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    file = Environment.getExternalStorageDirectory();
    fileNameList = getFileListfromSDCard();
    final ListView listView = (ListView) findViewById(R.id.list);
    ArrayAdapter<String> adapter1 = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, android.R.id.text1, fileNameList);
    listView.setAdapter(adapter1);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            int itemPosition = position;
            String itemValue = (String)   listView.getItemAtPosition(position);
            Intent intent = new Intent(MainActivity.this, com.video.videolibrary.SelectedVideo.class);
            intent.putExtra("id", id);
            intent.putExtra("itemValue", itemValue);
            intent.putExtra("path", path);
            startActivity(intent);
        }

        });

    Button button = (Button) findViewById(R.id.btn_Online);
    // Capture button clicks
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
           Intent myIntent = new Intent(MainActivity.this,com.video.videolibrary.SelectedVideo.class);
            startActivity(myIntent);
        }
    });

    }

    private List<String> getFileListfromSDCard() {

    File files = new File(path);
    FileFilter filter = new FileFilter() {
        private final List<String> exts = Arrays.asList("mp4","MP4");
        @Override
        public boolean accept(File pathname) {
            String ext;
            String path = pathname.getPath();
            ext = path.substring(path.lastIndexOf(".") + 1);
            return exts.contains(ext);
        }
    };

    final File [] filesFound = files.listFiles(filter);
    List<String> flLst = new ArrayList<String>();
    if (filesFound != null && filesFound.length > 0) {
        for (File file : filesFound) {
            flLst.add(file.getName());
         }
    }
    return flLst;
    }

    }

Selected video class

        public class SelectedVideo extends Activity {
        VideoView view;AudioManager audioManager;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selected_video);
        view = (VideoView)findViewById(R.id.videoView1);
       Bundle bundle = getIntent().getExtras();
       String path=bundle.getString("path");
       String itemValue = bundle.getString("itemValue");
      view.setVideoURI(Uri.parse(path+"/"+itemValue ));
      VideoView videoView = (VideoView) findViewById(R.id.videoView1);
      MediaController mediaController = new MediaController(this);
      mediaController.setAnchorView(videoView);
      Uri uri = Uri.parse(path+"/"+itemValue);
      DisplayMetrics dm = new DisplayMetrics();
      this.getWindowManager().getDefaultDisplay().getMetrics(dm);
      int height = dm.heightPixels;
      int width = dm.widthPixels;
     videoView.setMinimumWidth(width);
     videoView.setMinimumHeight(height);
     videoView.setMediaController(mediaController);
     videoView.setVideoURI(uri);
     videoView.requestFocus();
     audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
     int maxVolume =    audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
     int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
     SeekBar volControl = (SeekBar)findViewById(R.id.volbar);
     volControl.setMax(maxVolume);
     volControl.setProgress(curVolume);
     volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)    {
            // TODO Auto-generated method stub
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
        }
        });

        Button stopbutton = (Button) findViewById(R.id.btn_stop);
        stopbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            view.pause();

            }
        });

        Button playbutton = (Button) findViewById(R.id.btn_play);
        playbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Bundle bundle = getIntent().getExtras();
            String itemValue = bundle.getString("itemValue");
            Toast.makeText(getApplicationContext(),
                    itemValue, Toast.LENGTH_LONG)
                    .show();
            view.start();
        }
        });

        Button backbutton = (Button) findViewById(R.id.btn_back);
        backbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            view.stopPlayback();
            startActivity(new Intent(SelectedVideo.this, MainActivity.class));
            }
        });

        }
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
    }

Android Manifest file

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.read_external_storage" />
        <application
        android:allowBackup="true"
        android:icon="@mipmap/video_library"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:configChanges="orientation|keyboardHidden">
        <activity
        android:name="com.video.videolibrary.MainActivity"
        android:label="@string/app_name">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>
        <activity
        android:name=".SelectedVideo">
        </activity>
        </application>

        </manifest>
2

There are 2 answers

1
Sebastian Walla On

First of all: Don't hardcode the path to your sdcard. You should rather use getExternalStorageDirectory () to get a File-object pointing at this location. So your variable files should be assigned as following:

File files= Environment.getExternalStorageDirectory(Environment.DIRECTORY_MOVIES);

As this will return you the default location, where videos, accessable to the user will be stored, this one should cover your needs.

The android api says to this:

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

Another option would be to use a ContentProvider. With a Cursor you can query this one and will get every indexed video. This would make your explicit searching for videos unneccessary.

A basic Cursor-query would basically look like this:

Cursor cursor=getContentResolver().query(
    MediaStore.Video.Media,              // The content URI of the table
    mProjection,                         // The columns to return for each row
    mSelectionClause,                    // Selection criteria
    null,                                // replacing placeholders of Selection criterias
    mSortOrder);                         // The sort order for the returned rows

    while(cursor.moveToNext()){
     //work with your data here
    }

Delete this line from your Android-Manifest.xml, it's unneccessary:

<uses-permission android:name="android.permission.read_external_storage" />
0
Raj Padvi On

Try this:

    String path = Environment.getExternalStorageDirectory().toString();
   // String path = "Environment.getExternalStorageDirectory().toString()+"/myvideo";

    ArrayList<String>alPath=new ArrayList<String>();
    ArrayList<String> alName=new ArrayList<String>();

    File directory = new File(path);
    File[] file = directory.listFiles();
    for (int i = 0; i < file.length; i++) {

            alName.add(file[i].getName());
           alPath.add(file[i].getAbsolutePath());


    ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>
   (VideoList.this,android.R.layout.simple_list_item_1,alName);
    listView.setAdapter(arrayAdapter);