Search code examples
androidnullpointerexceptionfindviewbyid

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource (int)' on a null object reference


I'm working with collapsing parallax, inside the coordinate layout I have an element with id:imageViewTest that is in this file: activity_company_detail.xml

<android.support.design.widget.AppBarLayout
    ...>

    <android.support.design.widget.CollapsingToolbarLayout
        ...
        >

        <ImageView
                android:id="@+id/imageViewTest"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:srcCompat="@android:color/darker_gray"
                tools:ignore="ContentDescription"/>

    <android.support.v7.widget.Toolbar
        .../>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_company_detail"/>

In fragment class I try to call this element R.id.imageViewTest through the method view.findViewById (...), this element is in the activity of this fragment, it is necessary to change it programmatically its functionality. CompanyDetailActivityFragment.java

private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
....
view = inflater.inflate(R.layout.fragment_company_detail, container, false);
ImageView  imageViewPrueba = (ImageView)view.findViewById(R.id.imageViewTest);
imageViewPrueba.setImageResource(R.mipmap.ic_logo_promo);
...
}

When trying to use this element I get the following error: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource (int)' on a null object reference`

Try with getActivity.findViewById () but I'm still in the problem

Sorry for my English.

Thanks for the help @Kiryl-Tkach.

Resolved:

In the activity: CompanyDetailActivity.java

public void setImageDrawable(){
    ImageView  imageViewPrueba = (ImageView) findViewById(R.id.imageViewPrueba);
    imageViewPrueba.setImageDrawable(...));
}

In the fragment: CompanyDetailActivityFragment.java

@Override
public View onCreateView(){
...
((CompanyDetailActivity)getActivity()).setImageDrawable();
...
}

Solution

  • You cannot do this because it is in not your fragments layout. Look at your method: view.findViewById(R.id.imageViewPrueba);. You are looking it in your view object, which has layout @layout/content_company_detail, and it doesn't know anything about its activity. All you need to do is to create method in your activity setImageResource and call it from your fragment. Just remember that your fragment only should operate its own views, and the best practise to operate with other views is to call methods of other activities and fragments.