1.SharedPreferences是什么?
SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置,通过Android系统生成一个xml文件保到:/data/data/包名/shared_prefs目录下,类似键值对的方式来存储数据。
2.如何储存数据?
SharedPreferences.Editor SP1= sp.edit();
SP1.putString("Value",meditText1.getText().toString().trim());
SP1.commit();
3.如何读取数据?
String value = sp.getString("Value","Null");
meditText2.setText(value);
4.记住密码案例
package com.example.zuoye1;
import android.content.Context;
import android.content.SharedPreferences;
import android.icu.text.BreakIterator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SPchucun extends AppCompatActivity {
private EditText meditText1 ,meditText2 ;
private Button SaveBtn,GetBtn;
//声明Sharedpreferenced对象
private SharedPreferences sp ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_preference);
meditText1= (EditText) findViewById(R.id.edit1);
meditText2 = (EditText) findViewById(R.id.edit2);
SaveBtn = (Button) findViewById(R.id.btn_Save);
GetBtn = (Button) findViewById(R.id.btn_Get);
}
public void Click(View view) {
sp = getSharedPreferences("User", Context.MODE_PRIVATE);
switch (view.getId()){
case R.id.btn_Save:
SharedPreferences.Editor SP1 = sp.edit();
SP1.putString("Value",meditText1.getText().toString().trim());
SP1.commit();
break;
case R.id.btn_Get:
String value = sp.getString("Value","Null");
meditText2.setText(value);
break;
}
}
}