Skip to main content

How to Create Video Gallery App Using Recyclerview



Here we will create a simple Video Gallery in android using Recyclerview. Below is the project structure of this tutorial. You can download the demo app from Google Play.



You may Like:-




Below is the Project Structure of our  Video Gallery using Recyclerview App











Project Structure

Project Setup for creating the Video Gallery using Recyclerview


In above given screen shots you can see the hierarchy of our Video Gallery example tutorial. For creating the project go Android Studio File Menu - New - New Project and then give the name of your project and select an empty Activity.


1.Update build.gradle


First of all you have to update your app level build.gradle file to include some gradle dependency. So modify your build.gradle file as given below.

build.gradle

 apply plugin: 'com.android.application'  
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.debugandroid.videolist"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.0'
compile 'com.android.support:recyclerview-v7:24.2.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
testCompile 'junit:junit:4.12'
}


2. Create xml file


In second steps we will create our xml file for our Video Gallery
activity_main.xml
 <?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.debugandroid.VideoGallery.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recyclerView">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>

video_item.xml
 <?xml version="1.0" encoding="utf-8"?>  
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="1dp"
android:layout_margin="2dp">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardCornerRadius="1dp"
android:layout_margin="0dp">
<ImageView
android:layout_width="200dp"
android:layout_height="100dp"
android:id="@+id/media_img_bck"
android:layout_gravity="center"
android:scaleType="fitXY"
/>
<TextView
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:gravity="right|top"
android:textSize="10sp"
android:textStyle="italic"
android:id="@+id/media_new"
android:layout_gravity="right|top"
android:layout_marginBottom="10dp"
android:visibility="invisible"/>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:gravity="left|top"
android:id="@+id/media_name"
android:textColor="@android:color/primary_text_light"
android:layout_gravity="center_vertical"
android:layout_weight="0.60"
android:textSize="12sp"/>
<TextView
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:gravity="left"
android:textSize="10sp"
android:textStyle="normal"
android:textColor="@android:color/secondary_text_dark"
android:id="@+id/media_details"
android:layout_gravity="center_vertical"
android:layout_marginBottom="10dp"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>

header.xml
 <?xml version="1.0" encoding="utf-8"?>  
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="1dp"
android:layout_marginBottom="0dp"
android:layout_marginTop="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
>
<TextView
android:id="@+id/gallery_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"
android:layout_gravity="left"
android:gravity="left"
android:textSize="16sp"
android:textColor="@android:color/primary_text_light" />
</android.support.v7.widget.CardView>

footer.xml
 <?xml version="1.0" encoding="utf-8"?>  
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="1dp"
android:layout_marginBottom="0dp"
android:layout_marginTop="0dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
>
<TextView
android:id="@+id/gallery_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gallery"
android:layout_gravity="left"
android:gravity="left"
android:textSize="16sp"
android:textColor="@android:color/primary_text_light" />
</android.support.v7.widget.CardView>


As you can saw that we have created four xml files hear, here one activity_main.xml is the main layout file of our application, video_item.xml will be used for display the indiviual video inside recyler view and header & footer view will be used to display the header inside our recycler view. However here in this example we are not going to use the footer but adding it here if you required then you can enable it by just putting true at the time of adapter initialization.

 

3.Creating class for our Video Gallery using Recyclerview


Here we will create for java file which we use in our project.



  • MainActivity.java is the main activity launch class from where we start our app.

  • MediaQuery.java will be used to featch the details of the video.

  • VideoAdapter.java is adapter for our recycler view to show the video.

  • VideoItem.java is the class to define the Video Item details like Name, size etc.





VideoItem.java
 package com.debugandroid.VideoGallery;  
/**
* Created by Pawan on 4/8/2016.
*/
public class VideoItem {
String _ID;
String ARTIST;
String TITLE;
String DATA;
String DISPLAY_NAME;
String DURATION;
public VideoItem(String _ID, String ARTIST, String TITLE,
String DATA, String DISPLAY_NAME, String DURATION){
this._ID=_ID;
this.ARTIST=ARTIST;
this.TITLE=TITLE;
this.DATA=DATA;
this.DISPLAY_NAME=DISPLAY_NAME;
this.DURATION=DURATION;
};
public VideoItem(){
}
public String get_ID() {
return _ID;
}
public void set_ID(String _ID) {
this._ID = _ID;
}
public String getARTIST() {
return ARTIST;
}
public void setARTIST(String ARTIST) {
this.ARTIST = ARTIST;
}
public String getTITLE() {
return TITLE;
}
public void setTITLE(String TITLE) {
this.TITLE = TITLE;
}
public String getDATA() {
return DATA;
}
public void setDATA(String DATA) {
this.DATA = DATA;
}
public String getDISPLAY_NAME() {
return DISPLAY_NAME;
}
public void setDISPLAY_NAME(String DISPLAY_NAME) {
this.DISPLAY_NAME = DISPLAY_NAME;
}
public String getDURATION() {
return DURATION;
}
public void setDURATION(String DURATION) {
this.DURATION = DURATION;
}
}

