Android数据存储之SharedPreferences使用

SharedPreferences是Android中一种轻型的数据存储类。本质上是基于XML文件进行存储Key-Value键值对的数据,生成的XML文件的目录在/data/data/包名/Shared_Pref/下。主要是用来存储一些简单的配置信息,如登陆时是否保存用户名密码等。html

SharedPreferences自己只能获取数据而不支持存储或修改,存储修改是经过SharedPreferences的一个内部接口Editor来实现的。java

实现SharedPreferences存储的步骤以下:android

① 获取SharedPreferences对象;数据库

② 获取SharedPreferences.Editor对象;ide

③ 经过Editor接口的putXxx方法保存K-V键值对。Xxx表示不一样的数据类型(float,int,String,boolean,long);布局

④ 使用Editor接口的commit方法进行操做的提交。this

使用SharedPreferences的过程比较简单,下面经过一个保存用户名的小案例演示一下SharedPreferences的简单使用。url

主布局文件:spa

<?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:orientation="vertical"
    tools:context=".MainActivity">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tvUsername"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="14dp"
            android:text="用户名"
            android:textSize="20dp"
            android:textAlignment="center"/>
        <EditText
            android:id="@+id/etUsername"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/Base.V7.Widget.AppCompat.EditText"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <TextView
            android:id="@+id/tvPassword"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="14dp"
            android:text="密    码"
            android:textSize="20dp"
            android:textAlignment="center"/>
        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:theme="@style/Base.V7.Widget.AppCompat.EditText"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <TextView
            android:id="@+id/tvRememberUsername"
            android:text="保存用户名"
            android:textSize="15dp"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
       <CheckBox
           android:id="@+id/cbRememberUsername"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <Button
            android:id="@+id/btnLogin"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_marginRight="15dp"
            android:layout_marginLeft="10dp"
            android:layout_height="60dp"
            android:text="登陆"
            android:textSize="20dp"/>

        <Button
            android:id="@+id/btnCancel"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:layout_marginLeft="5dp"
            android:layout_height="60dp"
            android:text="取消"
            android:textSize="20dp"/>

    </LinearLayout>
</LinearLayout>
activity_main

MainActivity.javacode

public class MainActivity extends AppCompatActivity implements View.OnClickListener { //声明控件
    private EditText etUsername, etPassword; private TextView tvUsername, tvPassword, tvSaveUsername; private CheckBox cbSaveUsername; private Button btLogin, btCancel; //声明SharedPreferences对象
    private SharedPreferences preferences; //声明Editor对象
    private SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews();//初始化控件
        /** * 经过getSharedPreferences方法获取SharedPreferences对象, * getSharedPreferences(String name,int mode) * name: 生成的XML文件的名字 * mode: 生成的XML文件的权限(是否能被其余程序读取等) * * 也能够使用PreferenceManager.getDefaultSharedPreferences(this)获取SharedPreferences对象, * 这样生成的XML文件名为: 包名+“_preferences” * XML权限为:MODE_PRIVATE */
// preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences = getSharedPreferences("myPref", MODE_PRIVATE); //获取Editor对象
        editor = preferences.edit(); //经过SharedPreferences对象的getXxx方法获取Key对应的Value,第二个参数为默认值
        String name = preferences.getString("username", ""); //若是name为空,说明还未进行过用户名的存储
        if (name == null) { cbSaveUsername.setChecked(false); } else {//若是不为空则将已存储的用户名自动填写到编辑框中
            cbSaveUsername.setChecked(true); etUsername.setText(name); } } //初始化控件
    private void initViews() { etUsername = (EditText) findViewById(R.id.etUsername); etPassword = (EditText) findViewById(R.id.etPassword); tvUsername = (TextView) findViewById(R.id.tvUsername); tvPassword = (TextView) findViewById(R.id.tvPassword); tvSaveUsername = (TextView) findViewById(R.id.tvRememberUsername); cbSaveUsername = (CheckBox) findViewById(R.id.cbRememberUsername); btLogin = (Button) findViewById(R.id.btnLogin); btCancel = (Button) findViewById(R.id.btnCancel); btLogin.setOnClickListener(this); btCancel.setOnClickListener(this); } //按钮点击事件
 @Override public void onClick(View v) { //获取到编辑框中的用户名和密码
        String name = etUsername.getText().toString(); String pass = etPassword.getText().toString(); switch (v.getId()) { //登陆按钮的点击处理
            case R.id.btnLogin: //若是用户名和密码合法
                if ("admin".equals(name) && "abc123".equals(pass)) { //若是勾选了保存用户名的复选框,则将用户名存储到XML文件中
                    if (cbSaveUsername.isChecked()) { editor.putString("username", name); } else {//若是没有勾选则将用户名从XML文件中移除(若是有的话)
                        editor.remove("username"); } //使用Editor对象操做后,须要调用commit方法进行提交,否则全部的操做都无效。相似与数据库中事务的提交
 editor.commit(); Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "登陆失败", Toast.LENGTH_SHORT).show(); } break; case R.id.btnCancel: break; } } }

完整源码 :  点击下载

 

做者: caobotao
本文版权归做者和博客园共有,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文连接,不然保留追究法律责任的权利。
相关文章
相关标签/搜索