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 Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

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 sync completed.
Update the project build config …

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit.
What is Retrofit?
If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps.

Further, you can check the Retrofit Library here.

So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website.
Prerequisite for using the Retrofit for WordPress Android App
There is s…