作者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
→ lovelycateye:是吧? 謀哩拎跨買ㄟ嘛 05/22 11:52
→ samdynasty:在1裡面:A是會存在的,要clear沒錯 05/22 13:04
→ samdynasty:在2.狀況一會在,狀況二你又清掉了,就什麼都沒有啦!! 05/22 13:05