简体   繁体   English

Android应用程序进程重新启动时如何保留应用程序EditText数据

[英]How to retain app EditText data when Android app process restarts

When we deny any permission in the settings page while our app is alive.当我们在应用程序运行时拒绝设置页面中的任何权限时。 Android kills our app. Android 杀死了我们的应用程序。 And re-create everything (fragments and activities).并重新创建一切(片段和活动)。 viewModel is also cleared. viewModel 也被清除。 This cause the typed text in any edit text field gets cleared.这会导致在任何编辑文本字段中键入的文本被清除。 FYI, While creating the fragment, the savedInstanceState will be non-null.仅供参考,在创建片段时,savedInstanceState 将是非空的。 But i see in some apps, like Gmail, Maps, the form data is retained while process restart.但是我在某些应用程序中看到,例如 Gmail、地图,在进程重新启动时会保留表单数据。 Can anyone please explain how to retain the edit text data while process recreate?谁能解释在重新创建过程时如何保留编辑文本数据?

You can retain ViewModel data using SavedStateHandle .您可以使用SavedStateHandle保留ViewModel数据。

class MyViewModel(private val state: SavedStateHandle) : ViewModel() { ... }

SavedStateHandle is a key-value map where you can save your EditText content. SavedStateHandle是一个键值映射,您可以在其中保存您的EditText内容。 The value will persist even after the process is killed by the System.即使进程被系统杀死,该值仍将保持不变。 You can retrieve the value using the same key.您可以使用相同的键检索值。

To set the value:要设置值:

savedStateHandle["text"] = text

and retrieve it back simply use the below statement:并将其取回只需使用以下语句:

savedStateHandle["text"]
override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    // store your data
    outState.putString("some code", "111")
    outState.putString("some code1", "222")
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // read your data
    savedInstanceState.getString("some code")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android:当系统重新启动我的App流程时,如何保存在Application类中初始化的对象 - Android: How to save objects initialised in the Application class when the System Restarts my App Process 在Android应用中保留数据 - Retain data in android app 应用程序清除数据时如何从启动中重新启动应用程序 - How to restarts the app from splash when app clears data 应用终止后,Android中的后台数据收集器将重新启动 - Background data collector in Android restarts when App is terminated 重新打开应用程序时如何保留EditText值? - How to retain EditText value on reopening of app? 如何在Android中存储对象,以便即使重新启动应用程序也可以访问它们 - How to store Objects in Android so that they are accessible even when app restarts Sideview重新启动Android应用 - Sideview restarts Android app Android EditText:如何处理数据 - Android EditText: How to process data 单击应用程序图标打开 Android 应用程序时会重新启动 - Android app restarts when opened by clicking app icon 即使我们退出Android应用程序,如何保留以前的数据? - How to retain the previous data even if we exit the Android app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM