Android本地存儲SharedPreferences詳解
Android本地存儲SharedPreferences詳解
存儲位置
SharedPreferences數(shù)據(jù)保存在: /data /data/<package_name> /shared_prefs 文件夾下,以XML格式保存,根元素為:<map />。文件名稱為獲取SharedPreferences實例時傳遞的參數(shù)值。
<map> <int name="key" value="value" /> <string name="key" > value </string> </map>
獲取實例
SharePerferences是一個接口,Context實現(xiàn)了API:getSharedPreferences(String, int);這個API依據(jù)String返回一個SharePerferences實例。同樣的String返回的SharePerferences的實例是同樣的。此處strign指定的是存儲數(shù)據(jù)的xml文件的名稱。
Activity實現(xiàn)了getPreferences(int),這種方法就是默認使用Activity的class name作為String調(diào)用 getSharedPreferences(String, int)。
//指定該SharedPreferences數(shù)據(jù)僅僅能被本應用讀、寫。 Context.MODE_PRIVATE //指定該SharedPreferences數(shù)據(jù)也能被其它應用程序讀,但不能寫。 Context.MODE_WORLD_READABLE //指定該SharedPreferences數(shù)據(jù)也能被其它應用程序讀、寫。 Context.MODE_WORLD_WRITEABLE //文件是否存在,存在那么追加,否則新建 Context.MODE_WORLD_APPEND
讀
//推斷SharedPreferences是否包括特定key的數(shù)據(jù)。 boolean contains(String key) //獲取SharedPreferences里所有的key-value對。 Map<String,?> getAll() //獲取指定key相應的value,假設key不存在。則返回默認值defValue。 Xxx getXxx(String key, Xxx defValue)
寫
SharedPreferences接口本身未提供寫入數(shù)據(jù)的能力,而是通過其內(nèi)部接口。其調(diào)用SharedPreferences.edit() 方法就可以獲得它所相應的 SharedPreferences.Editor對象。Editor有例如以下向SharedPreferences寫入數(shù)據(jù)的方法: //清空SharedPreferences里全部數(shù)據(jù)。 Editor.clear() //向SharedPreferences里存入指定key相應的數(shù)據(jù)。 Editor.putXxx(String key, Xxx Value) //刪除SharedPreferences里指定key相應的數(shù)據(jù)項。 Editor.remove(String key) //當Editor編輯完畢后,調(diào)用該方法提交改動。 boolean Editor.commit()
讀寫其它應用的SharedPreferences
1.創(chuàng)建其它應用的相應 Context。
Context useContext =createPackageContext("package_name",Context.CONTEXT_IGNORE_SECURITY);
2.調(diào)用其它應用的 Context的 getSharedPreferences()方法獲取 SharedPreferences對象。
3.調(diào)用其它應用的 SharedPreferences.edit()方法獲得對應SharedPreferences.Editor對象。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Android編程實現(xiàn)popupwindow彈出后屏幕背景變成半透明效果
這篇文章主要介紹了Android編程實現(xiàn)popupwindow彈出后屏幕背景變成半透明效果,涉及Android設置getWindows透明度的方法,需要的朋友可以參考下2016-01-01
Android開發(fā)TextView內(nèi)的文字實現(xiàn)自動換行
這篇文章主要為大家介紹了Android開發(fā)TextView內(nèi)的文字實現(xiàn)自動換行,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
Android基于Intent實現(xiàn)Activity之間數(shù)據(jù)傳遞的方法
這篇文章主要介紹了Android基于Intent實現(xiàn)Activity之間數(shù)據(jù)傳遞的方法,結合實例形式分析了Activity之間數(shù)據(jù)傳遞操作的相關技巧,代碼備有較為詳盡的注釋,需要的朋友可以參考下2016-11-11
Android文本框搜索和清空效果實現(xiàn)代碼及簡要概述
在工作過程中可能會遇到這樣一個效果:文本框輸入為空時顯示輸入的圖標;不為空時顯示清空的圖標,此時點擊清空圖標能清空文本框內(nèi)輸入文字,感興趣的你可以了解下哦,或許對你學習android有所幫助2013-02-02
Android自定義view Path 的高級用法之搜索按鈕動畫
這篇文章主要介紹了Android自定義view Path 的高級用法之搜索按鈕動畫,需要的朋友可以參考下2017-06-06

