LoginSignup
1
1

Android Studio: DataStore の使い方

Last updated at Posted at 2023-11-02

こちらと同じことを行いました。
【Kotlin/Android Studio】DataStoreの使い方!データの保存と取得方法

Preferences DataStore を使うサンプルです。

プロジェクトの作成

プロジェクト名: datastore01

環境

app/build.gradle.kts
(省略)
dependencies {
(省略)
    implementation("androidx.datastore:datastore-preferences:1.0.0")
}

画面

layer/activity_main.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="409dp"
        android:layout_height="729dp"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp">

        <TextView
            android:id="@+id/activity_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Counter"
        android:textSize="50sp" />

        <Button
            android:id="@+id/add_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add"
            android:textSize="50sp" />
        <Button
            android:id="@+id/get_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Get"
            android:textSize="50sp" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

プログラム

MainActivity.kt
package com.example.datastore01

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.IOException

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

                val addButton:Button = findViewById(R.id.add_button)
        val getButton:Button = findViewById(R.id.get_button)

        addButton.setOnClickListener{
            GlobalScope.launch (Dispatchers.IO) {
                incrementCounter()
            }
        }
        getButton.setOnClickListener{
            runBlocking {
                getCounter()
            }
        }

    }

     suspend fun incrementCounter() {
        applicationContext.dataStore.edit { settings ->
            val currentCounterValue = settings[EXAMPLE_COUNTER] ?: 0
            settings[EXAMPLE_COUNTER] = currentCounterValue + 1
        }
    }


        suspend fun getCounter() {
        val text:TextView = findViewById(R.id.activity_text)
        val exampleCounterFlow: Flow<Int> = dataStore.data
            .catch { exception ->
                if (exception is IOException) {
                    emit(emptyPreferences())
                } else {
                    throw exception
                }
            }
            .map { preferences ->
                preferences[EXAMPLE_COUNTER] ?: 0
            }

        text.text = exampleCounterFlow.first().toString()
    }
}

実行結果

image.png

実機動作確認

Android 8.1.0 で動作することを確認しました。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1