MediaQuery.java
 package com.debugandroid.VideoGallery;  
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Pawan on 4/8/2016.
*/
public class MediaQuery {
private Context context;
private int count = 0;
private Cursor cursor;
List<VideoItem> videoItems;
public MediaQuery(Context context){
this.context=context;
}
public List<VideoItem> getAllVideo() {
String selection = null;
String[] projection = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.ARTIST,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DURATION
};
cursor = context.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection,
selection,
null,
null);
videoItems = new ArrayList<VideoItem>();
VideoItem videoItem;
while (cursor.moveToNext()) {
videoItem = new VideoItem();
videoItem.set_ID(cursor.getString(0));
videoItem.setARTIST(cursor.getString(1));
videoItem.setTITLE(cursor.getString(2));
videoItem.setDATA(cursor.getString(3));
videoItem.setDISPLAY_NAME(cursor.getString(4));
videoItem.setDURATION(cursor.getString(5));
videoItems.add(videoItem);
}
return videoItems;
}
public int getVideoCount(){
int count=0;
count=(getAllVideo()).size();
return count;
}
}

VideoAdapter.java
 package com.debugandroid.VideoGallery;  
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
/**
* Created by Pawan on 2/20/2016.
*/
public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<VideoItem> videoList;
Context context;
private final static int FADE_DURATION = 1000;
public static Glide glid;
private String album_name;
String name;
int days;
Bundle bundle=new Bundle();
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
private static final int TYPE_FOOTER = 2;
private boolean mWithHeader;
private boolean mWithFooter;
public VideoAdapter(List<VideoItem> videoList, Context context, String album, boolean withHeader, boolean withFooter) {
this.videoList = videoList;
this.context=context;
this.album_name=album;
this.mWithHeader=withHeader;
this.mWithFooter=withFooter;
}
@Override
public int getItemViewType(int position) {
if (mWithHeader && isPositionHeader(position))
return TYPE_HEADER;
if (mWithFooter && isPositionFooter(position))
return TYPE_FOOTER;
return TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if(viewType==TYPE_HEADER) {
return new headView(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.header, viewGroup, false));
}
else if(viewType==TYPE_FOOTER){
return new footer(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.footer, viewGroup, false));
}
else {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.video_item, viewGroup, false);
VideoViewHolder holder = new VideoViewHolder(itemView);
itemView.setTag(holder);
return holder;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof headView){
((headView) holder).vName.setText(album_name);
}
else if(holder instanceof footer){
((footer) holder).context = context;
}
else {
VideoItem mediaObject=getItem(position);
name=mediaObject.getDISPLAY_NAME();
if (name.length() > 25) {
((VideoViewHolder) holder).vName.setText(name.substring(0, 25) + "..");
} else {
((VideoViewHolder) holder).vName.setText(name);
}
((VideoViewHolder) holder).vImage.setImageResource(R.color.cardview_dark_background);
((VideoViewHolder) holder).vFilePath = mediaObject.getDATA();
((VideoViewHolder) holder).context = context;
((VideoViewHolder) holder).b = bundle;
((VideoViewHolder) holder).position = position;
glid.with(context)
.load(mediaObject.getDATA())
.centerCrop()
.placeholder(R.color.cardview_dark_background)
.crossFade()
.into(((VideoViewHolder) holder).vImage);
setScaleAnimation(((VideoViewHolder) holder).vImage);
}
}
private void setScaleAnimation(View view) {
ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
private void setFadeAnimation(View view) {
AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(FADE_DURATION);
view.startAnimation(anim);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
int itemCount = videoList.size();
if (mWithHeader)
itemCount=itemCount+1;
if (mWithFooter)
itemCount=itemCount+1;
return itemCount;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private boolean isPositionFooter(int position) {
return position == getItemCount() - 1;
}
protected VideoItem getItem(int position) {
return mWithHeader ? videoList.get(position - 1) : videoList.get(position);
}
private int getItemPosition(int position){
return mWithHeader ? position - 1 : position;
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
protected ImageView vImage;
protected TextView vName;
protected TextView vDetails,vNew;
protected String vFilePath;
protected Context context;
protected Bundle b;
protected int position;
public void clearAnimation()
{
this.clearAnimation();
}
public VideoViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.media_name);
vImage = (ImageView) v.findViewById(R.id.media_img_bck);
vDetails = (TextView) v.findViewById(R.id.media_details);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent movieIntent = new Intent();
movieIntent.setAction(android.content.Intent.ACTION_VIEW);
movieIntent.setDataAndType(Uri.parse(vFilePath), "video/*");
context.startActivity(movieIntent);
}
});
}
}
public class headView extends RecyclerView.ViewHolder {
protected TextView vName;
protected Context context;
protected Bundle b;
protected int position;
public headView(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.gallery_title);
}
}
public class footer extends RecyclerView.ViewHolder {
protected Context context;
protected int position;
public footer(View v) {
super(v);
}
}
}

4. Create MainActivity.java file


