1. 程式人生 > >資料儲存(五種方式)SharedPreferences儲存

資料儲存(五種方式)SharedPreferences儲存

一.SharedPreferences儲存

1.使用SharedPreferences儲存資料時,不需要指定檔案字尾,字尾自動設定為*.xml。

2.儲存資料---SaveData.java

publicclass MySharedPreferencesDemo extends Activity {

    private static final String FILENAME ="mldn"; // 儲存的檔名稱

    @Override

    public void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        super.setContentView(R.layout.main);

        SharedPreferences share = super.getSharedPreferences(FILENAME,

                Activity.MODE_PRIVATE);//指定操作的檔名稱

        SharedPreferences.Editor edit =share.edit();//編輯檔案

        edit.putString("author","LiXingHua");//儲存字串

        edit.putInt("age", 30);

        edit.commit();// 提交更新

    }

}

執行之後檔案儲存在了DDMS中,要想檢視檔案,可選擇:WindowàOpen PerspectiveàOther命令,開啟之後選擇FileExplorer\data\data\<package name>\shared_prefs\目錄就可以找到生成的檔案。找到後可以單擊DDMS工具欄中的Pull a file from the device按鈕匯出檔案。

資料的儲存必須使用commit()方法,使用該方法才可以真正的儲存所配置的資料資訊,否則資料不會儲存。

3.讀取資料:利用getXxx()方法根據key進行讀取,也可以直接通過getAll()方法將全部的資料按照Map集合的方式取出。

publicclass MySharedPreferencesDemo extends Activity {

    private static final String FILENAME ="mldn"; // 儲存的檔名稱

    private TextView authorinfo = null ;

    private TextView ageinfo = null ;

    @Override

    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        super.setContentView(R.layout.main);

        this.authorinfo = (TextView)super.findViewById(R.id.authorinfo) ;

        this.ageinfo = (TextView)super.findViewById(R.id.ageinfo) ;

        SharedPreferences share = super.getSharedPreferences(FILENAME,

                Activity.MODE_PRIVATE);//指定操作的檔名稱

        this.authorinfo.setText("作者:" +share.getString("author", "沒有作者資訊。"));

        this.ageinfo.setText("年齡:" +share.getInt("age", 0)) ;

    }

}
原文參考:Android開發實戰經典