SharedPreferences的简单使用以及官方API给出的使用方法

来源:互联网 发布:外卖点餐系统源码 编辑:程序博客网 时间:2024/06/16 04:17
Android的四种数据存储方式:
1.SharedPreferences
2.SQLite
3.Content Provider
4.File


今天介绍的是SharedPreferences:

1.是一种轻型的数据存储方式
2.本质是基于XML文件存储key-value键值对数据

3.通常用来存储一些简单的配置信息

为了使用SharedPreferences,写了一个小案例“用户账号登录信息的存储”

首先贴出代码:

package com.example.sharedprefsdemo;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.support.v4.widget.SearchViewCompat.OnCloseListenerCompat;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText mUserName, mPssWord;private CheckBox mCheck;private Button mLogin, mCancel;private Editor editor;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initComponent();/** * 1.获得SharedPreferences对象 * 2.通过preferences.edit()获得Editor对象 * 3.通过Editor对象配置文件里写入信息 * 4.写完或者修改完信息后一定要commit */SharedPreferences preferences = getSharedPreferences("user_info",MODE_PRIVATE);editor = preferences.edit();String usrName = preferences.getString("USER_NAME", "");String pssWord = preferences.getString("PASSWORD", "");if ( usrName != null) {mUserName.setText(usrName);}if ( pssWord != null) {mCheck.setChecked(true);mPssWord.setText(pssWord);}}/* * 初始化组件 */private void initComponent() {mUserName = (EditText) findViewById(R.id.username);mPssWord = (EditText) findViewById(R.id.psswd);mCheck = (CheckBox) findViewById(R.id.check);mLogin = (Button) findViewById(R.id.login);mCancel = (Button) findViewById(R.id.cancel);mLogin.setOnClickListener(new MyListener());mCancel.setOnClickListener(new MyListener());}class MyListener implements OnClickListener {@Overridepublic void onClick(View v) {String userName = mUserName.getText().toString().trim();String pssWord = mPssWord.getText().toString().trim();if (v.getId() == R.id.login) {if (userName.equals("admin") && pssWord.equals("123456")) {if (mCheck.isChecked()) {// 写入信息editor.putString("USER_NAME", userName);editor.putString("PASSWORD", pssWord);editor.commit();}else{// 移除信息editor.remove("PASSWORD");editor.commit();}Toast.makeText(MainActivity.this, "成功登陆!", 0).show();}else{Toast.makeText(MainActivity.this, "账户信息有误,请重新输入!", 0).show();}}}}}
布局文件代码:

<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:layout_margin="5dp"    android:orientation="vertical"    tools:context="${relativePackage}.${activityClass}" >    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/_username"            android:textSize="18sp" />        <EditText            android:id="@+id/username"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:singleLine="true" >        </EditText>    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="密  码"            android:textSize="18sp" />        <EditText            android:id="@+id/psswd"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:password="true"            android:singleLine="true" >        </EditText>    </LinearLayout>    <CheckBox        android:id="@+id/check"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:checked="false"        android:text="记住密码" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:orientation="horizontal" >        <Button            android:id="@+id/login"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="登陆" />        <Button            android:id="@+id/cancel"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="取消" />    </LinearLayout></LinearLayout>
当记住密码未被勾选时,在以后登陆时的界面如下:


当记住密码被勾选时,在以后登陆时的界面如下:


用户的登录信息通过editor写入到xml文件中,如下:


user_info.xml文件里存储的是键值对。

下面给出官网的API对SharedPreferences的用法解释:

The SharedPreferences class provides a general framework that allows youto save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, andstrings. This data will persist across user sessions (even if your application is killed).

To get a SharedPreferences object for your application, use one oftwo methods:

  • getSharedPreferences() - Use this if you need multiple preferences files identified by name,which you specify with the first parameter.
  • getPreferences() - Use this if you needonly one preferences file for your Activity. Because this will be the only preferences filefor your Activity, you don't supply a name.

To write values:

  1. Call edit() to get aSharedPreferences.Editor.
  2. Add values with methods such as putBoolean() andputString().
  3. Commit the new values with commit()



0 0