Skip to content

Instantly share code, notes, and snippets.

@karim-eg
Last active September 7, 2023 21:00
Show Gist options
  • Save karim-eg/99431f3e43d2581e45a70c9c5595200b to your computer and use it in GitHub Desktop.
Save karim-eg/99431f3e43d2581e45a70c9c5595200b to your computer and use it in GitHub Desktop.
Full Activity Code For Using DataStore
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.datastore.preferences.core.edit
import co.encept.datastore.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.apply {
// Get User Data If It Exists
CoroutineScope(Dispatchers.IO).launch {
getUserData()
}
// Save User Data
btnSave.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
saveUserData(
edName.text.toString(),
edEmail.text.toString()
)
}
}
// Delete Saved User Data
btnDelete.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
deleteUserData()
getUserData()
}
}
}
}
private suspend fun saveUserData(name: String, email: String) {
user.edit { usrData ->
usrData[DataStoreKeys.USER_NAME] = name
usrData[DataStoreKeys.EMAIL] = email
}
// Display Data after save:
getUserData()
}
private suspend fun getUserData() {
user.data.collect { usrData ->
val name = usrData[DataStoreKeys.USER_NAME] ?: "none"
val email = usrData[DataStoreKeys.EMAIL] ?: "none"
// Display Data On UI
runOnUiThread {
binding.apply {
userName.text = "Username: $name"
txtEmail.text = "Email: $email"
}
}
}
}
private suspend fun deleteUserData() {
user.edit { usrData ->
usrData.clear()
}
// Display Data after delete:
getUserData()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment