安卓应用开发中的参数存取

在开发安卓应用中,总是需要保存设置一些参数。开始我找到用SharedPreferences的方法,但官方网站说过期了,新的要用DataStore。本文就是介绍DataStore Preference 的简单编程。

DataStore是Jetpack中的一个组件,用于做数据持久化,DataStore以异步、一致的事务方式存储数据,克服了SharedPreferences的一些缺点,DataStore基于Kotlin协程和Flow实现,就是用来取代SharedPreferences的。

DataStore 提供 2 种不同的实现:

  • Preferences DataStore
  • Proto DataStore

Preferences DataStore 比较简单,本文就只是介绍这种简单方法。

一、新建工程,添加依赖

首先在android Studio下新建一个工程,选择 Empty Active View 作为模板,名字取为 DataStore Demo。

在app模块下的build.gradle中的dependencies{}闭包中添加如下依赖:

 //Preferences DataStore
    implementation ("androidx.datastore:datastore-preferences:1.0.0")
    implementation ("androidx.datastore:datastore-preferences-core:1.0.0")

二,修改布局文件activity_main.xml

这个文件在res/layout 下面,文件的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <EditText
        android:id="@+id/number"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:text=""
        android:hint="input number"
        />

    <Button
        android:id="@+id/btn_put"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save" />

    <Button
        android:id="@+id/btn_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get" />

    <Button
        android:id="@+id/btn_clear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Clear" />


</LinearLayout>

这个文件就是界面里有3个按钮,读,写,清除,然后一个TextView 显示内容,一个EditTexty 用于输入数据。

三,代码

首先我们需要定义一个datastore 变量,然后定义2个要操作的key:

//define dataStore
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "Study")

    //定义要操作的key
    private val key = stringPreferencesKey("name")
    private val keynum = intPreferencesKey("number")

然后定义2个变量对应textview 和EditText,存取函数put, get, get2

    private lateinit var tv: TextView
    private lateinit var et:EditText

    private suspend fun put() = dataStore.edit { it[key] = "Home"
        var num:Int
        try {
            num = et.text.toString().toInt()
        }
        catch (ex: Exception)
        {
            num=2
        }
        it[keynum]=num
    }

    private fun get() = runBlocking {
        return@runBlocking dataStore.data.map { it[key] ?: "Office" }.first()
    }

    private fun get2() = runBlocking {
        return@runBlocking dataStore.data.map { it[keynum] ?: 5 }.first()
    }

然后在OnCreate 里

把TextView 和 EditText 对应好。

3个按钮的对应的按钮事件,以及里面的函数,代码如下:

        et=findViewById(R.id.number)
        tv=findViewById(R.id.textView)

        val btn_put: Button = findViewById(R.id.btn_put)
        btn_put.setOnClickListener {
            runBlocking { put() }
        }

        val btn_get: Button = findViewById(R.id.btn_get)
        btn_get.setOnClickListener {
            val data=get()
            val num=get2()
            tv.setText("$data count=$num")
        }

        val btn_clear: Button = findViewById(R.id.btn_clear)
        btn_clear.setOnClickListener {
            runBlocking { dataStore.edit { it.clear() } }
         }

代码都好了,可以开始运行测试了。

完整的代码工程在https://github.com/liwenz/datastoreDemo2

app运行的效果是:初始的时候,textview 显示 hello world

在clear 或者第一次Get 时,显示 office count=2

Save 时把home 存name中,编辑行数字存 count 中,

Get 时把 name 和count 显示在Textview 区, 比如 home count=6677

本文参考 ​​​​​​Android Jetpack组件 DataStore的使用和简单封装_android jetpack datesouce_初学者-Study的博客-CSDN博客 

参考的博文内容比较全面,封装了参数设置存取类,同时介绍了 Proto DataStore

而我的博文力求简单,容易上手。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值