美文网首页
Android SharedPreferences

Android SharedPreferences

作者: 百里漫步 | 来源:发表于2017-10-23 20:48 被阅读0次

Android的四种数据存储方式:

  1. SharedPreferences
  2. SQLite
  3. Content Provider
  4. File

SharedPreferences:

  1. 是一种轻型的数据存储方法;
  2. 本质是基于 XML 文件存储 key-value 键值对数据;
  3. 通常用来存储一些简单的配置信息。一般是放置当前应用的属性值,信息量不多,所以用数据库的话不划算,还可能造成时间上的浪费。
    只能实现非常简单的存放数据和读取数据。SharedPreferences只能识别简单的数据类型,比如String、int,对于复杂的类型,比如自定义的类型,可能就无法存储了(或者通过转码操作转变为字符串也倒是可以存储)。
    SharedPreferences属于Android自带的轻量级的存储类,效率并不是很高。

要点:

  1. SharedPreferences对象本身只能获取数据而不支持存储和修改,存储和修改是通过 Editor 对象实现的;
  2. 实现 SharedPreferences 存储的步骤:
    (1)获得 SharedPreferences 对象;
    (2)获得 SharedPreferences.Editor 对象;
    (3)通过 Editor 接口的 putXxx 方法保存 key-value对,其中的Xxx表示不同的数据类型;
    (4)通过 Editor 接口的 commit 方法保存 key-value对。

activity_main.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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="16dp"
        android:text="用户名:" />

    <EditText
        android:id="@+id/etuserName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10" />

    <TextView
        android:id="@+id/aa"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/etuserName"
        android:text="密     码" />

    <EditText
        android:id="@+id/etuserpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/etuserName"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/aa"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <CheckBox
        android:id="@+id/chkSaveName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:checked="false"
        android:layout_below="@+id/etuserpass"
        android:text="保存用户名" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/chkSaveName"
        android:onClick="doClick"
        android:text="登陆" />

    <Button
        android:id="@+id/btnCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/btnLogin"
        android:layout_alignBottom="@+id/btnLogin"
        android:layout_toRightOf="@+id/btnLogin"
        android:onClick="doClick"
        android:text="取消" />

</RelativeLayout>

MainActivity.java

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    EditText etUserName,etUserPass;
    CheckBox chk;
    SharedPreferences pref;
    Editor edtior;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取preference对象
////        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
//      SharedPreferences pref =getSharedPreferences("myPref", MODE_PRIVATE);
//      获取editor对象,进行编辑修改
        //Editor editor = pref.edit();
//      editor.putString("name","张三");
//      editor.putInt("age", 30);
//      editor.putLong("time", System.currentTimeMillis());
//      editor.putBoolean("default", true);
//      editor.commit();
//      editor.remove("default");
//      editor.commit();
//      System.out.println(pref.getString("name", ""));
//      System.out.println(pref.getInt("age", 0));
        etUserName = (EditText) findViewById(R.id.etuserName);
        etUserPass = (EditText) findViewById(R.id.etuserpass);
        chk = (CheckBox) findViewById(R.id.chkSaveName);
        pref =getSharedPreferences("UserInfo", MODE_PRIVATE);
        edtior = pref.edit();
        String name = pref.getString("userName", "");
        if (name==null) {
            chk.setChecked(false);
        }else {
            chk.setChecked(true);
            etUserName.setText(name);
        }
    }
    public void doClick(View v){
        switch (v.getId()) {
        case R.id.btnLogin:
            String name = etUserName.getText().toString().trim();
            String pass = etUserPass.getText().toString().trim();
            if ("admin".equals(name)&&"123456".equals(pass)) {
                if (chk.isChecked()) {
                    edtior.putString("userName", name);
                    edtior.commit();
                    
                }else {
                    edtior.remove("userName");
                    edtior.commit();
                }
                Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(MainActivity.this, "禁止登陆", Toast.LENGTH_LONG).show();
            }
            break;

        default:
            break;
        }
    }
    

}

演示效果:


SharedPreferences.gif

相关文章

网友评论

      本文标题:Android SharedPreferences

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