0

I have trying to setBackgroundColor recycleView in fragment like in tutorial.

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

    recycleViewRandom.setBackgroundColor(Color.BLUE)

    return inflater.inflate(R.layout.fragment_recycle_view, container, false)
}

and here is my xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".fragments.MainFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleViewRandom"
        android:layout_width="368dp"
        android:layout_height="495dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>

everything looks good, same as in tutorial, but I have got from IDE:

setBackgroundColor(int)' on a null object reference

How is it possible that is null ?

jackfield
  • 65
  • 1
  • 7

1 Answers1

0

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

Declare

 lateinit var                            recycleViewRandom: RecyclerView

Then

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        contentView = inflater.inflate(R.layout.fragment_recycle_view, container, false)
        initUI(contentView)
        return contentView
    }

You should Initialize RecyclerView.

    fun initUI(contentView: View)
    {
        recycleViewRandom= contentView.findViewById(R.id.recycleViewRandom)
        recycleViewRandom.setBackgroundColor(Color.BLUE)
     }
IntelliJ Amiya
  • 70,230
  • 14
  • 154
  • 181