首页 > 解决方案 > 寻找持久化用户数据的方法

问题描述

我需要我的用户能够在“设置”片段中输入 API 密钥,并且我需要在其他各种地方使用这个 API 密钥,例如其他片段、活动、工人。

到目前为止,我的理解是 getSharedPreferences 就是为这种目的而设计的,就像 iOS 下的 NSUserDefaults 一样:在某处保存某些东西,在其他地方获取它。

然而我似乎无法让 getSharedPreferences 工作,我已经用 MainActivity.context 在整个应用程序中初始化了它,但它总是丢失数据(API密钥)

我正在使用 ModelPreferencesManager https://gist.github.com/malwinder-s/bf2292bcdda73d7076fc080c03724e8a

我有一个 ApplicationState 类,如下所示:

public class ApplicationState : Application() {
    companion object {
        // ...
        lateinit var mContext: Context
        var api_key : String = "undefined"
        // ...
    }
        fun save(){
            Log.e("ApplicationState", "save")
            ModelPreferencesManager.with(mContext)
            ModelPreferencesManager.put(api_key , key: "api_key_identifier")
        }

        fun load(){
            Log.e("ApplicationState", "load")
            ModelPreferencesManager.with(mContext)
            api_key = ModelPreferencesManager.get<String>(key: "api_key_identifier") ?: "not read"
        }
}

首先,我将应用程序上下文存储在第一个 Activity 上(在其他任何事情之前):

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
        ApplicationState.mContext = applicationContext
        // ...
    }
}

我现在希望能够按如下方式保存 api_key:

ApplicationState.api_key = "blablah" // from some input in a random fragment
ApplicationState.save()

稍后加载:

ApplicationState.load()
var api_key = ApplicationState.api_key // in some activity or random fragment or worker

但是它不会产生预期的结果,api_key 没有保存(或加载?无法弄清楚)

我也尝试过使用 JSON 文件,但仍然没有运气,看起来它要么不写/不读,要么因为某种原因被删除。

我可以向更有经验的人伸出援助之手,因为我是 Android 开发新手,似乎无法通过这些错综复杂的事物

标签: androidkotlin

解决方案


我不知道你在用你的 ModelPreferencesManager 做什么。

但这是在偏好中保存某些内容的标准方法。

    val sharedPref = requireContext().getSharedPreferences(keyPrefIdentifier, 
    Context.MODE_PRIVATE) //get shared preferences
    val editor = sharedPref.edit() //make modifications to shared preferences
    editor.putString("userApiKeyIdent", "theActualKey")
    editor.apply() //save shared preferences persitent.

这就是你再次阅读它们的方式。

    val sharedPref = requireContext().getSharedPreferences(keyPrefIdentifier, 
    Context.MODE_PRIVATE)
    val apiKey = sharedPref.getString("userApiKeyIdent", "defaultValue")

编辑:您将 api 密钥保存为首选项的标识符。但将其作为“api key”

它应该看起来像这样

    fun save(){
        Log.e("ApplicationState", "save")
        ModelPreferencesManager.with(mContext)
        ModelPreferencesManager.put("api_key ", api_key) //like this
    }

推荐阅读