Home > OS >  Crashing on loading gallery adapter for recyclerview
Crashing on loading gallery adapter for recyclerview

Time:01-24

Edit: After JonR85's answer it returned the image adapter but now after returning the inflated view it crashes the application


override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        var _galleryFragment:View?
          _galleryFragment =   requireActivity().findViewById<View>(R.id.gallery_fragment) as View
              galleryFragment =   GetGalleryFragment(inflater,container) as View


             galleryNumberText =     (galleryFragment).findViewById(R.id.galleryNumber) as? TextView?
             recyclerView = (galleryFragment).findViewById(R.id.recyclerViewImageItems) as? RecyclerView?

             if(ContextCompat.checkSelfPermission(this.context as Context,Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this.parentFragment?.getActivity() as MainActivity,
                Array<String>(2){Manifest.permission.READ_EXTERNAL_STORAGE},READ_PERMISSION_CODE)
            var i:Any?;
        }
        else
        {
            loadImages()
        }
           return galleryFragment
    }

I have been trying to setup a recyclerview in a fragment(which first is inflated then assigns the objects(recycler view and the text view) in the class that constains the image with the recyclerview and ask for permision but somehow just when it loads the recyclerview it closes the application(apparently crashes at E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.applicationtest, PID: 14303 java.lang.NullPointerException at com.example.applicationtest.gallery_fragment.loadImages(gallery_fragment.kt:140) at com.example.applicationtest.gallery_fragment.onCreateView(gallery_fragment.kt:104) at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282) at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189) at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106) at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002) at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524) at android.os.Handler.handleCallback(Handler.java:938) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:236) at android.app.ActivityThread.main(ActivityThread.java:8037) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

which calls a GalleryAdapter's constructor

abd I have created a galleryElement in a different view to the fragment(I didnt include it), what could be causing the crash?

    fun loadImages(){
        recyclerView!!.setHasFixedSize(true)
        recyclerView!!.layoutManager = GridLayoutManager(this.activity,4)

        try {
            this.imageList = ImageGallery.GetImagesList(this.context as Context )
        }
        catch (ex:Exception)
        {
            println(ex.message)
        }
        galleryAdapter = GalleryAdapter(this.context as Context,imageList,
            object : IPhotoInterface {
                override fun onPhotoClick(stringPath: String):Unit {
                    //process picture on click
                }
            })
       try {
           recyclerView?.adapter = galleryAdapter
           galleryNumberText?.text = "${imageList.size} images"
       }
        catch(ex:Exception)
        {
            println(ex.message)
        }
    }```

GalleryAdapter


 class GalleryAdapter(var ctx: Context, var listOfImages:MutableList<String>,var photoListener: ViewHolder.IPhotoInterface): RecyclerView.Adapter<GalleryAdapter.ViewHolder>() {
    
        class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
    
            fun GetImageInit(view:View):ImageView =view.findViewById(R.id.imageElement1)
    
            var image : ImageView
    
            init {
                image  = GetImageInit(itemView) as ImageView
            }
            interface IPhotoInterface {
    
                fun onPhotoClick(stringPath:String): Unit
            }
    
        }
    
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
          var inflatedView:View =  LayoutInflater.from(this.ctx).inflate(R.layout.gallery_fragment,parent,false)
           return ViewHolder(inflatedView)
        }
    
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            var image:String = (listOfImages as List<String>).get(position)
            Glide.with(ctx).load(image).into(holder.image)
            holder.itemView.setOnClickListener{view->
                this.photoListener.onPhotoClick(image)
            }
        }
    
        override fun getItemCount(): Int {
           return this.listOfImages.size
        }
    }

```

gallery_fragment

```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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".gallery_fragment"
    android:background="#333333"
    android:orientation="vertical">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:id="@ id/galleryNumberContainer">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ id/galleryNumber"
            android:layout_centerVertical="true"
            android:layout_marginLeft="16dp"
            android:textColor="@color/white"
            android:textStyle="bold"
            android:textSize="18dp"
            />
    </RelativeLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerViewImageItems"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </androidx.recyclerview.widget.RecyclerView>

</RelativeLayout>

GalleryItem in a different view file
```xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@ id/gallery_item"
    
        >
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:scaleType="centerCrop"
            app:layout_constraintDimensionRatio="1"
            android:id="@ id/imageElement1"
            tools:ignore="MissingConstraints"
            ></ImageView>
    </androidx.constraintlayout.widget.ConstraintLayout>

how I have obtained the image list

kotlin
 

public fun GetImagesList(context: Context):MutableList<string>{
            lateinit var uri:Uri
            var cursor:Cursor?
            var columnIndexDataId:Int =0
            var imageCollectionList:MutableList<string> =  mutableListOf<string>()
            var projection:Array<string>
            var absoluteImagePath:String =""
            uri =MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            var selection:string = "_id?"
           // var selectionArgs :Array<string> = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])

            try {
                val columnName:string="_data"
                projection = arrayOf(columnName)
                cursor =context.contentResolver.query(uri,null,null,null,null)
               //if cursor is not null then execute codeblock
                cursor?.let {
                        while(it.moveToNext())
                        {
                            val columnIndex = cursor.getColumnIndexOrThrow(columnName)
                            absoluteImagePath =cursor.getString(columnIndex)
                            imageCollectionList.add(absoluteImagePath)
                        }
                }
            }
            catch (ex:Exception){
                    print(ex.message)
            }
            return imageCollectionList
        }

CodePudding user response:

class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){

        var image : ImageView = view.findViewById(R.id.imageElement1)

        interface IPhotoInterface {

            fun onPhotoClick(stringPath:String): Unit
        }

    }
  •  Tags:  
  • Related