안드로이드 에러(Android_error)

java.lang.NullPointerException ~ on a null object reference 오류가 뜰때 해결 방법

이망국 2023. 8. 27. 00:16
728x90
반응형

ImageView를 다루다 보니 다음과 같은 오류가 떳었다.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setBackground(android.graphics.drawable.Drawable)' on a null object reference


ImageView 에 원하는 이미지로 나오도록 shape를 적용시키다가 불러온 이미지에는 적용이 안되었다.

 

그러하여 코드 내부에서 적용하려 다음 코드를 적용시켰고

likeUserProfile.background = resources.getDrawable(R.drawable.like_background, null)
likeUserProfile.clipToOutline = true

 그 결과 NullPointerException 오류가 떳었다.


우선 이 오류는 아주 간단하다.

말 그대로 shape를 Background로 적용할 때 like_background라는 ImageView가 null 인 상태에서 접근했기 때문이다.

 

즉, 초기화를 한번해주면 된다.

 

val likeUserProfile = likeViewHolder.findViewById<ImageView>(R.id.likeUserProfile)

findViewById를 통해 id가 likeUserProfile인 ImageView를 찾고 likeUserProfile라는 변수에 초기화를 해준다.

 

그 후 위의 코드 2줄을 넣으면 된다.

val likeUserProfile = likeViewHolder.findViewById<ImageView>(R.id.likeUserProfile)
likeUserProfile.background = resources.getDrawable(R.drawable.like_background, null)
likeUserProfile.clipToOutline = true

이런식으로하면 잘 적용된다.

728x90
반응형