Android快速入门之使用SharedPreferences实现记住密码功能

SharedPreferences是Android系统提供的一种轻量级数据存储方式,其数据存储是以key-value对方式存储基本数据类型:整型、布尔型、长整型和字符串,常用来存储应用的配置信息、用户设置参数等数据量不大的数据。

SharedPreferences本身是一个接口,程序无法直接创建SharedPreferences实例,实际开发中会根据以下方法获取对应的SharedPreferences对象:

  • Context:getSharedPreferences(String name,int mode) ,获取文件名对应的SharedPreferences对象,name:对应的XML文件名称,mode:访问模式。
  • Activity: getPreferences(int mode) 只需指定mode即可,默认采用所在的类名作为xml文件的名称
  • PreferenceManager: getDefaultSharedPreferences(Context); 每个应用有一个默认的偏好文preferences.xml,使用getDefaultSharedPreferences获取。

Mode参数常用值:

  • Context.MODE_PRIVATE: SP中的数据只能被本应用程序读写。
  • Context.MODE_WORLD_READABLE: SP中的数据能被其他应用程序读,但不能写。
  • Context.MODE_WORLD_WRITEABLE: SP中的数据能被其他应用程序读、写。

SharedPreferences常用方法:

  • boolean contains(String key) 判断是否包含某个配置信息
  • SharedPreferences.Editor edit() 获得Preferences编辑的Editor对象
  • Map<String ,?>getAll() 获取所有配置信息
  • XXX getXXX(String key,XXX defValue) 从配置文件中获取对应的信息

SharedPreferences接口本身没有提供写入数据的能力,通过SharedPreferences的内部接口实现。
SharedPreferences调用edit()方法获取它对应的Editor对象,Editor提供了方法向sharedPreferences写入数据。

SharedPreferences.Editor常用方法

  • SharedPreferences.Editor clear():清空SharedPreferences中的数据。
  • SharedPreferences.Editor putXxx(String key, xxx Value)向SharedPreferences存入指定key对应的数据。
  • Boolean commit():当Editor编辑完成后,调用该方法提交修改。

存储和获取数据:

//实现数据存储
SharedPreferences sharedPreferences=getSharedPreferences("data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("stuId",strStuId);
editor.putString("stuName",strStuName);
editor.commit();

//获取数据
SharedPreferences sharedPreferences=getSharedPreferences("data", Context.MODE_PRIVATE);
String strStuId=sharedPreferences.getString("stuId","");
String strStuName=sharedPreferences.getString("stuName","");

案例:记住密码功能

布局文件:activity_shared_preferences_save.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="30dp"
    tools:contex**加粗样式**t=".SharedPreferencesSaveActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="学号:"
        android:id="@+id/txtStuId"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="75dp"
        android:layout_alignParentLeft="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="姓名:"
        android:id="@+id/txtStuName"
        android:layout_below="@+id/txtStuId"
        android:layout_alignParentStart="true"
        android:layout_marginTop="42dp"
        android:layout_alignParentLeft="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtStuId"
        android:layout_alignTop="@+id/txtStuId"
        android:layout_toEndOf="@+id/txtStuId"
        android:layout_toRightOf="@+id/txtStuId" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edtStuName"
        android:layout_below="@+id/edtStuId"
        android:layout_alignStart="@+id/edtStuId"
        android:layout_alignLeft="@+id/edtStuId" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edtStuName"
        android:layout_marginTop="5dp">
        <CheckBox
            android:id="@+id/remember_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Remember password"
            android:textSize="16sp"/>

    </LinearLayout>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"
        android:id="@+id/btnLogin"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />


</RelativeLayout>

运行代码:

public class SharedPreferencesSaveActivity extends AppCompatActivity {
   
   

    private Button btnLogin;
    private EditText edtStuId,edtStuName;
    private CheckBox rememberPass;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
   
   
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences_save);

        pref = getSharedPreferences("data", Context.MODE_PRIVATE);
        btnLogin=(Button) findViewById(R.id.btnLogin);
        edtStuId=(EditText)findViewById(R.id.edtStuId);
        edtStuName=(EditText)findViewById(R.id.edtStuName);
        rememberPass=(CheckBox)findViewById(R.id.remember_pass);

        boolean isRemember = pref.getBoolean("remember_password",false);
        if(isRemember){
   
   
            String stuId=pref.getString("stuId","");
            String stuName=pref.getString("stuName","");

            edtStuId.setText(stuId);
            edtStuName.setText(stuName);
            rememberPass.setChecked(true);
        }

        btnLogin.setOnClickListener(new View.OnClickListener() {
   
   
            @Override
            public void onClick(View v) {
   
   
                String strStuId=edtStuId.getText().toString();
                String strStuName=edtStuName.getText().toString();
                editor=pref.edit();
                if(rememberPass.isChecked()){
   
   
                    editor.putBoolean("remember_password",true);
                    editor.putString("stuId",strStuId);
                    editor.putString("stuName",strStuName);

                }else{
   
   
                    editor.clear();
                }
                editor.commit();
                Intent intent=new Intent(SharedPreferencesSaveActivity.this,MainActivity.class);
                startActivity(intent);
            }
        });
    }

}

运行结果:
在这里插入图片描述

在这里插入图片描述

读取其他的SharedPreferences,当应用程序创建的SharedPreferences指定了可被其他应用访问的权限时,该SharedPreferences中的数据可以被其他程序读取。

在应用程序中访问其他程序创建的SharedPreferences的步骤:
1、创建其他程序对应的Context;
2、调用其他应用的Context的getSharedPreferences(String name,int mode)获得相应的SharedPreferences对象;
3、如果需要写入数据,调用SharedPreferences的edit()方法获得相应的Editor即可。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章