Android-SharedPreferences,sharedpreferences

來源:互聯網
上載者:User

Android-SharedPreferences,sharedpreferences

[返回目錄]

SharedPreferences提供一種按“Key=value”的形式進行資料存放區

android.content.SharedPreferences借口所儲存的資訊只能是一些基本的資料類型,如字串,整形,布爾型等

SharedPreferences儲存的是設定檔,檔案尾碼預設為 *.xml,跟Java中的Properties類一樣(只能儲存基本的資料類型)

不能儲存中文,中文需要轉碼

預設情況下,所有設定檔都儲存在系統檔案夾中,/data/data/包名/shared prefs下

Window->show View->Others->File Explorer可以查看系統檔案夾


如:

<span style="font-family:SimHei;font-size:18px;">package com.example.testsharedpreferences;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;public class MainActivity extends Activity {private final String FILENAME="potato"; //儲存檔案名稱,最後產生potato.xml檔案@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);SharedPreferences sharedPreferences=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);SharedPreferences.Editor edit=sharedPreferences.edit();edit.putString("name", "potato");edit.putInt("age", 22);edit.putBoolean("isStudent", true);edit.commit();}}</span>

在系統檔案夾中的/data/data/ com.example.testsharedpreferences/shared prefs下會增加一個 potato.xml檔案

其中,SharedPreferences中儲存資料是通過SharedPreferences.Editor介面進行的


讀取SharedPreferences的資料方法如下:

<span style="font-family:SimHei;font-size:18px;">package com.example.testsharedpreferences;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.util.Log;public class MainActivity extends Activity {private final String FILENAME="potato"; //儲存檔案名稱,最後產生potato.xml檔案@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);SharedPreferences sharedPreferences=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);Log.e("Potato", "Name:"+sharedPreferences.getString("name", "我是預設值"));Log.e("Potato", "Age:"+sharedPreferences.getInt("age", 1));Log.e("Potato", "isStudent:"+sharedPreferences.getBoolean("isStudent", false));}}</span>





對於安卓的sharedpreferences的問題

刪除xml檔案不能徹底刪除SharedPreferences。具體可以看android的源碼,這個東西是靜態,只要沒有被回收,還是能在緩衝中讀出原來的資料。
徹底刪除的辦法是:用editor的clear並且要commit。不能這麼暴力的…………
 
android SharedPreferences的封裝

這裡我幫你簡單的封裝了一下。blog.csdn.net/...542944 只封裝了string和int類型,其他類型同理。你可以看一下。。。。一定要設滿意答案呀。寫了好一會呢。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.