Android(Kotlin)中SharedPreferences失效致程序崩溃问题排查
崩溃原因排查与修复方案
核心崩溃原因:ID不匹配导致未初始化异常
你的XML布局中EditText的ID是editTextText,但Kotlin代码里调用findViewById(R.id.edittext)时用的是edittext(小写且缺少Text后缀),这会导致lateinit var editText变量从未被正确初始化。当onResume执行editText.setText(myValue)时,会抛出UninitializedPropertyAccessException,直接引发程序崩溃。
次要问题:保存与读取的Key不一致
你定义了常量private val key = "myStoreData"用于读取数据,但在onDestroy保存时用的是"my Store Data"(带空格),这会导致后续读取不到之前保存的内容,即使崩溃修复后功能也无法正常工作。
额外优化点:生命周期选择
onDestroy并不保证一定会被系统调用(比如内存紧张时系统可能直接杀死进程),建议把保存逻辑移到onPause或onStop,这两个生命周期方法的调用更可靠。
修复后的完整代码
MainActivity.kt
class MainActivity : AppCompatActivity() { private lateinit var editText: EditText private val name = "MY_TEXT" private val key = "myStoreData" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 修正ID匹配XML中的editTextText editText = findViewById(R.id.editTextText) } override fun onResume() { super.onResume() val sharedPreferences = getSharedPreferences(name, MODE_PRIVATE) val myValue = sharedPreferences.getString(key, "") editText.setText(myValue) } // 改用onPause保证保存逻辑可靠执行 override fun onPause() { super.onPause() val sharedPreferences = getSharedPreferences(name, MODE_PRIVATE) val edit = sharedPreferences.edit() // 使用统一的key常量 edit.putString(key, editText.text.toString()) edit.apply() } }
activity_main.xml(无需修改,确认ID即可)
<EditText android:id="@+id/editTextText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="text" android:minHeight="48dp" android:text="text" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="Autofill,HardcodedText,LabelFor" />
内容的提问来源于stack exchange,提问作者iliya
相关产品推荐
相关产品推荐

