android.content.SharedPreferences.edit()

本文深入探讨了在使用SharedPreferences进行用户设置存储时遇到的问题,重点分析了由于使用了两个不同的Editor实例导致的数据无法成功保存的原因,并提供了解决方法。

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

今天在实现一个保存用户设置到SharedPreferences时,出现了一个不能将数据保存到SharedPreferences中的情况。经过仔细的分析得出:

android.content.SharedPreferences.Editor.putString(String key, String value)

android.content.SharedPreferences.Editor.commit()

这两个方法所用的editor不同所致。

错误代码如下:

SharedPreferences config_sp = getSharedPreferences("config", MODE_PRIVATE);

config_sp.edit().putString("passwd_safe", enCodeSafePasswd);
config_sp.edit().commit();

 

 

SharedPreferences.edit()方法的说明如下

/**
     * Create a new Editor for these preferences, through which you can make
     * modifications to the data in the preferences and atomically commit those
     * changes back to the SharedPreferences object.
     *
     * <p>Note that you <em>must</em> call {@link Editor#commit} to have any
     * changes you perform in the Editor actually show up in the
     * SharedPreferences.
     *
     * @return Returns a new instance of the {@link Editor} interface, allowing
     * you to modify the values in this SharedPreferences object.
     */

正如上面红色的标记所说,该方法会创建一个新的Editor对象,因此两次的Editor对象是不一样的。所以就造成了数据存储失败。

转载于:https://www.cnblogs.com/ithaibo-sit/p/4579077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值