Android的SharePreferences存储的案例(qq账号存储)

使用SharedPreferences类存储数据时,首先需要调用getSharedPreferences(String name,int mode)方法获取实例对象。由于该对象本身只能获取数据,不能对数据进行存储和修改,因此需要调用SharedPreferences类的edit()方法获取可编辑的Editor对象,最后通过该对象的putXxx()方法存储数据,示例代码如下

//或取sp对象,参数data表示文件名,MODE_PRIVATE表示文件操作模式
SharePreferences sp=getSharedPreferences("data",MoDE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();//获取编辑器
editor.putString("name","传智播客");//存入String类型数据
editor.putString("age",8);//存入int类型数据
editor.commit();//提交修改

Editor对象是以key/value的形式保存数据的,并且根据数据类型的不同,会调用不同的方法。需要注意的是,操作完数据后,一定要调用commit()方法进行数据提交,否则所有操作不生效。

注意:SharedPreferences中的Editor编辑器是通过key/value(键值对)的形式将数据保存在data/data/<packagename>/shared_prefs文件夹下文件中,其中value值只能是float,int,long,boolean,String,Set<String>类型数据。

2.读取SharedPreferences中的数据

获取SharedPreferecnes对象,然后通过该对象的getXXX()方法根据相应key值获取到value的值即可,示例代码如下:

SharedPreferences sp=getSharedPreferences("data",MODE_PRIVATE);
String data=sp.getString("name","");//获取用户名


//getXXX()方法的第二个参数为缺省值,如果sp中不存在该key,将返回缺省值,
例如getString("name",""),若name不存在则key就返回空字符串

3.删除SharedPreferences中的数据

需要调用Editor对象的remove(String key)方法或者clear()方法即可,示例代码如下:

editor.remove("name");//删除一个数据
editor.clear();//删除所有数据

然后展示该案例

程序运行成功后,在界面中输入账号和密码,点击”登录"按钮,会弹出提示信息“登录成功”与“保存成功”,此时如果将程序退出,再重新打开会发现QQ账号和密码仍然显示在当前的EditText中

在activity-main.xml中添加以下代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#E6E6E6"
    android:orientation="vertical"
    android:padding="10dp">
    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:src="@drawable/head" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@android:color/white"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="账号:"
            android:textColor="#000"
            android:textSize="20sp" />
        <EditText
            android:id="@+id/et_account"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:background="@null"
            android:padding="10dp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@android:color/white"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="密码:"
            android:textColor="#000"
            android:textSize="20sp" />
        <EditText
            android:id="@+id/et_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:background="@null"
            android:inputType="textPassword"
            android:padding="10dp" />
    </LinearLayout>
    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:background="#3C8DC4"
        android:text="登录"
        android:textColor="@android:color/white"
        android:textSize="20sp" />
</LinearLayout>

创建一个工具类SaveQQ,用来保存qq账号和密码

package com.example.qqlogin;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.HashMap;
import java.util.Map;

public class SaveQQ {
    //保存QQ账号和登录密码到data.xml文件中
    public static boolean saveUserInfo(Context context, String account, String password){
        SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
        SharedPreferences.Editor edit=sp.edit();
        edit.putString("username",account);
        edit.putString("pwd",password);
        edit.commit();
        return true;

    }
    //从data。xml文件中获取存储的QQ账号和密码
    public static Map<String,String> getUserInfo(Context context){
        SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
        String account=sp.getString("username",null);
        String password=sp.getString("pwd",null);
        Map<String,String> userMap=new HashMap<String,String>();
        userMap.put("account",account);
        userMap.put("password",password);
        return userMap;

    }
}

在mianActivity中添加以下代码

package com.example.qqlogin;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    private EditText et_account;   //账号输入框
    private EditText et_password; //密码输入框
    private Button btn_login;      //登录按钮
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        //通过工具类SaveQQ中的getUserInfo()方法获取QQ账号和密码信息
        // Map<String, String> userInfo = FileSaveQQ.getUserInfo(this);
        Map<String, String> userInfo = SaveQQ.getUserInfo(this);
        if (userInfo != null) {
            et_account.setText(userInfo.get("account"));   //将获取的账号显示到界面上
            et_password.setText(userInfo.get("password")); //将获取的密码显示到界面上
        }
    }
    private void initView() {
        et_account = (EditText) findViewById(R.id.et_account);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        //设置按钮的点击监听事件
        btn_login.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                //当点击登录按钮时,获取界面上输入的QQ账号和密码
                String account = et_account.getText().toString().trim();
                String password = et_password.getText().toString();
                //检验输入的账号和密码是否为空
                if (TextUtils.isEmpty(account)) {
                    Toast.makeText(this, "请输入QQ账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                //保存用户信息
                boolean isSaveSuccess = SaveQQ.saveUserInfo(this, account,
                        password);
                /*  boolean isSaveSuccess = SPSaveQQ.saveUserInfo(this, account, password);*/
                if (isSaveSuccess) {
                    Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

这是用到的一张图片资源       

为了验证QQ信息是否保存到了SharedPreferences中,可以在Device FileExplorer 视图中找到该程序的share_prefs目录,然后找到data.xml。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值