Home > Enterprise >  NullPointerException on RecyclerView setLayoutManager
NullPointerException on RecyclerView setLayoutManager

Time:04-10

I have faced the problem that my application will keep stopping when clicking search page fragments. I do not understand why this problem will happen? I directly used my other success code in another fragment but in this fragment suddenly appear this problem. Can somebody help me? Thank you for your help!!

My problem error :

java.lang.NullPointerException: Attempt to invoke virtual method
'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)'
on a null object reference at com.example.assignment_mad.Search_Page_Fragment.onViewCreated(Search_Page_Fragment.kt:153)

My main frgment ( Search_Page_Fragment ) :

    package com.example.assignment_mad

    import android.content.Intent
    import android.os.Bundle
    import androidx.fragment.app.Fragment
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.Toast
    import androidx.recyclerview.widget.LinearLayoutManager
    import androidx.recyclerview.widget.RecyclerView
    import kotlinx.android.synthetic.main.fragment_notification_.*

    class Search_Page_Fragment : Fragment() {

        private lateinit var newRecyclerView: RecyclerView
        private lateinit var newArrayList: ArrayList<Company_Search>
        private lateinit var tempArrayList: ArrayList<Company_Search>
        lateinit var imageId:Array<Int>
        lateinit var job_name:Array<String>
        lateinit var saveicon:Array<Int>
        lateinit var company_name:Array<String>
        lateinit var place:Array<String>
        lateinit var salary:Array<String>
        lateinit var news:Array<String>


        private var layoutManager: RecyclerView.LayoutManager? = null
        private var adapter: RecyclerView.Adapter<Search_Page_Adapter.MyViewHolder>? = null

        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            var views =inflater.inflate(R.layout.fragment_search__page_, container, false)
            newRecyclerView=views.findViewById(R.id.recyclerView_Search)

            // Inflate the layout for this fragment
            return views


        }

        override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {

            imageId= arrayOf(
                R.drawable.company_logo_1,
                R.drawable.company_logo_2,
                R.drawable.company_logo_3,
                R.drawable.company_logo_4,
                R.drawable.company_logo_5,
                R.drawable.company_logo_6,
                R.drawable.company_logo_7,
                R.drawable.company_logo_8,
                R.drawable.company_logo_9,
                R.drawable.company_logo_10
            )

            job_name= arrayOf(
                "Engineer",
                "Computer",
                "Coder",
                "Teacher",
                "Engineer",
                "Engineer",
                "Engineer",
                "Engineer",
                "Engineer",
                "Engineer"
            )

            saveicon= arrayOf(
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24,
                R.drawable.ic_baseline_bookmark_added_24
            )

            company_name= arrayOf(
                "Phonix Sdn Bhd",
                "Computer Sdn Bhd",
                "Coder",
                "Teacher",
                "Engineer",
                "Engineer",
                "Engineer",
                "Engineer",
                "Engineer",
                "Engineer"
            )

            place= arrayOf(
                "Kuala Lumpur",
                "Kuala Lumpur",
                "Selangor",
                "Rimbunan",
                "Kuala Lumpur",
                "Kuala Lumpur",
                "Kuala Lumpur",
                "Kuala Lumpur",
                "Kuala Lumpur",
                "Kuala Lumpur"
            )

            salary= arrayOf(
                "RM3000",
                "RM4000",
                "RM3500",
                "RM2000",
                "RM1000",
                "RM3000",
                "RM3000",
                "RM3000",
                "RM3000",
                "RM3000",
            )

            news= arrayOf(
                getString(R.string.news_a),
                getString(R.string.news_b),
                getString(R.string.news_c),
                getString(R.string.news_d),
                getString(R.string.news_e),
                getString(R.string.news_f),
                getString(R.string.news_g),
                getString(R.string.news_h),
                getString(R.string.news_i),
                getString(R.string.news_j)
            )

            newArrayList= arrayListOf<Company_Search>()
            tempArrayList= arrayListOf<Company_Search>()
            getUserdata()

            super.onViewCreated(itemView, savedInstanceState)

            newRecyclerView.apply {
                layoutManager= LinearLayoutManager(activity)
                newRecyclerView.setHasFixedSize(true)

            }


            recyclerView.apply {
                // set a LinearLayoutManager to handle Android
                // RecyclerView behavior
                layoutManager= LinearLayoutManager(activity)
                // set the custom adapter to the RecyclerView
                adapter = Search_Page_Adapter(newArrayList)
            }

        }


        private fun getUserdata() {
            for (i in imageId.indices){
                val companySearch=Company_Search(imageId[i],job_name[i],saveicon[i],company_name[i],place[i],salary[i])
                newArrayList.add(companySearch)
            }

    //        tempArrayList.addAll(newArrayList)
    //
    //        val adapter = Notification_Fragment(tempArrayList)

            var adapter=Search_Page_Adapter(newArrayList)
            newRecyclerView.adapter=adapter
            adapter.setOnItemClickListener(object :Search_Page_Adapter.onItemClickListener{
                override fun onItemClick(position: Int) {
                    Toast.makeText(context,"You clicked in item no . $position",Toast.LENGTH_SHORT).show()

                    val intent= Intent(context,Search_Page_Detail::class.java)
                    intent.putExtra("name",newArrayList[position].job_name)
                    intent.putExtra("imageId",newArrayList[position].titleImage)
                    intent.putExtra("news",news[position])
                    startActivity(intent)
                }
            })
        }


    }