Till now we have created our all supporting calls and finally we have to modify your MainActivity.java, so modify it as given below.
 package com.debugandroid.VideoGallery;  
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private MediaQuery mediaQuery;
private List<VideoItem> videoItemList;
private RecyclerView recyclerView;
private VideoAdapter videoAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
videoItemList=new ArrayList<VideoItem>();
mediaQuery=new MediaQuery(this);
videoItemList=mediaQuery.getAllVideo();
Log.d("VideoList","Count:"+videoItemList.size());
videoAdapter=new VideoAdapter(videoItemList,this,"Gallery",true,false);
GridLayoutManager glm = new GridLayoutManager(this, 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (videoAdapter.getItemViewType(position)) {
case 0:
return 2;
case 1:
return 1;
case 2:
return 2;
default:
return 1;
}
// return (position == 0||position==1||position==2) ? 2 : 1;
}
});
// GridLayoutManager gridLayoutManager=new GridLayoutManager(this,2);
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(videoAdapter);
}
}

5.Setting permission for Video Gallery


Lastly you have to setup the permission to read the all video from storage. In api level 21 or higer you have to write some code as well. So add below permission in your AndroidManifest.xml.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

So our Video Gallery is read to test, you can run and use it, even you can play your video.

I have tried to keep it very simple but if you have any query or doubt than comment below or you may refer older post.
If you like this tutorial want to be in touch then you can like us on Facebook, Tiwtter and Google+
Source Code is available on https://github.com/debugandroid/VideoGallery


Comments

  1. […] Download our Video Gallery Demo App for working demo and if your want checks out the complete working tutorial then check out How to create Video Gallery in Android Tutorial. […]

    ReplyDelete
  2. […] our earlier tutorial we have create a Video Gallery app today we will learn how to implement native ad to our Video Gallery app. Video Gallery Demo app […]

    ReplyDelete
  3. Sir , I am not able to create slider for my images .
    It should be like when I click on a image ,it should take Me to another activity and then I should be able to slide left right to view other images from the gallery, please help sir ,I am very badly stuck .
    Hoping to get reply from you soon sir ,thank you

    ReplyDelete
  4. Use the viewpager to create the slider -
    Step1: On click event start the new activity with following data with Intent
    a: Array of all image url
    b: current position of click event
    Step2: Use the viewpager in your new activity to render the all image and show on the screen

    Below is the sample ViewPager adapter code

    public class PhotoPagerAdapter extends PagerAdapter {

    private final static int FADE_DURATION = 1000;
    private List IMAGES;
    private LayoutInflater inflater;
    private Context context;
    private Matrix matrix = new Matrix();

    public PhotoPagerAdapter(Context context,List IMAGES) {
    this.context = context;
    this.IMAGES=IMAGES;
    inflater = LayoutInflater.from(context);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
    }

    @Override
    public int getCount() {
    return IMAGES.size();
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
    View imageLayout = inflater.inflate(R.layout.slidingimageslayout, view, false);

    assert imageLayout != null;
    PhotoView imageView = (PhotoView) imageLayout
    .findViewById(R.id.image);


    GlideApp.with(context)
    .load(IMAGES.get(position).getData())
    //.thumbnail(0.2f)
    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
    .skipMemoryCache(false)
    .into(imageView);

    view.addView(imageLayout, 0);

    return imageLayout;
    }
    private void setFadeAnimation(View view) {
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
    return view.equals(object);
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }
    public Point getDisplaySize(Display display) {
    Point size = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
    display.getSize(size);
    } else {
    int width = display.getWidth();
    int height = display.getHeight();
    size = new Point(width, height);
    }

    return size;
    }
    @Override
    public Parcelable saveState() {
    return null;
    }

    @Override
    public int getItemPosition(Object object) {

    return POSITION_NONE;
    }
    }

    ReplyDelete
  5. Hi,

    It's a gerat tutorial...how to get video folder names ..when I click folder name next screen show videos in that folder...

    Thanks

    ReplyDelete
  6. […] connect that particular network. We will add this functionality to our existing Demo app “Video Gallery“. If you would like to check out the demo of the app then downloaded the app from Google Play […]

    ReplyDelete
  7. […] Download our Video Gallery Demo App for working demo and if your want checks out the complete working tutorial then check out How to create Video Gallery in Android Tutorial. […]

    ReplyDelete
  8. […] now you can test your app, we have done this tutorial on previous tutorial of creating VideoGallery app in […]

    ReplyDelete
  9. […] Read:- How to Create Video Gallery App Using Recyclerview Step by Step Guide to create option Menu in […]

    ReplyDelete
  10. get Vedio Album return an unsorted arraylist so how to sort this and also how to use group by?

    ReplyDelete
  11. you can modify the order by variable as required.

    String orderBy = MediaStore.Images.Media.DATE_TAKEN;

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Scan and List All Available WiFi Network In Android

In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. You May Like Below Topic: How to Read and Write JSON data using GSON WP Android App using REST and volley WP Android App using REST and volley part2 Implementation of SwipeRefreshLayout in RecyclerView Create Amazing Bottom Navigation Bar Without Any External Library Introduction In this tutorial, we learn how to connect to a WiFi hotspot in android by code. In this Demo we will create an as small app which will scan the all available network or Hotspot and list down the network when you select specific network, the application will connect that particular network. We will add this functionality to our existing Demo app " Video Gallery ". If you would like to check out t