When app is on portrait, everything is fine, but when I use landscape (I create 2 vision of the app, but only portrait works), the app suddenly closes and shows that java.lang.NullPointerException: findViewById(R.id.roll_button) must not be null
or Unable to start activity ComponentInfo{MainActivity}: java.lang.NullPointerException
.
I added some solutions from internet including adding android:configchanges
or android:scrrenOrientation="portrait"
, it didnot help.
The code is show below:
MainActivity:
class MainActivity : AppCompatActivity() {
lateinit var diceImage: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.roll_button)!!
rollButton.setOnClickListener {
rollDice()
}
diceImage = findViewById(R.id.dice_image)
}
private fun rollDice() {
val randomInt = Random().nextInt(6) + 1
val drawableResource = when (randomInt) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
diceImage.setImageResource(drawableResource)
}
}
Code below is activity_main.xml: (Most would be fine below)
<?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"
android:configChanges="orientation|screenSize"
tools:context=".MainActivity"
>
<ImageView
android:id="@+id/dice_image"
android:layout_width="123dp"
android:layout_height="96dp"
android:layout_marginStart="144dp"
android:layout_marginTop="112dp"
android:configChanges="orientation|screenSize"
android:src="@drawable/empty_dice"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="TODO" />
<Button
android:id="@+id/roll_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="6dp"
android:text="@string/roll"
android:configChanges="orientation|screenSize"
app:layout_constraintBottom_toTopOf="@+id/textView2"
app:layout_constraintStart_toEndOf="@+id/textView2"/>
</android.support.constraint.ConstraintLayout>