SharedPreferences实现保存用户名功能

1. 简介

  SharedPreferences是一种轻型的数据存储方式,通过key-value键值对的方式将数据存储在xml文件中,常用于存储简单的配置信息。

2. 使用方式

2.1 获取SharedPreferences对象

  Android中可通过以下三种方式获取SharedPreferences对象:

2.2.1 Context类中的getSharedPreferences()

  接收两个参数,第一个参数指定存储数据的文件,若指定文件不存在,则新建该文件,存放目录为"/data/data/package_name/shared_prefs/",其中package_name为包名。

  第二个参数则为操作模式,主要有两种:

  MODE_PRIVATE:私有模式,默认情况下的模式,与直接传入0作为参数效果一样,表示只有当前程序可对这个文件进行操作。

  MODE_MULTI_PROCESS:多进程模式,允许多个进程对该文件进行操作。

2.2.2 Activity类中的getPreferences()

  这个方法与上一个方法比较相似,不同之处在于它只接收一个参数,用于指定操作模式,而无需指定文件名,这个方法默认将当前Activity的类名作为存储数据的文件名。

2.2.3 PreferenceManager类中的getDefaultSharedPreferences()

  这是一个静态方法,接收一个Context参数,使用当前应用程序的包名作为存储数据的文件名。

2.2 获取SharedPreferences.Editor对象

  SharedPreferences对象本身是只可以读取而不能保存数据的,需要保存数据则要调用SharedPreferences对象的edit()方法获取一个Editor对象。

2.3 通过putXxx方法存储数据

  得到Editor对象后,则可调用它的putXxx方法添加数据,这里的Xxx指的是添加的数据类型,例如存储字符串数据则调用putString()方法。这个方法接收两个参数,第一个参数为key值,第二个参数为数据的值,即一个键值对。

2.4 提交变化

  添加或移除(remove方法)数据后,需要调用Editor对象的commit()方法将所作变化提交。

2.5 获取存储的数据

  获取已经存储的数据较为简单,直接调用SharedPreferences对象的getXxx方法即可,使用方法与Editor对象的putXxx类似。这个方法也是接收两个参数,第一个参数指定要获取的数据的key值,第二个参数指定当获取的数据不存在时所返回的默认值。

3. 范例-实现保存用户名的功能

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context="com.studying.myapplication.MainActivity">

    <!--用户名-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="用户名" />

        <EditText
            android:id="@+id/username"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4" />
    </LinearLayout>

    <!--密码-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="密码" />

        <EditText
            android:id="@+id/passward"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:inputType="textPassword" />
    </LinearLayout>

    <!--是否记住用户名-->
    <CheckBox
        android:id="@+id/remember"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="false"
        android:text="记住用户名" />

    <!--登录-->
    <Button
        android:id="@+id/login"
        android:layout_width="200dp"
        android:layout_height="35dp"
        android:text="登录"
        android:textSize="12sp" />

</LinearLayout>

活动类:

public class MainActivity extends Activity implements View.OnClickListener {

    private SharedPreferences mPref;
    private SharedPreferences.Editor mEditor;
    private EditText mUserName;
    private EditText mPassword;
    private CheckBox mIsRemember;
    private Button mLogin;

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

        init();
    }

    private void init() {
        mUserName = (EditText) findViewById(R.id.username);
        mPassword = (EditText) findViewById(R.id.passward);
        mIsRemember = (CheckBox) findViewById(R.id.remember);
        mLogin = (Button) findViewById(R.id.login);
        mLogin.setOnClickListener(this);

        mPref = getSharedPreferences("user_data", MODE_PRIVATE);
        mEditor = mPref.edit();

        //若之前曾设置过记住用户名,则读取并设置用户名
        if (mPref.getBoolean("is_remember", false)) {
            mUserName.setText(mPref.getString("user_name", ""));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                String userName = mUserName.getText().toString().trim();
                String password = mPassword.getText().toString().trim();
                //测试用账号
                if ("admin".equals(userName) && "123456".equals(password)) {
                    Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
                    //若勾选了记住用户名,则保存数据
                    if (mIsRemember.isChecked()) {
                        mEditor.putString("user_name", userName);
                        mEditor.putBoolean("is_remember", true);
                        mEditor.commit();
                    }
                } else {
                    Toast.makeText(this, "用户名或密码错误!", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
posted @ 2017-04-04 21:51  jyau  阅读(2505)  评论(3编辑  收藏  举报