Home > Enterprise >  How to Load all the media from gallery of phone to the recycler view in the fragment
How to Load all the media from gallery of phone to the recycler view in the fragment

Time:03-18

I have made fragments in an activity using view pager and added grid layout recycler view in them. I want to load the all the media of my gallery (videos and images) to be displayed in that recycler view. How can I do that ?

This is how it looks like.

enter image description here

I want all the media of the gallery of my phone to display in this grid recycler view, in place of these images.

Here's is my recycler view code:

Adapter code:

package com.nandini.android.fragmentstab

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView

class CustomAdapter(var imageList: ArrayList<ItemViewModel>):RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {

        var view= LayoutInflater.from(parent.context).inflate(R.layout.item_view_photo,parent,false)
//        return RecyclerView.ViewHolder(view)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        var itemViewModel:ItemViewModel = imageList[position]
        holder.imageView.setImageResource(itemViewModel.image)
    }

    override fun getItemCount(): Int {
        return imageList.size
    }

    class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        val imageView: ImageView = itemView.findViewById(R.id.img_itm)
    }

}

Item data class:

package com.nandini.android.fragmentstab

data class ItemViewModel(val image:Int) {
}

Fragment Adapter code:

package com.nandini.android.fragmentstab

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter

class FragmentAdapter(fm:FragmentManager):FragmentStatePagerAdapter(fm,
    BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

    var fragmentList : ArrayList<Fragment> = ArrayList()
    var fragmenttitle:ArrayList<String> = ArrayList()


    override fun getCount(): Int {
        return  fragmentList.size
    }

    override fun getItem(position: Int): Fragment {
        return fragmentList[position]
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return fragmenttitle[position]
    }

    fun addFragment(fragment: Fragment,title:String){
        fragmentList.add(fragment)
        fragmenttitle.add(title)
    }

}

Fragment kt file:

package com.nandini.android.fragmentstab

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [AllFragment.newInstance] factory method to
 * create an instance of this fragment.
 */

class AllFragment : Fragment() {



    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

//    var recyclerView= activity?.findViewById<RecyclerView>(R.id.recyclerView)
//    var adapter:RecyclerView.Adapter<CustomAdapter.ViewHolder>?=null
//    var data = ArrayList<ItemViewModel>()

    lateinit var recyclerView:RecyclerView
     var dataList:ArrayList<ItemViewModel> = ArrayList<ItemViewModel>()
     var adapterr:RecyclerView.Adapter<CustomAdapter.ViewHolder>?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

        var view:View=inflater.inflate(R.layout.fragment_all, container, false)
        recyclerView=view.findViewById(R.id.recyclerView)
        recyclerView.layoutManager=GridLayoutManager(activity,3)
        for(i in 1..50){
            dataList.add(ItemViewModel(R.drawable.image_thumbnail))
        }

        recyclerView.adapter=adapterr
        adapterr=CustomAdapter(dataList)

        return view
    }


    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment PhotosFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            AllFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

Code for Gallery class:

import android.content.Context
import android.database.Cursor
import android.provider.MediaStore
import androidx.core.content.ContentProviderCompat.requireContext
import java.security.AccessController.getContext

class ImageGallery {
    public fun listOfImages(context: Context) : ArrayList<String> {
        var imageList: ArrayList<String> = ArrayList()
        var projection = arrayOf(MediaStore.MediaColumns.DATA,MediaStore.Images.Media.BUCKET_DISPLAY_NAME)
        var orderBy:String=MediaStore.Video.Media.DATE_TAKEN
            val imagecursor: Cursor = getContext().contentResolver.managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, orderBy "DESC"
            )
            for (i in 0 until imagecursor.count) {
                imagecursor.moveToPosition(i)
                val dataColumnIndex =
                    imagecursor.getColumnIndex(MediaStore.Images.Media.DATA)
                imageList.add(imagecursor.getString(dataColumnIndex))
            }
            return imageList
        }
    }

CodePudding user response:

To Fetch Images

var imageList: ArrayList<String> = ArrayList()
fun fetchImages(): ArrayList<String> {
    val columns = arrayOf(MediaStore.Images.Media.DATA, 
    MediaStore.Images.Media._ID)
    val imagecursor: Cursor = requireActivity().managedQuery(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
        null, ""
    )
    for (i in 0 until imagecursor.count) {
        imagecursor.moveToPosition(i)
        val dataColumnIndex = 
        imagecursor.getColumnIndex(MediaStore.Images.Media.DATA)
        imageList.add(imagecursor.getString(dataColumnIndex))
    }
return imageList
}

To Fetch Videos

var videoList: ArrayList<String> = ArrayList()
    fun fetchVideos: ArrayList<String> {
        val columns = arrayOf(MediaStore.Video.Media.DATA, 
        MediaStore.Video.Media._ID)
        val imagecursor: Cursor = requireActivity().managedQuery(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, ""
        )
        for (i in 0 until imagecursor.count) {
            imagecursor.moveToPosition(i)
            val dataColumnIndex = 
            imagecursor.getColumnIndex(MediaStore.Video.Media.DATA)
            videoList.add(imagecursor.getString(dataColumnIndex))
        }
    return videoList
    }

Just concatenate then shuffle array for all fragment or whatever your scenario

Pass these arrays in your adapter

Glide.with(context).load(list.get(position)).into(holder.img_thumbnail)

Hope it helps :) If you have any confusion feel free to ask.

  • Related