LoginSignup
8
5

More than 5 years have passed since last update.

【Android】Kotlin Android ExtensionsをFragmentで使ったときのNullPointerExceptionエラー対処法

Posted at

Kotlin Android Extensions をFragmentで使ったときにNullPointerExceptionで落ちたのでその対処法メモです。

結論

onViewCreated()を使う。

環境

kotlin 1.1.50

エラー内容

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

原因

textViewというIDのViewをkotlin-android-extensionsで参照した場合、内部的にはgetView().findViewById(R.id.textView)を実行していて、FragmentのonCreateView()ではgetView()nullになるため。

サンプルコード

レイアウト

fragment_main.xml
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

ダメな例

BadFragment.kt
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater?.inflate(R.layout.fragment_main, container, false)
    textView.text = "foo" // NullPointerException
    return view
}

良い例

GoodFragment.kt
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? =
    inflater?.inflate(R.layout.fragment_main, container, false)

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    textView.text = "foo" // OK
}

補足

ActivityではonCreate()で使っても大丈夫です。

参考

Kotlin Android Extensions - Kotlin Programming Language
https://kotlinlang.org/docs/tutorials/android-plugin.html

Kotlin Android Extensions and Fragments - Stack Overflow
https://stackoverflow.com/questions/34541650/kotlin-android-extensions-and-fragments

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5