0

In my class, I have created a variable...

private ImageView imgLayoutImgEditPet;

In the onCreate method, I reference the variable...

imgLayoutImgEditPet = new ImageView(this);

I then add this ImageView to the layout...

layoutImgEditPet.addView(imgLayoutImgEditPet);

This should work, yet I get this error...

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference

How can I instantiate a new ImageView to my layout?

Garren Fitzenreiter
  • 781
  • 1
  • 5
  • 22
  • It's not the `ImageView`. It's `layoutImgEditPet` that's null. – Mike M. Dec 18 '18 at 07:03
  • layoutImgEditPet is still referenced, but it is in tag. How would i reference the layout if it's in the include tags? – Garren Fitzenreiter Dec 18 '18 at 07:05
  • You'd `findViewById()` it just like you would any other `View`. However, if it's the root `View` in the included layout, and you've set an `android:id` on the `` tag, be aware that the ``'s ID overrides the root `View`'s ID. That is, the root `View` will end up with the ID that's on the ``. – Mike M. Dec 18 '18 at 07:08
  • ahh gotcha. i will have to reference the included layout and find its inner layout by using includedlayout.innerlayout.findViewById() – Garren Fitzenreiter Dec 18 '18 at 07:13
  • 1
    No, that's not what I'm saying. I'm just pointing out that the root `View`'s ID might not be what you expect. After it's attached to the `Activity`'s hierarchy, you can just use `findViewById()` directly, like any other `View`, no matter how nested it is, but you have to use the correct ID. – Mike M. Dec 18 '18 at 07:14
  • Oooooooh. I guess I will have to nest the linearlayout of the included layout inside another layout because the linear layout i was trying to reference is in fact the root view – Garren Fitzenreiter Dec 18 '18 at 07:47
  • That's fine. You don't have to nest it. Just use the right ID to find it. If you have an `android:id` on the `` tag, then that's the ID that the `LinearLayout` will end up with, no matter what ID you've set on the `` tag. – Mike M. Dec 18 '18 at 07:50
  • 1
    Ahh. Got it! It's working now. Thanks! – Garren Fitzenreiter Dec 18 '18 at 07:53

0 Answers0