본문 바로가기

안드로이드

[Android/ Kotlin] DataBinding, Hilt, DataStore 사용하기.

728x90

 

Hilt, DataStore ,DataBinding 을 사용하여 아이디 비밀번호를 저장하는 예제입니다. 

 

HiltAndroidApp 

@HiltAndroidApp
class App : Application()

 

 

Repository 

interface DataStoreRepository {

    suspend fun getCheckBox(key: String): Boolean?
    fun login()
    suspend fun buttonClickListener(id: String, password: String, check: Boolean)
}

 

Domain 

 

class SaveDataStore @Inject constructor(private val context: Context) : DataStoreRepository {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name =  "autoLogin")


    override suspend fun getCheckBox(key: String): Boolean? {
        return try {
            val preferencesKey = booleanPreferencesKey(key)
            val preferences = context.dataStore.data.first()
            preferences[preferencesKey]?: false
        }catch (e: Exception){
            e.printStackTrace()
            null
        }
    }

    override fun login() {
        val intent = Intent(context, MainActivity::class.java)
        intent.flags = FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    override suspend fun buttonClickListener(Id: String, Password: String, Check: Boolean) {
            putID("ID",Id)
            putPassword("Password",Password)
            if (Check) putCheckBox("check" , true) else putCheckBox("check", false)
            login()

    }
}

 

 

ViewModel

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: DataStoreRepository) : ViewModel(){

    var checkBox =MutableLiveData<Boolean>()

    init {
        if (getCheckBox()==true){
            repository.login()
        }else{
            checkBox.value = false
        }
    }


    fun checkValue() {
        checkBox.value = checkBox.value != true
    }

    fun getCheckBox(): Boolean? = runBlocking {
        repository.getCheckBox("check")
    }

     fun login() {
        repository.login()
    }

    fun buttonClickListener(textId: String, textPassword: String){
        viewModelScope.launch {
            repository.buttonClickListener(textId, textPassword,  checkBox.value?: false)
        }
    }
}

 

Activity

@AndroidEntryPoint
class LoginActivity : AppCompatActivity() {

    private lateinit var binding : ActivityLoginBinding
    private val viewModel: LoginViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.lifecycleOwner = this
        binding.activity = this
        binding.viewModel = viewModel


    }

    fun loginApp(view : View){
        if (binding.editTextID.text.toString().isEmpty() || binding.editTextPassword.text.toString().isEmpty()) {
            Toast.makeText(this, "아이디와 비밀번호를 확인해주세요.", Toast.LENGTH_SHORT).show()
            return
        } else {
            viewModel.buttonClickListener(binding.editTextID.text.toString(),binding.editTextPassword.text.toString())
        }
    }
}

 

layout.xml

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="viewModel"
            type="com.example.obbliapp.viewModel.LoginViewModel" />

        <variable
            name="activity"
            type="com.example.obbliapp.ui.login.LoginActivity" />
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        tools:context=".ui.login.LoginActivity">
        <ImageView
            android:id="@+id/logoImage"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/music_logo"
           />
        <EditText
            android:id="@+id/editTextID"
            android:hint="아이디를 입력해주세요."
            android:layout_margin="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/editTextPassword"
            android:hint="비밀번호를 입력해주세요."
            android:layout_margin="5dp"
            android:inputType="textPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
        <CheckBox
            android:id="@+id/checkbox"
            android:gravity="center_vertical"
            android:onClick="@{() -> viewModel.checkValue()}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="자동 로그인"/>
        <Button
            android:id="@+id/buttonLogin"
            android:text="Login"
            android:onClick="@{activity::loginApp}"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

   

    </LinearLayout>
</layout>