0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Android】Fragmentに引数はNGと学んだ話

Posted at

起きたこと

画面見にくいなーと思ってAndroid端末の設定から表示サイズ変更したところアプリが落ちた。

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.simplefragment/com.example.simplefragment.MainActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.simplefragment.BlankFragment1: could not find Fragment constructor

InstantiationExceptionなるものが出力されたので調べてみた。

原因

調べたら記事がわんさか出てきた。どうやら引数付きのFragmentが原因らしい。
Fragmentは引数なしのデフォルトコンストラクタを持っており、Fragment生成時はこのデフォルトコンストラクタが必要のため呼び出される。
しかし、引数ありのカスタムコンストラクタは許容されておらずInstantiationExceptionが出力されてしまうとのこと。

class BlankFragment1(
    testParam: String ・・・これがいけない
) : Fragment() {

参考:
https://developer.android.com/reference/android/app/Fragment

学び

結局エラーで落ちないようFragmentの引数を削除する方向で修正。
今後はFragmentにはパラメータを渡さないことを心がけたい。。。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?