View

ViewBinding(실제 에러 사례)

제롱구리 2024. 3. 20. 01:00
728x90

오늘 알아 볼 것

저번에 ViewBinding에 대해서 글을 포스트 했었는데
그 포스트 내용 중 NullPointException에 대한 이야기가 있었다.
그런 오늘 진짜 딱 맞는 사례가 생겨서
글을 추가로 포스트하게 되었다. 생각났을 때 바로바로!!

문제의 코드

[Activity 코드]

class SignInActivity : AppCompatActivity() {
    val etId = findViewById<EditText>(R.id.et_id)
    val etPw = findViewById<EditText>(R.id.et_pw)
    val btnLogin = findViewById<Button>(R.id.btn_login)
    val btnSignin = findViewById<Button>(R.id.btn_signin)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_signin)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        initListener()
    }
    private fun initListener(){
        btnLogin.setOnClickListener {
            if(!etId.text.isNullOrEmpty() && !etPw.text.isNullOrEmpty()){
                Toast.makeText(this, "로그인 성공", Toast.LENGTH_SHORT).show()
                val intent = Intent(this, HomeActivity::class.java)
                intent.putExtra("id",etId.text)
                intent.putExtra("pw",etPw.text)
                startActivity(intent)
            }else{
                Toast.makeText(this, "아아디/비밀번호를 확인해주세요", Toast.LENGTH_SHORT).show()
            }
        }
        btnSignin.setOnClickListener {
            val intent = Intent(this, SignUpActivity::class.java)
            startActivity(intent)
        }
    }


}

\[xml 코드]
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/signin"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SignInActivity">

    <ImageView
        android:id="@+id/iv_loggo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:src="@drawable/orrn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_id_tag"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="50dp"
        android:text="@string/strName"
        android:textSize="20dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/iv_loggo" />

    <EditText
        android:id="@+id/et_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginEnd="50dp"
        android:hint="@string/strIdHint"
        android:textSize="17dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_id_tag" />

    <TextView
        android:id="@+id/tv_pw_tag"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="50dp"
        android:text="@string/strPw"
        android:textSize="20dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/et_id" />

    <EditText
        android:id="@+id/et_pw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginEnd="50dp"
        android:hint="@string/strPwHint"
        android:inputType="textPassword"
        android:textSize="17dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_pw_tag" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="50dp"
        android:layout_marginEnd="50dp"
        android:text="@string/strLogin"
        android:textSize="17dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/et_pw" />

    <Button
        android:id="@+id/btn_signin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="50dp"
        android:text="@string/strSignin"
        android:textSize="17dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_login" />
</androidx.constraintlayout.widget.ConstraintLayout>

자 해당 코드를 설명하겠다. 해당 코드에서 주의해서 봐야 될 부분을 Activity이다. xml의 경우는 이해를 돕기위해서 작성한 코드이다.
해당 코드를 실행하게 되면 아래 사진과 같은 에러가 뜬다.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.bootclogin/com.example.bootclogin.SignInActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

이런 추가적으로 아래로 더 내려가 보면 아래 사진처럼 해당 NullPointException 이라는 곳이 보인다.


그리고 맨아래 줄인 아래 글을 클릭해서 따라 가게 되면

at com.example.bootclogin.SignInActivity.<init>(SignInActivity.kt:14)

아래 사진처럼 오류가 난 곳으로 이동하게 된다.

이게 무슨 오류냐면 해당 변수의 값이 Null이라는 것이다. 이게 무슨 소리일까?
눈치가 빠른분이라면 눈치 채셨을거 같지만(나도 바보같은 짓을 했넹...)
바로 onCreate 되기 전에 변수에 해당 Editext 값이 할당시키려고하니 Null이 뜨게 된것이다.

즉 아직 해당 액티비티의 xml 객체화도 하지 않았는데 변수부터 할당 시키니 당연히 Null이라고 한거다...

바보같넹..이런 실수를 하다니... 구지 변명을 하자면...
오랫만에 findViewbyId를 쓰다보니....
하두 ViewBinding에 적응되어서 그렇다.
ViewBinding을 하게되면 선언부에 보통 binding을 선언만 해두고 onCreate에서 바인딩을 할당하게 되는데 순간적으로 아무생각없이 이부분이 onCreate에서 할당된다는 것을 잊었기 때문이다. 헤헤 ㅇㅅㅇ;;


아무튼 이번에 이 실수를 하고 바로 생각났던 부분이 저번 포스트에서 ViewBinding을 쓰는 이유 중에 NullPointException을 방지 할 수 있다 였는데 이번 이 상황이 정말 딱 맞아 떨어지는 것 같아서 오늘의 글을 포스트하게 되었다.

추가적으로 그러므로 ViewBinding을 쓰자!!! ㅋㅋㅋ

'TIL > 스터디' 카테고리의 다른 글

Jetpack Navigation (safe args)  (0) 2024.03.22
Constraintlayout Chain  (0) 2024.03.21
안드로이드 단일 아키텍처  (0) 2024.03.19
ViewBinding  (0) 2024.03.18
RoomDB(2편)  (0) 2024.03.14
Share Link
reply
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28