SharedPreferences基础
見歸檔項(xiàng)目:SharedPreferencesDemo.zip
1、對于數(shù)據(jù)量較小,且有明顯的K-V形式的數(shù)據(jù)而言,適合用SharedPreferences保存。SharedPreferences的數(shù)據(jù)以xml文件的形式保存在/data/data/包名/SharedPreferences的目錄下,如下例:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map><string name="hi3">liaoliuqing</string><string name="hi">liaoliuqing</string><string name="name">liaoliuqing</string> </map>
2、寫入SharedPreferences數(shù)據(jù)的基本步驟
(1)獲取SharedPreferences實(shí)例
(2)通過SharedPreferences的實(shí)例獲取Editor實(shí)例。注:SharedPreferences本身并沒有提供寫入數(shù)據(jù)的能力,而是通過其內(nèi)部類SharedPreferences.Editor來實(shí)現(xiàn)。
(3)調(diào)用Editor的write方法,切記后面還要commit。
3、讀取SharedPreferences數(shù)據(jù)的基本步驟
(1)獲取SharedPreferences實(shí)例
(2)讀取單一數(shù)據(jù):調(diào)用SharedPreferences的getXxx()方法,分別讀取String,int,long等類型。
(3)讀取全量數(shù)據(jù):調(diào)用SharedPreferences的getAll()方法,再遍歷map。
實(shí)例:
圖形界面如下
package com.ljh.sharepreferencedemo;import java.util.Map; import java.util.Map.Entry;import android.os.Bundle; import android.app.Activity; import android.content.SharedPreferences; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final EditText etKey = (EditText) findViewById(R.id.et_key);final EditText etValue = (EditText) findViewById(R.id.et_value);Button btRead = (Button) findViewById(R.id.bt_read);Button btWrite = (Button) findViewById(R.id.bt_write);final TextView tvContent = (TextView) findViewById(R.id.tv_content);//1、獲取SharedPreferences對象。SharedPreferences是一個接口,程序無法直接創(chuàng)建SharedPreferences對象,只能通過Context提供的getSharedPreferences()方法。final SharedPreferences preference = getSharedPreferences("test", MODE_PRIVATE);//2、獲取SharedPreferences。Editor對象,用于寫數(shù)據(jù)。本步驟只對寫數(shù)據(jù)有必要。final SharedPreferences.Editor editor = preference.edit();btWrite.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {String key = etKey.getText().toString().trim();String value = etValue.getText().toString().trim();//3、寫入數(shù)據(jù)并commit。editor.putString(key, value);editor.commit();}});btRead.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {//2、根據(jù)key值讀取單一數(shù)據(jù) /* String content = preference.getString("name", "lujinhong");tvContent.setText(content);*///2、讀取所有數(shù)據(jù)String content = "";Map<String, ?> allContent = preference.getAll();//注意遍歷map的方法for(Map.Entry<String, ?> entry : allContent.entrySet()){content+=(entry.getKey()+entry.getValue());}tvContent.setText(content);}});}}
總結(jié)
以上是生活随笔為你收集整理的SharedPreferences基础的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 菜单之二:使用xml文件定义菜单
- 下一篇: 使用SQLiteHelper创建数据库并