Android--SharedPreferences的存储和获取数据--案例《登录》

来源:互联网 发布:ep订票软件 编辑:程序博客网 时间:2024/04/26 11:47

Sharedpreferences的使用简介

SharedPreference是Android平台上一个轻量级的存储类,主要用于存储一些应用程序的配置参数,比如用户名、密码、自定义参数的设置等。Sharedpreferences中存储的数据是以key/value兼职对的形式保存在XML文件夹中,改文件位于data/data/<packagename>/shared+pres的文件夹中。需要注意的是,SharedPreferences中的value值只能是float、int、long、Boolean、String、StringSet类型数据。

使用SharedPreferences类存储数据时,首先需要通过context.getSharedPrefences(Stringname,int mode)获取SharedPreferences的实例对象(Sharedpreferences sp=context.getSharedpreferences("保存文件的name",Context.MODE_PRIVATE)).

接下来做一个登录的app,主要实现存储和获取功能,进一步了解SharedPreferences的使用。案例如下:

1.设计一个登录布局界面。代码如下:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_exe01"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="bzu.edu.cn.a17lab05.Exe01Activity"    android:orientation="vertical"    android:background="#87CEFA"    >    <RelativeLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@drawable/bg"        >    <EditText    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:drawableLeft="@drawable/a"    android:hint="请输入账号"        android:background="#FFFFFF"        android:id="@+id/e1"        android:textSize="30dp"        android:layout_marginTop="10dp"        />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:drawableLeft="@drawable/b"        android:hint="请输入密码"        android:layout_below="@id/e1"        android:background="#FFFFFF"        android:layout_marginTop="10dp"        android:textSize="30dp"        android:id="@+id/e2"        android:password="true"        />    <CheckBox        android:text="记住密码"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/e2"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:id="@+id/c1"        android:textSize="20dp"        android:layout_marginTop="8dp"/>    <Button        android:layout_width="110dp"        android:layout_height="35dp"        android:text="登录"        android:layout_below="@id/e2"        android:layout_toRightOf="@id/c1"        android:layout_marginLeft="30dp"        android:textSize="20dp"        android:background="@drawable/bg2"        android:layout_marginTop="3dp"        android:id="@+id/b1"        />    </RelativeLayout>    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        app:srcCompat="@drawable/c"        android:layout_marginBottom="50dp"        android:id="@+id/imageView"        android:layout_marginRight="13dp"        android:layout_marginEnd="13dp"        android:layout_alignParentBottom="true"        android:layout_alignParentRight="true"        android:layout_alignParentEnd="true" /></RelativeLayou>
实现效果为
2.创建一个工具类Utils
  因为使用SharedPreferences存储数据是一个比较独立的模块,因此,添加一个包,在该包中编写Utils类用于实现账号和密码
存储和获取功能,代码如下:
package cn.edu.bzu.utils;import android.content.Context;import android.content.SharedPreferences;import java.util.HashMap;import java.util.Map;//获取SharedPreferences实例对象,再获取Editor编辑使用其中的方法。实现账号和密码保存到data。XML文件中。public class Utils {    public static boolean saveInfo(Context context, String yong, String password){        SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);        SharedPreferences.Editor edit=sp.edit();        edit.putString("username",yong);        edit.putString("psw",password);        edit.commit();        return true;    }
//使用Map<>方法从data.xml文件中获取数据    public static Map<String,String> getInfo(Context context){        SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);        String yong=sp.getString("username",null);        String password=sp.getString("psw",null);        Map<String,String> userMap=new HashMap<String, String>();        userMap.put("yong",yong);        userMap.put("password",password);        return userMap;    }}
3.编写界面交互代码
在其中,实现党用户输入完账号和密码后,选择记住密码,然后单击登录按钮调用saveInfo()发放保存密码。代码如下:
package bzu.edu.cn.a17lab05;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import java.util.Map;import cn.edu.bzu.utils.Utils;public class Exe01Activity extends AppCompatActivity {    private Button b1;    private EditText ee1;    private EditText ee2;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_exe01);        ee1=(EditText) findViewById(R.id.e1);        ee2=(EditText) findViewById(R.id.e2);        b1=(Button) findViewById(R.id.b1);        Map<String,String>userInfo= Utils.getInfo(this);        if(userInfo!=null){            ee1.setText(userInfo.get("yong"));            ee2.setText(userInfo.get("password"));        }        b1.setOnClickListener(new View.OnClickListener() {            public void onClick(View view) {               String yong=ee1.getText().toString().trim();                String password=ee2.getText().toString().trim();                if (TextUtils.isEmpty(yong)){                    Toast.makeText(Exe01Activity.this, "请输入账号", Toast.LENGTH_SHORT).show();                    return;                }                if (TextUtils.isEmpty(password)){                    Toast.makeText(Exe01Activity.this, "请输入密码", Toast.LENGTH_SHORT).show();                    return;                }                Toast.makeText(Exe01Activity.this, "登陆成功", Toast.LENGTH_SHORT).show();                Log.i("Exe01Activity","记住密码"+yong+","+password);                boolean isSaveSuccess=Utils.saveInfo(Exe01Activity.this,yong,password);                if (isSaveSuccess){                    Toast.makeText(Exe01Activity.this, "保存成功", Toast.LENGTH_SHORT).show();                }                else {                    Toast.makeText(Exe01Activity.this, "保存失败", Toast.LENGTH_SHORT).show();                }            }        });    }}最后实现效果为:
此次实现存储和获取账号密码的功能,当你记住密码是下次重新打开时仍然显示当前的EditText。这就说明信息存储在SharerdPreferences中了
案例成功了


2 0
原创粉丝点击