作者darkk6 (Mr. Pan)
看板AndroidDev
标题[问题] SharedPreferences 清空资料
时间Wed May 22 01:50:42 2013
大家好~ 小弟目前遇到一个问题想要厘清, Android API 写的部分不是很懂
希望大家可以帮忙:
SharedPreferences.Editor 的 clear 和 commit
API 中 clear() 的解说有提到
Note that when committing back to the preferences, the clear is done
first, regardless of whether you called clear before or after put
methods on this editor.
想厘清的点主要有两点: (因为SharedPreferences 太长底下以 SP 代替)
1. 取得 SP.Editor,假设中间只有 put 资料,然後做了 commit
请问原本 SP 里面的资料会不会被清空重写?
ex :
//第一次
SP.Editor edit=sp.edit();
edit.putString("A","DATA_1");
edit.commit();
//第二次
SP.Editor edit=sp.edit();
edit.putString("B","DATA_2");
edit.commit();
//------ 到这边,这个 SP 里面有 A 这笔资料吗? ------
// 如果还有 A 这笔资料,我要只留下B 是否就要先呼叫 clear 呢?
// PS : 不考虑用 remove
2. API doc 上面那句话的意思是不是,只要在 commit() 之前有 clear()
不论先後,都会先执行 clear 吗?
ex :
// 状况 1 - 假设这个 SP 里面目前只有一个 "C"=>"3" 的资料
SP.Editor edit=sp.edit();
edit.clear();
edit.putString("A","1");
edit.putString("B","2")
edit.commit();
// 状况 2 - SP 目前的状态同状况 1 所述
SP.Editor edit=sp.edit();
edit.putString("A","1");
edit.putString("B","2")
edit.clear();
edit.commit();
这两种状况在完成 commit 之後,
是否 SP 里面都还是会有 "A" => "1" 和 "B" => "2" 呢?
感谢大家~~
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.47.174.135
1F:→ lovelycateye:是吧? 谋哩拎跨买ㄟ嘛 05/22 11:52
2F:→ samdynasty:在1里面:A是会存在的,要clear没错 05/22 13:04
3F:→ samdynasty:在2.状况一会在,状况二你又清掉了,就什麽都没有啦!! 05/22 13:05