SharedPreferences.Editor里的commit什么意思
时间: 2024-06-05 17:08:27 浏览: 8
SharedPreferences.Editor里的commit()方法是将当前对SharedPreferences的修改提交并写入到持久化存储中。它阻塞当前线程直到写入操作完成。相反,apply()方法将异步执行写入操作,并返回一个布尔值表示操作是否成功。一般来说,如果您需要等待写入完成才能继续执行下一行代码,就使用commit()方法。否则,使用apply()方法通常会比较好。
相关问题
sharedpreferences.Editor 这是什么类型
SharedPreferences.Editor是一个接口,用于编辑SharedPreferences中存储的数据。在Android中,我们通常通过SharedPreferences的edit()方法获取到一个SharedPreferences.Editor对象,然后使用该对象的putXXX()方法添加或修改数据,最终通过commit()或apply()方法将修改后的数据保存到SharedPreferences中。SharedPreferences.Editor接口提供了一系列用于操作SharedPreferences数据的方法,包括添加、修改、删除、清空等。因此,SharedPreferences.Editor是一个非常重要的接口,用于实现Android应用程序中的数据存储功能。
SharedPreferences.Editor editorMain;
这是在Android中创建SharedPreferences.Editor对象的代码。SharedPreferences.Editor用于修改SharedPreferences中的键值对。在使用SharedPreferences.Editor之前,需要先获取SharedPreferences对象,可以通过以下代码获取:
```
SharedPreferences sp = context.getSharedPreferences("name", Context.MODE_PRIVATE);
```
其中,name是SharedPreferences的名称,可以自定义。MODE_PRIVATE表示只有当前应用程序可以访问该SharedPreferences。
接着,通过SharedPreferences对象的edit()方法获取SharedPreferences.Editor对象:
```
SharedPreferences.Editor editor = sp.edit();
```
获取到SharedPreferences.Editor对象后,就可以使用其提供的putXXX()等方法向SharedPreferences中写入键值对,最后通过commit()方法提交修改即可:
```
editor.putString("key", "value");
editor.commit();
```
这样就成功向SharedPreferences中写入了一个键值对。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)