Wednesday, 4 December 2013

Android Play video from SD Card | Populating a listview with videos from sdcard in android

Hello Friends,
            This is an android simple example which list all videos file store in 
device sd card and Play it in Video view .
Android provides a view control android.widget.VideoView that encapsulates
creating and initializing the MediaPlayer.










1. VideoStoredInSDCard.java

package com.example.videoplayer;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class VideoStoredInSDCard extends Activity {
 private Cursor videocursor;
 private int video_column_index;
 ListView videolist;
 int count;
 String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,
   MediaStore.Video.Thumbnails.VIDEO_ID };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  init_phone_video_grid();
 }

 @SuppressWarnings("deprecation")
 private void init_phone_video_grid() {
  System.gc();
  String[] proj = { MediaStore.Video.Media._ID,
    MediaStore.Video.Media.DATA,
    MediaStore.Video.Media.DISPLAY_NAME,
    MediaStore.Video.Media.SIZE };
  videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
    proj, null, null, null);
  count = videocursor.getCount();
  videolist = (ListView) findViewById(R.id.PhoneVideoList);
  videolist.setAdapter(new VideoAdapter(getApplicationContext()));
  videolist.setOnItemClickListener(videogridlistener);
 }

 private OnItemClickListener videogridlistener = new OnItemClickListener() {
  public void onItemClick(AdapterView parent, View v, 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(VideoStoredInSDCard.this,
     ViewVideo.class);
   intent.putExtra("videofilename", filename);
   startActivity(intent);
  }
 };

 public class VideoAdapter extends BaseAdapter {
  private Context vContext;

  public VideoAdapter(Context c) {
   vContext = c;
  }

  public int getCount() {
   return count;
  }

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

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

  public View getView(int position, View convertView, ViewGroup parent) {
   System.gc();
   ViewHolder holder;
   String id = null;
   convertView = null;
   if (convertView == null) {
    convertView = LayoutInflater.from(vContext).inflate(
      R.layout.listitem, parent, false);
    holder = new ViewHolder();
    holder.txtTitle = (TextView) convertView
      .findViewById(R.id.txtTitle);
    holder.txtSize = (TextView) convertView
      .findViewById(R.id.txtSize);
    holder.thumbImage = (ImageView) convertView
      .findViewById(R.id.imgIcon);

    video_column_index = videocursor
      .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
    videocursor.moveToPosition(position);
    id = videocursor.getString(video_column_index);
    video_column_index = videocursor
      .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
    videocursor.moveToPosition(position);
    // id += " Size(KB):" +
    // videocursor.getString(video_column_index);
    holder.txtTitle.setText(id);
    holder.txtSize.setText(" Size(KB):"
      + videocursor.getString(video_column_index));

    String[] proj = { MediaStore.Video.Media._ID,
      MediaStore.Video.Media.DISPLAY_NAME,
      MediaStore.Video.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(
      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 = getContentResolver();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
      crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND,
      options);
    holder.thumbImage.setImageBitmap(curThumb);
    curThumb = null;

   } /*
    * else holder = (ViewHolder) convertView.getTag();
    */
   return convertView;
  }
 }

 static class ViewHolder {

  TextView txtTitle;
  TextView txtSize;
  ImageView thumbImage;
 }
}


2. ViewVideo.java

package com.example.videoplayer;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class ViewVideo extends Activity {
      private String filename;
      VideoView vv;
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.gc();
            Intent i = getIntent();
            Bundle extras = i.getExtras();
            filename = extras.getString("videofilename");
            // vv = new VideoView(getApplicationContext());
            setContentView(R.layout.activity_view);
            vv = (VideoView) findViewById(R.id.videoView);
            vv.setVideoPath(filename);
            vv.setMediaController(new MediaController(this));
            vv.requestFocus();
            vv.start();
      }
}


3. AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.videoplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.videoplayer.VideoStoredInSDCard"
            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=".ViewVideo" >
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>






