I am having a hard time dealing with fragments in an Android app of mine. Something seems weird and a look by somebody else might shed some light.
Here is the XML for the fragment:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
android:id="@+id/theFragmentID"
tools:context=".NiceFragment">
<TextView
android:id="@+id/labelOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Place_Holder-One" />
<TextView
android:id="@+id/labelTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Place_Holder=Two" />
<EditText
android:id="@+id/inpNew"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="60px" />
.....
</FrameLayout>
Here is some Kotlin code I have somewhere in the app (namely in the onCreateView() method of the fragment):
val labelOne = fragHandle.findViewById<TextView>(R.id.labelOne)
labelOne.text = "Some interesting sentence"
val labelTwo = fragHandle.findViewById<TextView>(R.id.labelTwo)
labelTwo.text = "Some other very interesting sentence"
And finally this is the error I get on the last line of the code above:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at me.soft.myapp.NiceFragment.onCreateView(NiceFragment.kt:99)
The four lines of Kotlin code above may be better located in the onViewCreated() method of the fragment. But the point of my question is:
Why is there a problem on the 4th line while the 2nd works perfectly?
From my perspective labelOne and labelTwo are just two totally equivalent objects.
I also tried to put this chunk of code inside onViewCreated(), but the problem is still there.
What detail could I be missing?