The page adapter :

    package com.example.assignment_mad

    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.TextView
    import androidx.recyclerview.widget.RecyclerView
    import com.google.android.material.imageview.ShapeableImageView

    class Search_Page_Adapter(private val companysList:ArrayList<Company_Search>):RecyclerView.Adapter<Search_Page_Adapter.MyViewHolder>() {

        private var mListener:onItemClickListener?=null

        interface onItemClickListener{
            fun onItemClick(position: Int)
        }

        fun setOnItemClickListener(listener: onItemClickListener){
            mListener=listener
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

            val itemView=LayoutInflater.from(parent.context).inflate(R.layout.list_item_search,parent,false)
            return MyViewHolder(itemView,mListener)
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            val currentItem=companysList[position]
            holder.titleImage.setImageResource(currentItem.titleImage)
            holder.job_name.text=currentItem.job_name
            holder.save_icon.setImageResource(currentItem.save_icon)
            holder.company_name.text=currentItem.company_name
            holder.place.text=currentItem.place
            holder.salary.text=currentItem.salary


        }

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

        //to insert the post detail
        class MyViewHolder(itemView: View,listener: onItemClickListener?):RecyclerView.ViewHolder(itemView){

            val titleImage:ShapeableImageView=itemView.findViewById(R.id.title_image2)
            val job_name:TextView=itemView.findViewById(R.id.job_name)
            val save_icon:ShapeableImageView=itemView.findViewById(R.id.save_icon)
            val company_name:TextView=itemView.findViewById(R.id.company_name)
            val place:TextView=itemView.findViewById(R.id.detail_place)
            val salary:TextView=itemView.findViewById(R.id.detail_salary)

            init {
                itemView.setOnClickListener{
                    listener?.onItemClick(adapterPosition)
                }
            }
        }

    }

The xml file for search_fragment :

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".Search_Page_Fragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@ id/search_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Search Job"
            android:inputType="text"
            android:minHeight="48dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@ id/place_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:text="Area, City or Town"
            android:textSize="16sp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="32dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@ id/search_bar"
            app:layout_constraintStart_toStartOf="parent"/>

        <Spinner
            android:id="@ id/spinner_job"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="200dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@ id/place_name" />

        <TextView
            android:id="@ id/job_specialize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:text="Job Specialize"
            android:textSize="16sp"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="32dp"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@ id/search_bar"
            app:layout_constraintEnd_toEndOf="parent" />

        <Spinner
            android:id="@ id/spinner_place"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="200dp"
            app:layout_constraintTop_toBottomOf="@ id/job_specialize"
            app:layout_constraintEnd_toEndOf="parent"
            />


        <androidx.recyclerview.widget.RecyclerView
            android:id="@ id/recyclerView_Search"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="108dp"
            app:layout_constraintTop_toBottomOf="@ id/spinner_job"
            tools:layout_editor_absoluteX="-16dp"
            tools:listitem="@layout/list_item_search" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</FrameLayout>

The list_item_search_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:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="8dp">


    <com.google.android.material.imageview.ShapeableImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:id="@ id/title_image2"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:shapeAppearanceOverlay="@style/RoundCorner"
        android:src="@drawable/company_logo_1"/>

    <TextView
        android:id="@ id/job_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/blue"
        android:text="Gradute Engineer"
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/title_image2"/>

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@ id/save_icon"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/title_image2"
        android:layout_marginEnd="32dp"
        app:shapeAppearanceOverlay="@style/RoundCorner"
        android:src="@drawable/ic_baseline_bookmark_added_24"/>


    <TextView
        android:id="@ id/company_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:text="Neric Compat"
        android:textSize="18sp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/job_name"/>

    <TextView
        android:id="@ id/detail_place"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:text="Petaling Jaya"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/company_name"/>

    <TextView
        android:id="@ id/detail_salary"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:text="MYR 3,700 - 4,300 /Month"
        android:textSize="16sp"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/detail_place"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_margin="8dp"
        style="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/detail_salary"
        android:background="@color/underline"/>


</androidx.constraintlayout.widget.ConstraintLayout>

CodePudding user response:

Your NullPointerException indicates that when this line of code is reached...

        layoutManager= LinearLayoutManager(activity)

...that your newRecyclerView is null. Are you sure that you have the right resource ID here when you attempt to set it?

        newRecyclerView=views.findViewById(R.id.recyclerView_Search)

Try using the debugger and set a breakpoint on these two lines to confirm is newRecyclerView is indeed null.

CodePudding user response:

You must assign the RecyclerView a LayoutManager. Since you have both of them, place this line as the last statement of recyclerView.apply { … } block(s):

setLayoutManager(layoutManager)
//               ↑↑↑↑↑↑↑↑↑↑↑↑↑
//               Your LayoutManager
  • Related