Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView NullPointer Error

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

I have followed the step to put ImageView in an activity. How does the error happen and how to fix it? Noted that in hadis_layout, I use RecylerView. Thanks

  1. My ImageView

    <ImageView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:id="@+id/hadisView"
    android:layout_gravity="center_horizontal"
    android:layout_weight="0.36"
    android:contentDescription="Hadis"
    android:src="@drawable/hadith01arabic"/>
    
  2. My Activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hadis_layout);
    
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
    
        ImageView imageView = (ImageView) findViewById(R.id.hadisView);
        imageView.setImageResource(R.drawable.hadith01arabic);
    
    }
    
like image 576
chemat92 Avatar asked May 03 '26 15:05

chemat92


1 Answers

  • You cannot just change your recycleview Image resource from activity. to do that you have to make changes to your overwritten onBindViewHolder function at the RecycleViewAdapter class. add

    ViewHolderObject.imgResourceIdName.setImageResource(R.drawable.image_name);

    to onBindViewHolder function in RecycleViewAdapter class with relevant id of the itemView to be changed. (here imgResourceIdName is in the recycleView single_rv_item.xml resource file.)


The above error occurs when you try to set an image resource to an ImageView which isn't in the resouce_layout.xml file. that means even though you set your image resource by

imageView.setImageResource(R.drawable.hadith01arabic);
the object of imageView is null.

by doing

ImageView imageView = (ImageView)findViewById(R.id.hadisView);

you have just initialize an null imageView object variable which of ImageView data type. because findViewById(R.id.hadisView) does not points to any resource. check whether the hadisView named imageView resource presents in the relevant resource.xml file first.

like image 81
Tharusha Avatar answered May 05 '26 05:05

Tharusha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!