SharedPreferences
Introducing SharedPreferences
SharedPreferences is a lightweight storage solution provided by Android. It stores data through key-value pairs. The underlying layer uses XML files to store key-value pair data. SharedPreferences will become unreliable during concurrent read/write. , Data may be lost when high concurrency.
SharedPreferences information writing
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 information read
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+"");