使用Kotlin的Android SharedPreferences

本文介绍了如何在Android应用中使用Kotlin实现SharedPreferences,用于本地数据存储。讲解了SharedPreferences的重要方法,如设置、检索、清除和删除值,并展示了Kotlin简化代码的例子,包括布局代码和MainActivity的Kotlin实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In this tutorial, we’ll learn how to implement SharedPreferences in our Android Application using Kotlin.

在本教程中,我们将学习如何使用Kotlin在Android应用程序中实现SharedPreferences。

什么是Android SharedPreferences? (What is Android SharedPreferences?)

SharedPreferences is part of the Android API since API level 1. It’s an interface that allows us to store/modify/delete data locally.

从API级别1开始,SharedPreferences就成为Android API的一部分。它是一个接口 ,允许我们在本地存储/修改/删除数据。

Generally, it is used to cache user local data such as login forms. The data is stored in the form of a key-value pair.

通常,它用于缓存用户本地数据,例如登录表单。 数据以键值对的形式存储。

You can create multiple files to hold the SharedPreferences data.

您可以创建多个文件来保存SharedPreferences数据。

共享首选项方法 (SharedPreferences Methods)

Let’s look at some important methods for SharedPreferences.

让我们看一下SharedPreferences的一些重要方法。

  • getSharedPreferences(String, int) method is used to retrieve an instance of the SharedPreferences.
    Here String is the name of the SharedPreferences file and int is the Context passed.

    getSharedPreferences(String, int)方法用于检索SharedPreferences的实例。
    这里的String是SharedPreferences文件的名称, int是传递的上下文。
  • The SharedPreferences.Editor() is used to edit values in the SharedPreferences.

    SharedPreferences.Editor()用于编辑SharedPreferences值。
  • We can call commit() or apply() to save the values in the SharedPreferences file. The commit() saves the values immediately whereas apply() saves the values asynchronously.

    我们可以调用commit()apply()将值保存在SharedPreferences文件中。 commit()立即保存值,而apply()异步保存值。

使用Kotlin的SharedPreferences设置/检索值 (SharedPreferences Setting/Retrieving Values using Kotlin)

We can set values on our SharedPreference instance using Kotlin in the following way.

我们可以通过以下方式使用Kotlin在SharedPreference实例上设置值。

val sharedPreference =  getSharedPreferences("PREFERENCE_NAME",Context.MODE_PRIVATE)
var editor = sharedPreference.edit()
editor.putString("username","Anupam")
editor.putLong("l",100L)
editor.commit()

For retrieving a value:

要获取值:

sharedPreference.getString("username","defaultName")
sharedPreference.getLong("l",1L)

The permitted types on a SharedPreference instance are:

SharedPreference实例上允许的类型为:

Kotlin代码清除和删除SharedPreferences记录 (Kotlin Code to Clear and Remove SharedPreferences Records)

We can also clear all the values or remove a particular value by calling clear() and remove(String key) methods.

我们还可以通过调用clear()remove(String key)方法清除所有值或删除特定值。

editor.clear()
editor.remove("username")

Note: Changes made to the editor after the commit or apply aren’t considered.

注意:不考虑在提交或应用之后对编辑器所做的更改。

The above way to save and retrieve values from a SharedPreference is nearly the same as we do in Java.

从SharedPreference保存和检索值的上述方法与我们在Java中几乎相同。

So where’s the magic of Kotlin?

那么Kotlin的魔力在哪里?

That’s what we’ll see next through an example android application.

这就是我们接下来通过示例android应用程序看到的内容。

Android SharedPreferences Kotlin项目结构 (Android SharedPreferences Kotlin Project Structure)

In this application, we’ll have a login screen, which allows us to save/clear the form data.

在此应用程序中,我们将有一个登录屏幕,该屏幕允许我们保存/清除表单数据。

1.布局代码 (1. Layout code)

The code for the activity_main.xml layout file is given below.

下面给出了activity_main.xml布局文件的代码。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/inUserId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:hint="User ID"
        android:inputType="number" />

    <EditText
        android:id="@+id/inPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inUserId"
        android:hint="Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inPassword"
        android:text="SAVE USER DATA" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/btnSave"
        android:text="CLEAR USER DATA" />

    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/inPassword"
        android:text="SHOW" />

    <Button
        android:id="@+id/btnShowDefault"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/btnSave"
        android:text="Show Default" />


</RelativeLayout>

