-3
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
    val item = menu!!.findItem(R.id.menu_wrong_answer)
    val layout = item.actionView as RelativeLayout
    txt_wrong_answer = layout.findViewById(R.id.txt_wrong_answer) as TextView
    txt_wrong_answer.text = 0.toString()
    return true
}

Error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.abhishek.quiz, PID: 23203
    kotlin.TypeCastException: null cannot be cast to non-null type android.widget.RelativeLayout
        at com.abhishek.quiz.QuestionActivity.onPrepareOptionsMenu(QuestionActivity.kt:260)
        at android.app.Activity.onPreparePanel(Activity.java:3564)
        at androidx.fragment.app.FragmentActivity.onPrepareOptionsPanel(FragmentActivity.java:502)
        at androidx.fragment.app.FragmentActivity.onPreparePanel(FragmentActivity.java:488)
        at androidx.appcompat.view.WindowCallbackWrapper.onPreparePanel(WindowCallbackWrapper.java:99)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onPreparePanel(AppCompatDelegateImpl.java:2857)
        at androidx.appcompat.view.WindowCallbackWrapper.onPreparePanel(WindowCallbackWrapper.java:99)
        at androidx.appcompat.app.ToolbarActionBar$ToolbarCallbackWrapper.onPreparePanel(ToolbarActionBar.java:522)
        at androidx.appcompat.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:456)
        at androidx.appcompat.app.ToolbarActionBar$1.run(ToolbarActionBar.java:56)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6806)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
patrick.elmquist
  • 2,113
  • 2
  • 21
  • 35
aa aa
  • 1
  • 1
  • 3
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – a_local_nobody Nov 15 '19 at 11:20
  • "null cannot be cast to non-null type android.widget.RelativeLayout" means the item.actionView you are trying to cast to RelativeLayout is null. You should make sure it is not null before using it – Alessandro Tedesco Nov 15 '19 at 11:33

1 Answers1

1

I guess the problem is that you are casting null to RelativeLayout here:

val layout = item.actionView as RelativeLayout

Make sure that item.actionView doesn`t equal to null.

Artem
  • 354
  • 1
  • 4