SharedPreferences
- 介紹SharedPreferences
- SharedPreferences資訊撰寫
- SharedPreferences資訊讀取
- 效果展示
介紹SharedPreferences
SharedPreferences是Android提供的輕量級儲存方案,通過鍵值對(key-valuee)的方式儲存資料,底層使用XML檔案來儲存鍵值對資料,在并發的讀/寫時,SharedPreferences會變得不可靠,高并發時還可能會丟失資料,
SharedPreferences資訊撰寫
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get = (Button) findViewById(R.id.Get);
/*
* SharedPreferences的四種模式:
* 1:Context.MODE_PRIVATE:默認模式,只能在此應用使用,不能在其他應用使用
* 2:Context.MODE_APPEND:如果存在就在后面追加
* 3:Context.MODE_WORLD_READABLE
* 4:Context.MODE_WORLD_WRITEABLE
**/
Get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//實體化SharedPreferences
SharedPreferences preferences = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);//引數;名稱,模式
//使SharedPreferences為可編輯狀態
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name","FranzLiszt");
editor.putInt("age",19);
editor.commit();//提交
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
}
SharedPreferences資訊讀取
SharedPreferences preferences = getSharedPreferences("SharedPreferences", Context.MODE_PRIVATE);
String name = preferences.getString("name","");//后面是默認值
int age = preferences.getInt("age",1);
Log.d(TAG,name);
Log.d(TAG,age+"");
效果展示

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/263862.html
標籤:其他
