Android Kotlin : SharedPreferences를 이용한 자동 로그인

2022. 8. 3. 19:01[Android APP] feat. Kotlin/Kotlin 공부

개요

sharedPreferences란

- 간단하게 값을 저장하기 위해 사용하는 일종의 저장소이다.

- 토큰관리나 초기 설정값, 자동로그인 등과 같이 간단하게 값을 저장하기 위해 사용한다.

- 앱이 삭제되기 전까지 보존되기 때문에 앱을 종료하고 다시 실행시켜도 값이 저장되어 있다.

 

본문

우선 sharedProference를 사용하는 것은 매우 쉽다.

값을 저장하고 저장된 값을 빼서 쓰면 된다.

안쓰는 값들은 삭제해주면 된다.

 

1. 선언

//간단한 데이터 저장
val sharedPreference = getSharedPreferences("user_auto", MODE_PRIVATE)
val editor = sharedPreference.edit()

우선 위와 같이 데이터를 관리하기 위해 sharedPreference를 선언해준다.

 

2. 값 저장하기(putString("키 값", 저장할 값)

editor.putString("키값", 저장할 값)
editor.putString("token", login?.value?.token)

 

3. 값 적용시켜주기(apply)

값이 삭제되거나 추가되었다면 꼭 apply()를 시켜줘야 값 변경이 적용된다.

잊지말자!

editor.apply()

 

4. 특정 값 삭제하기 (remove)

editor.remove("token")

 

5. sharedPreference에 들어있는 모든 값 삭제하기 (clear)

editor.clear()

 

6. 값 불러와서 사용하기(sharedPreference.getString("키 값", ""))

sharedPreference.getString("키 값", "").toString()

ex) val uId = sharedPreference.getString("userId", "").toString()

 

 

 

 

일반 로그인을 할 때 자동로그인을 체크했다면

 

//간단한 데이터 저장
val sharedPreference = getSharedPreferences("user_auto", MODE_PRIVATE)
val editor = sharedPreference.edit()


//자동 로그인 체크 시
if (sharedPreference.getString("userId", "").toString().isNotEmpty() && sharedPreference.getString("userPw", "").toString().isNotEmpty()) {

    //첫 로그인 시 sharedPreference에 저장했던 아이디, 패스워드 값 불러오기
    val uId = sharedPreference.getString("userId", "").toString()
    val upw = sharedPreference.getString("userPw", "").toString()

    //로그인 API 호출(자동 로그인)
    loginService.requestLogIn(CodeList.sysCd, LoginRequestDTO(uId, upw))
        .enqueue(object : Callback<LoginDTO> {
            override fun onFailure(call: Call<LoginDTO>, t: Throwable) {
                Log.d("retrofit", t.toString())
            }

            //로그인 API 호출 성공 : 로그아웃 후, 전에 저장해놨던 userId, userPw로 재로그인
            override fun onResponse(call: Call<LoginDTO>, response: Response<LoginDTO>) {
                login = response.body()
				//안에 로그인 코드 넣어주기

            }
        })
}
//자동로그인 체크 확인(체크 시 : userId, userPw, token값 저장)
if (binding.autoLogin.isChecked) {
    editor.putString("userId", userId)
    editor.putString("userPw", passwd)
    editor.putString("token", login?.value?.token)
    editor.apply()
} else {
    editor.putString("token", login?.value?.token) //데이터 넣기
    editor.remove("userId") //userId 키를 가진 값 삭제
    editor.remove("userPw") //userPw 키를 가진 값 삭제
    editor.clear() //값 전체 삭제
    editor.apply() //적용	
}

 

잘돌아가는 전체 코드가 있지만 요런 식으로 사용하면 된다는 것만 알려주고 직접 해보길 바란다!

 

반응형