標籤:
Android SharedPreferences一般用於輕量級的資料存放區,比如使用者名稱和密碼等。
1 package com.lixu.testsharepreferences; 2 3 import android.app.Activity; 4 import android.content.Context; 5 import android.content.SharedPreferences; 6 import android.content.SharedPreferences.Editor; 7 import android.os.Bundle; 8 import android.widget.Toast; 9 10 public class MainActivity extends Activity {11 12 private static final String USER_NAME = "username";13 private static final String USER_PWS = "userpws";14 private String NAME = "name";15 16 @Override17 protected void onCreate(Bundle savedInstanceState) {18 super.onCreate(savedInstanceState);19 setContentView(R.layout.activity_main);20 writeSharedPreferences();21 readSharedPreferences();22 23 }24 25 // Context.MODE_PRIVATE 這個是設定存取權限 意思是只有本app可以讀寫裡面的資料26 // 如果SharedPreferences裡面沒有寫入資料 就返回"無值";27 private void readSharedPreferences() {28 SharedPreferences sp = this.getSharedPreferences(NAME, Context.MODE_PRIVATE);29 30 String str1 = sp.getString(USER_NAME, "無值");31 String str2 = sp.getString(USER_PWS, "無值");32 33 Toast.makeText(getApplicationContext(), "使用者名稱是:" + str1, 1).show();34 35 Toast.makeText(getApplicationContext(), "使用者密碼是:" + str2, 1).show();36 37 }38 39 private void writeSharedPreferences() {40 SharedPreferences sp = this.getSharedPreferences(NAME, Context.MODE_PRIVATE);41 42 Editor edt = sp.edit();43 edt.putString(USER_NAME, "lixu");44 edt.putString(USER_PWS, "123456789");45 // 提交46 edt.commit();47 48 }49 50 }
運行效果:
Android SharedPreferences一般的讀寫 的用法。