DataStore

Uso de DataStore

DataStore

 

Crear un proyecto llamado DataStoreExample

build.gradle (del módulo)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
buildFeatures {
viewBinding = true
}
buildFeatures { viewBinding = true }
buildFeatures {
    viewBinding = true
}

Buscar las dependencias en la estructura del proyecto

Añadir las dependencias

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.datastore.preferences) implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.lifecycle.runtime.ktx)

colors.xml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="gold">#FFEB3B</color>
</resources>
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color> <color name="gold">#FFEB3B</color> </resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <color name="gold">#FFEB3B</color>
</resources>

UserProfile

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
data class UserProfile(val name: String, val vip: Boolean)
data class UserProfile(val name: String, val vip: Boolean)
data class UserProfile(val name: String, val vip: Boolean)

activity_main.xml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?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/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_marginBottom="45dp"
android:hint="Introduce tu nombre"
android:maxLines="1"
android:singleLine="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3" />
<CheckBox
android:id="@+id/cbVIP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="367dp"
android:text="Eres VIP?"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etName"
app:layout_constraintVertical_bias="0.4" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="272dp"
android:text="Guardar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/etName"
app:layout_constraintVertical_bias="0.46" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?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/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/etName" android:layout_width="wrap_content" android:layout_height="55dp" android:layout_marginBottom="45dp" android:hint="Introduce tu nombre" android:maxLines="1" android:singleLine="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.3" /> <CheckBox android:id="@+id/cbVIP" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="367dp" android:text="Eres VIP?" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etName" app:layout_constraintVertical_bias="0.4" /> <Button android:id="@+id/btnSave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="272dp" android:text="Guardar" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etName" app:layout_constraintVertical_bias="0.46" /> </androidx.constraintlayout.widget.ConstraintLayout>
<?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/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_marginBottom="45dp"
        android:hint="Introduce tu nombre"
        android:maxLines="1"
        android:singleLine="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.3" />

    <CheckBox
        android:id="@+id/cbVIP"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="367dp"
        android:text="Eres VIP?"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etName"
        app:layout_constraintVertical_bias="0.4" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="272dp"
        android:text="Guardar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etName"
        app:layout_constraintVertical_bias="0.46" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
val Context.dataStore by preferencesDataStore(name = "USER_PREFERENCES_NAME")
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// val btnSave = findViewById<Button>(R.id.btnSave)
// val etName = findViewById<EditText>(R.id.etName)
//val cbVIP = findViewById<CheckBox>(R.id.cbVIP)
binding.btnSave.setOnClickListener {
lifecycleScope.launch(Dispatchers.IO) {
saveValues(binding.etName.text.toString(), binding.cbVIP.isChecked)
}
val intent = Intent(this, DetailActivity::class.java)
startActivity(intent)
}
}
private suspend fun saveValues(name: String, checked: Boolean) {
dataStore.edit { preferences ->
preferences[stringPreferencesKey("name")] = name
preferences[booleanPreferencesKey("vip")] = checked
}
}
}
val Context.dataStore by preferencesDataStore(name = "USER_PREFERENCES_NAME") class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_main) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // val btnSave = findViewById<Button>(R.id.btnSave) // val etName = findViewById<EditText>(R.id.etName) //val cbVIP = findViewById<CheckBox>(R.id.cbVIP) binding.btnSave.setOnClickListener { lifecycleScope.launch(Dispatchers.IO) { saveValues(binding.etName.text.toString(), binding.cbVIP.isChecked) } val intent = Intent(this, DetailActivity::class.java) startActivity(intent) } } private suspend fun saveValues(name: String, checked: Boolean) { dataStore.edit { preferences -> preferences[stringPreferencesKey("name")] = name preferences[booleanPreferencesKey("vip")] = checked } } }
val Context.dataStore by preferencesDataStore(name = "USER_PREFERENCES_NAME")

class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // val btnSave = findViewById<Button>(R.id.btnSave)
        // val etName = findViewById<EditText>(R.id.etName)
        //val cbVIP = findViewById<CheckBox>(R.id.cbVIP)

        binding.btnSave.setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                saveValues(binding.etName.text.toString(), binding.cbVIP.isChecked)
            }
            val intent = Intent(this, DetailActivity::class.java)
            startActivity(intent)
        }
    }

    private suspend fun saveValues(name: String, checked: Boolean) {
        dataStore.edit { preferences ->
            preferences[stringPreferencesKey("name")] = name
            preferences[booleanPreferencesKey("vip")] = checked
        }
    }

}

activity_detail.xml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?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/viewBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DetailActivity">
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?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/viewBackground" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".DetailActivity"> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:textSize="26sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.5" /> </androidx.constraintlayout.widget.ConstraintLayout>
<?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/viewBackground"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DetailActivity">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="26sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

DetailActivity

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class DetailActivity : AppCompatActivity() {
lateinit var binding: ActivityDetailBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_detail)
binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
// val backgroundView = findViewById<View>(R.id.viewBackground)
// val tvName = findViewById<TextView>(R.id.tvName)
lifecycleScope.launch(Dispatchers.IO) {
getUserProfile().collect {
withContext(Dispatchers.Main) {
binding.tvName.text = it.name
if (it.vip)
binding.viewBackground.setBackgroundColor(getColor(R.color.gold))
else
binding.viewBackground.setBackgroundColor(getColor(R.color.white))
}
}
}
}
private fun getUserProfile() = dataStore.data.map { preferences ->
UserProfile(
name = preferences[stringPreferencesKey("name")].orEmpty(),
// name = preferences[stringPreferencesKey("name")] ?: ""
vip = preferences[booleanPreferencesKey("vip")] ?: false
)
}
}
class DetailActivity : AppCompatActivity() { lateinit var binding: ActivityDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(R.layout.activity_detail) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) // val backgroundView = findViewById<View>(R.id.viewBackground) // val tvName = findViewById<TextView>(R.id.tvName) lifecycleScope.launch(Dispatchers.IO) { getUserProfile().collect { withContext(Dispatchers.Main) { binding.tvName.text = it.name if (it.vip) binding.viewBackground.setBackgroundColor(getColor(R.color.gold)) else binding.viewBackground.setBackgroundColor(getColor(R.color.white)) } } } } private fun getUserProfile() = dataStore.data.map { preferences -> UserProfile( name = preferences[stringPreferencesKey("name")].orEmpty(), // name = preferences[stringPreferencesKey("name")] ?: "" vip = preferences[booleanPreferencesKey("vip")] ?: false ) } }
class DetailActivity : AppCompatActivity() {

    lateinit var binding: ActivityDetailBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // setContentView(R.layout.activity_detail)
        binding = ActivityDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // val backgroundView = findViewById<View>(R.id.viewBackground)
        // val tvName = findViewById<TextView>(R.id.tvName)

        lifecycleScope.launch(Dispatchers.IO) {
            getUserProfile().collect {
                withContext(Dispatchers.Main) {
                    binding.tvName.text = it.name
                    if (it.vip)
                        binding.viewBackground.setBackgroundColor(getColor(R.color.gold))
                    else
                        binding.viewBackground.setBackgroundColor(getColor(R.color.white))
                }
            }
        }
    }

    private fun getUserProfile() = dataStore.data.map { preferences ->
        UserProfile(
            name = preferences[stringPreferencesKey("name")].orEmpty(),
            // name = preferences[stringPreferencesKey("name")] ?: ""
            vip = preferences[booleanPreferencesKey("vip")] ?: false
        )

    }
}

 

 

Deja una respuesta