android基础学习9——SharedPreferences的使用

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

接下来通过一个“QQ登录”的案例来演示如何使用SharedPreferences存储数据。

布局文件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"
    android:background="#E6E6E6"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/iv_head"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:src="@drawable/dddss" />

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/iv_head"
        android:layout_margin="10dp"
        android:background="#ffffff"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/rl_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp" >

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:text="账号" />

            <EditText
                android:id="@+id/et_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@+id/tv_name"
                android:background="@null" />
        </RelativeLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#E6E6E6" />

        <RelativeLayout
            android:id="@+id/rl_userpsw"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp" >

            <TextView
                android:id="@+id/tv_psw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:text="密码" />

            <EditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_toRightOf="@+id/tv_psw"
                android:inputType="textPassword"
                android:background="@null" />
        </RelativeLayout>
    </LinearLayout>

    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/layout"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:background="#3C8DC4"
        android:text="登录"
        android:textColor="#ffffff" />

</RelativeLayout>

创建工具类

添加一个utils包,编写一个Utils类,用于实现QQ号码和密码的存储与获取功能

package com.example.lenovo.utils;

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

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

public class Utils {
    // 保存QQ号码和登录密码,到data.xml文件中
    public static boolean saveUserInfo(Context context, String number,
                                       String password) {
        SharedPreferences sp = context.getSharedPreferences("data",
                Context.MODE_PRIVATE);
        Editor edit = sp.edit();
        edit.putString("userName", number);
        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 number = sp.getString("userName", null);
        String password = sp.getString("pwd", null);
        Map<String, String> userMap = new HashMap<String, String>();
        userMap.put("number", number);
        userMap.put("password", password);
        return userMap;
    }
}
编写页面交互代码

package com.example.lenovo.qqlogin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.lenovo.utils.Utils;

public class MainActivity extends AppCompatActivity implements OnClickListener {
    private EditText etNumber;
    private EditText etPassword;
    //	private CheckBox cbRemember;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // 取出号码
        Map<String, String> userInfo = Utils.getUserInfo(this);
        if(userInfo != null) {
            // 显示在界面上
            etNumber.setText(userInfo.get("number"));
            etPassword.setText(userInfo.get("password"));
        }
    }

    private void initView() {
        etNumber = (EditText) findViewById(R.id.et_number);
        etPassword = (EditText) findViewById(R.id.et_password);
//		cbRemember = (CheckBox) findViewById(R.id.cb_remember);
        findViewById(R.id.btn_login).setOnClickListener(this);
    }

    public void onClick(View v) {
        // 当点击登录时,获取QQ号码 和密码
        String number = etNumber.getText().toString().trim();
        String password = etPassword.getText().toString();
        // 校验号码和密码是否正确
        if(TextUtils.isEmpty(number)) {
            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();
        Log.i("MainActivity", "记住密码: " + number + ", " + password);
        // 保存用户信息
        boolean isSaveSuccess = Utils.saveUserInfo(this, number, password);
        if(isSaveSuccess) {
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
}


运行程序,输入号码和密码,然后点击登录,会提示保存成功



此时如果将程序退出,再重新打开,会发现QQ号码和密码仍然显示,说明QQ信息已经存储在SharedPreferences中。可以打开DDMS窗口找到data.xml文件导出看到已经成功保存QQ号码和密码。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值