'Added the code for loading image in the recycler view inside the fragment , but it is not working

I want to load the gallery images from the phone gallery and display them all in the recycler view which is in the fragment viewpager as Grid view.

Here's the code for the recycler adapter class, class for fetching the images from the gallery , fragment adapter class and fragment kt file. All the 4 kt files are not giving any error , even the whole project is not giving any error, but still the app is crashing on running the app.

In the logcat, the error is giving at all the three lines where ImageGallery class is used. And in Image Gallery class it is giving the error at :

val imagecursor: Cursor? = context.contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, orderBy+"DESC"
            )

Recycler Adapter Code:

package com.nandini.android.fragmentstab

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide

class CustomAdapter(var context: Context, var imageList: ArrayList<String>):RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

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

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

    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        var image: String = imageList[position]

        Glide.with(context).load(image).into(holder.img_itm)
    }

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

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

}

Class for fetching files:

package com.nandini.android.fragmentstab

import android.content.Context
import android.database.Cursor
import android.provider.MediaStore

public 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? = context.contentResolver.query(
                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
        }
    }

Fragment Adapter Class 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 Code:

package com.nandini.android.fragmentstab

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

class AllFragment : Fragment() {

    private var param1: String? = null
    private var param2: String? = null

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

    var galleryNumber: TextView?=null
    private final var MY_READ_PERMISSION_CODE=101

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

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

    private fun loadImage(){
        recyclerView?.layoutManager=GridLayoutManager(context,3)
        dataList= ImageGallery().listOfImages(requireContext())
        adapterr= context?.let { CustomAdapter(it,dataList) }
        recyclerView?.adapter =adapterr
        galleryNumber?.text=("Photos ("+ dataList.size+")")
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode== MY_READ_PERMISSION_CODE){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Toast.makeText(activity,"Read external storage permission granted.",Toast.LENGTH_SHORT).show()
                loadImage()
            }else{
                Toast.makeText(activity,"Read externalstotrage permission denied.",Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        galleryNumber=view?.findViewById(R.id.gallery_number)

        if(activity?.let { ContextCompat.checkSelfPermission(it, Manifest.permission.READ_EXTERNAL_STORAGE) } != PackageManager.PERMISSION_GRANTED){

            ActivityCompat.requestPermissions(
                requireActivity() ,
                arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),MY_READ_PERMISSION_CODE)

        }else{
            loadImage()
        }

        var view:View=inflater.inflate(R.layout.fragment_all, container, false)
        recyclerView=view.findViewById(R.id.recyclerView)
        return view
    }

    companion object {

        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            AllFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source