安卓开发-SharedPreference应用实例
SharedPrefernce多用于配置文件的使用,此文用账号密码来做讲解
1、创建一个工程,并建立一个简单的UI,如图
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/qq"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="输入QQ号码"/>
<EditText
android:id="@+id/pwd"
android:inputType="textPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="输入密码"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"/>
</LinearLayout>
<Button
android:onClick="login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"/>
</LinearLayout>
2、编写核心逻辑代码:
public class MainActivity extends AppCompatActivity {
private EditText qq;
private EditText pwd;
private CheckBox checkbox;
private SharedPreferences sp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qq=(EditText)findViewById(R.id.qq);
pwd=(EditText)findViewById(R.id.pwd);
checkbox=(CheckBox)findViewById(R.id.checkbox);
sp=getSharedPreferences("config",MODE_PRIVATE);
String num=sp.getString("qq","");
String password=sp.getString("pwd","");
qq.setText(num);
pwd.setText(password);
}
//这里为登录按钮绑定的方法
public void login(View view){
String q=qq.getText().toString().trim();//使用字符串q来获取qq号码的值
String p=pwd.getText().toString().trim();
if (checkbox.isChecked()){
Editor editor=sp.edit();
editor.putString("qq",q);
editor.putString("pwd",p);
editor.apply();
}
else{
}
}
}
使用sharedpreference的步骤:
创建sharedpreference对象:
SharedPreference sp=getSharedPreferences("config",MODE_PRIVATE);//MODE_PRIVATE可以使用0代替
获取编辑器:
Editor editor=sp.edit();
写入数据:
editor.putString("qq",q);
提交:
editor.apply();//也可以使用editor.commit(),但不推荐
回显数据:
String num=sp.getString("qq","");//使用sp.getxxx来获取key为qq的数据