Enjoy Coding :)

Download Source code Code

Mukesh Yadav

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

21 comments:

  1. Help me !
    How to get date and duration after show it's?
    I'm use :
    String[] proj = {
    MediaStore.Video.Media._ID,
    MediaStore.Video.Media.DATA,
    MediaStore.Video.Media.DISPLAY_NAME,
    MediaStore.Video.Media.SIZE,
    MediaStore.Video.Media.DATE_TAKEN,
    MediaStore.Video.Media.DURATION
    };
    But it's not return fomat date, time.It's return is : 17564656. why?

    ReplyDelete
  2. Worked well.. Thankyou

    ReplyDelete
  3. can you display its xml file ? thanks in advance

    ReplyDelete
  4. already provided the source code on git...plz cgeck the download link.
    OR
    https://github.com/mukesh4u/android/tree/master/VideoPlayer

    ReplyDelete
  5. it display videos from sd card or videos from any sub folder of sd card can also be displayed using this.

    ReplyDelete
  6. Very nice Tutorial keep it up!!!!!!!!!!!!!!

    ReplyDelete
  7. It doesnot work with 4.4

    ReplyDelete
  8. Hi Mukesh,
    I am working on android application. In this application, I used VideoView to play demo videos. I need to implement the full screen video while clicking the full screen option like youtube. Is there any way to do like this using VideoView ? I am waiting for your reply... Thanks in advance.

    ReplyDelete
  9. Hello,
    how can I delete a video with:

    videolist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView av, View v, int pos, long id) {
    return onLongListItemClick(v, pos, id);
    }
    protected boolean onLongListItemClick(View v, final int pos, long id) {



    final String str= videolist.getItemAtPosition(pos).toString();
    Log.i("ListView", "onLongListItemClick stirng=" + str);
    AlertDialog.Builder builder = new
    AlertDialog.Builder(StoredVideo.this);
    builder.setMessage("Are you sure you want to delete this video ?")
    .setCancelable(false)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {

    // CODE NEEDED TO DELETE VIDEO HERE


    ArrayAdapter myAdapter = (ArrayAdapter)videolist.getAdapter();
    myAdapter.remove(myAdapter.getItem(pos));
    myAdapter.notifyDataSetChanged();

    }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    dialog.cancel();
    }
    });
    AlertDialog alert = builder.create();
    alert.show();
    return true;
    }

    });

    ReplyDelete
  10. Hi Bro .... your post is very very very helpful ...... I have a question that is .... through this code you are showing All the videos from external storage .... but i want to show a specific folder videos can you help me .. I have tried may codes but fail :(

    ReplyDelete
    Replies
    1. Then In that case you need give path and the scan for all media file in that path.

      Delete
  11. how we can play a video in a Alert Dialog, my problem is that video playing correctly but Alert Dialog not show a Media Controller

    ReplyDelete
  12. Thank you for this tutorial! But I noticed that other video formats like .flv .mkv don't appear on the listview. Maybe they don't have thumbnails because they are not playable on a default player/codec? Please help me. Thanks

    ReplyDelete
  13. sir in my list there is 100 + video and when i scrolling down the app goes crash what i do sir...

    ReplyDelete
    Replies
    1. This may be giving you out of memory error.....so try to load data in list in a chunks(like paging).

      Delete
  14. sir how can i add custom mediacontroller with that tutorial..can you tell me about the custom media controller with videoview.

    ReplyDelete
  15. sir i want to add custom mediacontroller with videoview...and how can i add custom mediacontroller with next and prev button.

    ReplyDelete
  16. Can you update this tutorial please! thank you :)

    ReplyDelete
  17. Can you please update this tutorial :) thank you :)

    ReplyDelete
    Replies
    1. Hello Marvin,
      Please check the download link or directly check below
      link
      https://github.com/mukesh4u/android/tree/master/VideoPlayer

      Delete

 

Copyright @ 2013 Android Developer Blog.

Blog Widget by LinkWithin