Null Pointer Exception - Findviewbyid()

Null pointer Exception - findViewById()

findViewById() returns a View if it exists in the layout you provided in setContentView(), otherwise it returns null and that's what happening to you. Note that if you don't setContentView(), and don't have a valid view to findViewById() on, findViewById() will always return null until you call setContentView().

This also means variables in the top-level trigger an NPE, because they're called before onCreate(), and by extension, before setContentView(). See also the activity lifecycle

Example if you setContentView(R.layout.activity_first); and then call findViewById(R.id.first_View); it will return a View which is your layout.

But if you call findViewById(R.id.second_View); before setContentView(), it will return null since there is not a view in your activity_first.xml layout called @+id/second_View.

findViewById throws null exception when it is used on Alert Dialog widgets

Replace this:

tv7 = findViewById(R.id.tv7)
bt4 = findViewById(R.id.bt4)

With this:

tv7 = messageBoxView.findViewById(R.id.tv7)
bt4 = messageBoxView.findViewById(R.id.bt4)

You are inflating a view (the dialog) into your activity with:

val messageBoxView = LayoutInflater.from(this).inflate(R.layout.layout_dialog, null)

You then need to define tv7 and bt4 views, but they are in the view that you inflated previously. So you need to define them based on the inflated view.

findViewById() may produce NullPointerException

This is a known issue in android.support.v7.app.AppCompatActivity and it has been fixed in v24.

https://code.google.com/p/android/issues/detail?id=203345

You won't have any issues with android.support.v4.app.FragmentActivity or android.app.Activity

FindViewByID - Null Pointer Exception! [ANDROID STUDIO]

So far I understand the button with id calc_kreis doesn't exist on the "current" view and that's why findViewById returns null.

Method findViewById will only return widgets contained by the view you set on setContentView. If the button is placed on other view, your code will never work.



Related Topics



Leave a reply



Submit