android - 寻找持久化用户数据的方法
问题描述
我需要我的用户能够在“设置”片段中输入 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 开发新手,似乎无法通过这些错综复杂的事物
解决方案
我不知道你在用你的 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
}
推荐阅读
- sql - SQL:在分组之前排序(或加入替代)而不重复子查询
- r - 更新自定义 R 包数据
- ruby-on-rails - RoR 关联:has_one + has_many depedent: :destroy
- javascript - 如何将反应挂钩中的所有状态变量传递给我的子组件
- java - 为什么最后一个 else 语句没有在这里打印/执行?
- wordpress - 在小部件区域 wordpress 中拖动后小部件内容隐藏
- javascript - 尝试使用 CSS flex 让大画布溢出滚动条
- marklogic - 是否可以将数据从 SQL 导入 MarkLogic
- postgresql - PostgreSQL创建两个字段不能重复的字段
- python - Python/Flask - 如何在响应中返回有效的 JSON 而不是字符串?