Sharedpreferences提供了常规的数据类型保存接口比如:int、long、boolean、String、Float、Set和Map这些数据类型。
Activity文件:
package com.example.administrator.jackapp;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class sharedPreferenceActivity extends AppCompatActivity {
private EditText et_name;
private EditText et_password;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preference);
// 通过资源id创建EditText实例
et_name = (EditText)findViewById(R.id.et_name_sp);
et_password = (EditText)findViewById(R.id.et_password_sp);
// 得到SharedPreferences对象
sp = getSharedPreferences("info_sp",MODE_PRIVATE);
// 获取name键值对的内容赋值给st_name,默认值为:""
String st_name = sp.getString("name","");
String st_password = sp.getString("password","");
// 显示在屏幕上
et_name.setText(st_name);
et_password.setText(st_password);
}
// 按键点击监视方法login
public void login(View view){
// 获取需要保存的数据
String name = et_name.getText().toString();
String password = et_password.getText().toString();
// SharedPreferences保存文件在内部存储器,不需要权限
// 得到SharedPreferences对象
// sp = getSharedPreferences("info_sp",MODE_PRIVATE);
// 获取Editor对象
SharedPreferences.Editor editor = sp.edit();
// 设置需要输入的数据
editor.putString("name",name);
editor.putString("password",password);
//提交数据
editor.commit();
}
}
layout文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".sharedPreferenceActivity">
<EditText
android:id="@+id/et_name_sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入用户名sharedPreference"
/>
<EditText
android:id="@+id/et_password_sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入密码sharedPreference"
android:inputType="textPassword"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/bt_login_sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:layout_alignParentRight="true"
android:onClick="login"/>
</RelativeLayout>
</LinearLayout>