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
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"/>
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With