2. MainActivity Kotlin代码 (2. MainActivity Kotlin Code)

The code for the MainActivity.kt Kotlin class is given below.

下面给出了MainActivity.kt Kotlin类的代码。

package com.journaldev.androidlysharedpreferences

import android.content.Context
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import com.journaldev.androidlysharedpreferences.PreferenceHelper.defaultPreference
import com.journaldev.androidlysharedpreferences.PreferenceHelper.password
import com.journaldev.androidlysharedpreferences.PreferenceHelper.userId
import com.journaldev.androidlysharedpreferences.PreferenceHelper.clearValues
import com.journaldev.androidlysharedpreferences.PreferenceHelper.customPreference

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

    val CUSTOM_PREF_NAME = "User_data"

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

        btnSave.setOnClickListener(this)
        btnClear.setOnClickListener(this)
        btnShow.setOnClickListener(this)
        btnShowDefault.setOnClickListener(this)

    }

    override fun onClick(v: View?) {
        val prefs = customPreference(this, CUSTOM_PREF_NAME)
        when (v?.id) {
            R.id.btnSave -> {
                prefs.password = inPassword.text.toString()
                prefs.userId = inUserId.text.toString().toInt()
            }
            R.id.btnClear -> {
                prefs.clearValues

            }
            R.id.btnShow -> {
                inUserId.setText(prefs.userId.toString())
                inPassword.setText(prefs.password)
            }
            R.id.btnShowDefault -> {

                val defaultPrefs = defaultPreference(this)
                inUserId.setText(defaultPrefs.userId.toString())
                inPassword.setText(defaultPrefs.password)
            }
        }
    }


}

object PreferenceHelper {

    val USER_ID = "USER_ID"
    val USER_PASSWORD = "PASSWORD"

    fun defaultPreference(context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)

    fun customPreference(context: Context, name: String): SharedPreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE)

    inline fun SharedPreferences.editMe(operation: (SharedPreferences.Editor) -> Unit) {
        val editMe = edit()
        operation(editMe)
        editMe.apply()
    }

    var SharedPreferences.userId
        get() = getInt(USER_ID, 0)
        set(value) {
            editMe {
                it.putInt(USER_ID, value)
            }
        }

    var SharedPreferences.password
        get() = getString(USER_PASSWORD, "")
        set(value) {
            editMe {
                it.putString(USER_PASSWORD, value)
            }
        }

    var SharedPreferences.clearValues
        get() = { }
        set(value) {
            editMe {
                it.clear()
            }
        }
}

Thanks to Kotlin Android Extensions, we don’t have to use findViewById for each XML view.

感谢Kotlin Android扩展,我们不必为每个XML视图使用findViewById。

In the above code, we are creating a singleton class using the object keyword.

在上面的代码中,我们使用object关键字创建一个singleton类

We are declaring an inline higher-order function named editMe(), which holds the logic for the edit operation.

我们正在声明一个名为editMe()的内联高阶函数,该函数包含编辑操作的逻辑。

We’ve created separate properties for each of the values. We are using the get and set Kotlin properties to retrieve and set the data in the shared preferences.

我们为每个值创建了单独的属性。 我们使用get和set Kotlin属性来检索和设置共享首选项中的数据。

Kotlin has reduced the code verbosity and it looks much cleaner.

Kotlin减少了代码的冗长性,并且看起来更加简洁。

Furthermore, we can make it more concise by using another Kotlin higher-order function shown below.

此外,我们可以使用下面显示的另一个Kotlin高阶函数使其更加简洁。

fun SharedPreferences.Editor.put(pair: Pair<String, Any>) {
    val key = pair.first
    val value = pair.second
    when(value) {
        is String -> putString(key, value)
        is Int -> putInt(key, value)
        is Boolean -> putBoolean(key, value)
        is Long -> putLong(key, value)
        is Float -> putFloat(key, value)
        else -> error("Only primitive types can be stored in SharedPreferences")
    }

And we do the following while setting the values:

并在设置值时执行以下操作:

var SharedPreferences.password
        get() = getString(USER_PASSWORD, "")
        set(value) {
            editMe {
                it.put(USER_PASSWORD to value)
            }
        }

This is as close as Kotlin can get you to the English Language.

这与Kotlin可以带您接近英语。

The output of the above application in action is given below.

下面给出了上面应用程序的输出。

翻译自: https://www.journaldev.com/234/android-sharedpreferences-kotlin

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值