Android:SharedPreference实例详解

作者: Gunther | 来源:发表于2016-12-13 11:42 被阅读64次
  • 2016年12月8日,Google中国开发者大会在京举行,同时正式上线了Google中国开发者网站Google Developers,查看官方学习资源再也不用爬梯子了

在Android系统中,常用的数据储存方式有四种:

  1. 存储在手机内存中ROM
  2. 存储在SD卡中
  3. 存储在SharedPreferences中
  4. 存储在SQLite数据库中

在这里只介绍Android特有的SP和SQLite

SharedPreferences

SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置,它提供了Android平台常规的Long、Int、String字符串型的保存。

SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。

xml 处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。

这种方式应该是用起来最简单的Android读写外部数据的方法了。他以一种简单、 透明的方式来保存一些用户个性化设置的字体、颜色、位置等参数信息。一般的应用程序都会提供“设置”或者“首选项”的这样的界面,那么这些设置最后就可以通过Preferences来保存,而程序员不需要知道它到底以什么形式保存的,保存在了什么地方。当然,如果你愿意保存其他的东西,也没有什么限制。只是在性能上不知道会有什么问题。
在Android系统中该文件保存在:/data/data/PACKAGE_NAME /shared_prefs 目录下。

下面是一个使用SP做数据存储模拟用户登录的案例:
布局文件:

<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" >
<EditText 
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:hint="请输入用户名"
    android:id="@+id/et_username"
    />
<EditText 
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:hint="请输入密码"
    android:inputType="textPassword"
    android:id="@+id/et_pwd"
    />
    <LinearLayout 
    android:layout_marginTop="10dp"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:gravity="right"
    >
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登陆"
        android:onClick="login"
        />
    <CheckBox 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存密码"
         android:layout_marginRight="10dp"
         android:id="@+id/cb"
        />
</LinearLayout>
</LinearLayout>

案例代码:

public class MainActivity extends Activity {
private EditText et_username;
private EditText et_pwd;
private CheckBox cb;
//声明一个SharedPreferences对象
private SharedPreferences sp;
/*
 * 为了方便,因此将用户名和密码设置为常量
 */
private static final String PWD = "123456";
private static final String USERNAME = "wzy";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    /*
     * 第二个参数代表的是创建该文件的访问范围(权限),通常并建议选择MODE_PRIVATE,该值为0,
     * 意思是只有当前应用可以访问该文件。而还有2个可选项MODE_WORLD_READABLE 和MODE_WORLD_WRITEABLE
     * 值分别为1和2已经废除,因为这两种方式可以允许其他应用来访问此文件,这是很不安全的。
     */
    sp = getSharedPreferences("info", MODE_PRIVATE);
    et_username = (EditText) findViewById(R.id.et_username);
    et_pwd = (EditText) findViewById(R.id.et_pwd);
    cb = (CheckBox) findViewById(R.id.cb);
    /*


 * 从sp中获取用户信息,用户数据的回显
     * 第二个参数为默认返回值,也就是当要查找的key-value不存在时,返回的数据
     */
    String username = sp.getString("username", "");
    String pwd = sp.getString("pwd", "");
    et_username.setText(username);
    et_pwd.setText(pwd);
}

public void login(View view){
    String userName = et_username.getText().toString();
    String pwd = et_pwd.getText().toString();
    boolean checked = cb.isChecked();
    /*
     * 用户名和密码如果为空,则提示用户。
     */
    if (TextUtils.isEmpty(userName)) {
        Toast.makeText(this, "用户名不能为空!", Toast.LENGTH_SHORT).show();
        return ;
    }
    if (TextUtils.isEmpty(pwd)) {
        Toast.makeText(this, "密码不能为空!", Toast.LENGTH_SHORT).show();
        return ;
    }
    /*
     * 如果用户选择了保存密码,则将用户名和密码保存在手机内存中
     * 如果没有选择就将文件删除
     */
if (USERNAME.equals(userName)&&PWD.equals(pwd)) {
        if (checked) {
            /*
             * 在对sp进行写、修改需要获取Editor对象
             */
            Editor editor = sp.edit();
            editor.putString("username", userName);
            editor.putString("pwd", pwd);
            /*
             * 此处非常重要,执行完修改或者写操作后只有调用sp的commit方法,数据才会被保存下来。
             */
            editor.commit();


}else {//删除用户文件
            Editor editor = sp.edit();
            /*
             * 删除该sp中的所有数据
             */
            editor.clear();
            editor.commit();
        }
        Toast.makeText(this, "恭喜您,登陆成功!", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "对不起,登陆失败!", Toast.LENGTH_SHORT).show();
    }
}
}

相关文章

网友评论

    本文标题:Android:SharedPreference实例详解

    本文链接:https://www.haomeiwen.com/subject/krovmttx.html