Android中的SharedPreferences儲存資料方式 .

來源:互聯網
上載者:User

 

1.概述。SharePreferences是用來儲存一些簡單配置資訊的一種機制,使用Map資料結構來儲存資料,以索引值對的方式儲存,採用了XML格式將資料存放區到裝置中。例如儲存登入使用者的使用者名稱和密碼。只能在同一個包內使用,不能在不同的包之間使用,其實也就是說只能在建立它的應用中使用,其他應用無法使用。

建立的隱藏檔儲存在/data/data/<package name>/shares_prefs檔案夾下。

 

 

2.使用。
通過Context.getSharedPreferences方法擷取SharedPreferences對象,參數分別為儲存的檔案名稱和儲存模式。

view plaincopy to clipboardprint?
  1. // 擷取SharedPreferences對象   
  2. SharedPreferences sp = getSharedPreferences(DATABASE, Activity.MODE_PRIVATE);  
  3. // 擷取Editor對象   
  4. Editor editor = sp.edit();  

 

3.操作。SharePreferences儲存資料是通過擷取Editor編輯器對象來操作的。
插入資料:
調用Editor.putxxxx方法,兩個參數分別為鍵和值。
擷取資料:
調用Editor.getxxxx方法,兩個參數分別為鍵和不存在指定鍵時的預設值。
刪除資料:
調用Editor.remove方法,參數為指定的鍵。
清空所有資料:
調用Editor.clear方法
上述所有方法調用都要執行Editor.commit方法來提交。

 

下面通過對資料的增刪改查來示範下SharePreferences的使用。

完整程式:android_sharedpreferences.rar

view plaincopy to clipboardprint?
  1. /** 
  2.  * MainActivity 
  3.  *  
  4.  * @author zuolongsnail 
  5.  */  
  6. public class MainActivity extends Activity {  
  7.     private EditText keyET;  
  8.     private EditText valueET;  
  9.     private Button insertBtn;  
  10.     private Button deleteBtn;  
  11.     private Button modifyBtn;  
  12.     private Button queryBtn;  
  13.     private Button clearBtn;  
  14.     private TextView textView;  
  15.     /** 儲存的檔案名稱 */  
  16.     public static final String DATABASE = "Database";  
  17.     /** 儲存後的檔案路徑:/data/data/<package name>/shares_prefs + 檔案名稱.xml */  
  18.     public static final String PATH = "/data/data/code.sharedpreferences/shared_prefs/Database.xml";  
  19.   
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.main);  
  24.         keyET = (EditText) findViewById(R.id.key);  
  25.         valueET = (EditText) findViewById(R.id.value);  
  26.         insertBtn = (Button) findViewById(R.id.insert);  
  27.         deleteBtn = (Button) findViewById(R.id.delete);  
  28.         modifyBtn = (Button) findViewById(R.id.modify);  
  29.         queryBtn = (Button) findViewById(R.id.query);  
  30.         clearBtn = (Button) findViewById(R.id.clear);  
  31.         // 用於顯示隱藏檔中資料
      
  32.         textView = (TextView) findViewById(R.id.content);  
  33.         insertBtn.setOnClickListener(new OperateOnClickListener());  
  34.         deleteBtn.setOnClickListener(new OperateOnClickListener());  
  35.         modifyBtn.setOnClickListener(new OperateOnClickListener());  
  36.         queryBtn.setOnClickListener(new OperateOnClickListener());  
  37.         clearBtn.setOnClickListener(new OperateOnClickListener());  
  38.     }  
  39.   
  40.     class OperateOnClickListener implements OnClickListener {  
  41.         @Override  
  42.         public void onClick(View v) {  
  43.             // 擷取SharedPreferences對象
      
  44.             SharedPreferences sp = getSharedPreferences(DATABASE,  
  45.                     Activity.MODE_PRIVATE);  
  46.             // 擷取Editor對象   
  47.             Editor editor = sp.edit();  
  48.             //  擷取介面中的資訊   
  49.             String key = keyET.getText().toString();  
  50.             String value = valueET.getText().toString();  
  51.             switch (v.getId()) {  
  52.             // 插入資料   
  53.             case R.id.insert:  
  54.                 editor.putString(key, value);  
  55.                 editor.commit();  
  56.                 textView.setText(MainActivity.this.print());  
  57.                 break;  
  58.             // 刪除資料   
  59.             case R.id.delete:  
  60.                 editor.remove(key);  
  61.                 editor.commit();  
  62.                 textView.setText(MainActivity.this.print());  
  63.                 break;  
  64.             // 修改資料   
  65.             case R.id.modify:  
  66.                 editor.putString(key, value);  
  67.                 editor.commit();  
  68.                 textView.setText(MainActivity.this.print());  
  69.                 break;  
  70.             // 查詢資料   
  71.             case R.id.query:  
  72.                 String result = sp.getString(key, "");  
  73.                 textView.setText("key=" + key + ",value=" + result);  
  74.                 break;  
  75.             // 清空所有資料   
  76.             case R.id.clear:  
  77.                 editor.clear();  
  78.                 editor.commit();  
  79.                 textView.setText(MainActivity.this.print());  
  80.                 break;  
  81.             }  
  82.   
  83.         }  
  84.     }  
  85.   
  86.     /** 擷取隱藏檔的資料 */  
  87.     private String print() {  
  88.         StringBuffer buff = new StringBuffer();  
  89.         try {  
  90.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
  91.                     new FileInputStream(PATH)));  
  92.             String str;  
  93.             while ((str = reader.readLine()) != null) {  
  94.                 buff.append(str + "/n");  
  95.             }  
  96.         } catch (Exception e) {  
  97.             e.printStackTrace();  
  98.         }  
  99.         return buff.toString();  
  100.     }  
  101. }  

程式: 

下面提供一個SharedPreferences工具類,在開發中直接調用即可。

view plaincopy to clipboardprint?
  1. /** 
  2.  * SharedPreferences儲存資料方式工具類 
  3.  * @author zuolongsnail 
  4.  */  
  5. public class SharedPrefsUtil {  
  6.     public final static String SETTING = "Setting";  
  7.     public static void putValue(Context context,String key, int value) {  
  8.          Editor sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE).edit();  
  9.          sp.putInt(key, value);  
  10.          sp.commit();  
  11.     }  
  12.     public static int getValue(Context context,String key, int defValue) {  
  13.         SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);  
  14.         int value = sp.getInt(key, defValue);  
  15.         return value;  
  16.     }  
  17.     public static boolean getValue(Context context,String key, boolean defValue) {  
  18.         SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);  
  19.         boolean value = sp.getBoolean(key, defValue);  
  20.         return value;  
  21.     }  
  22.     public static String getValue(Context context,String key, String defValue) {  
  23.         SharedPreferences sp =  context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);  
  24.         String value = sp.getString(key, defValue);  
  25.         return value;  
  26.     }  
  27. }  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.