Android——SharedPreferences 存储(含源码下载)

Android 系统提供了轻量级的数据存储方式——SharedPreferences 存储。它屏蔽了对底层文件的操作,通过为程序开发人员提供简单的编程接口,实现以最简单的方式对数据进行永久保存。这种方式主要对少量的数据进行保存,比如对应用程序的配置信息、手机应用的主题、游戏的玩家积分等进行保存。

如何使用SharedPreferences 存储数据?

一、获取SharedPreferences 对象,一般有两种方法
方法1:getSharedPreferences(String name, int mode)
name:共享文件的名称(不包括扩展名),该文件为 XML 格式。
mode:用于指定访问权限,它的参数值可以是 MODE_PRIVATE、MODE_MULTI_PROCESS,一般选用第一个即可。
方法2:getPreferences(int mode)
mode与方法1相同。

二、获得 SharedPreferences.Editor 对象,通过Editor 对象的方法进行写入。
获得Editor 对象:SharedPreferences.Editor editor=getSharedPreferences("myinfo",MODE_PRIVATE).edit();
写入数据(通过键值的方式写入):editor.putString("VALUE","hello");
提交当前数据:editor.commit();

三、获取SharedPreferences 的对象sharedPreferences,通过sharedPreferences进行读取数据操作
获取sharedPreferences对象:SharedPreferences sharedPreferences = getSharedPreferences("myinfo",MODE_PRIVATE);
对数据进行读取:sharedPreferences.getString(“VALUE”,“myinfo”)

下面通过一个实例体验一下SharedPreferences存储。
本次通过一个简单的用户登录界面来展现,用SharedPreferences存储来保存账户和密码信息。
在这里插入图片描述
代码如下:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/et_user"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="10dp"
        android:drawableRight="@drawable/icon_user"
        android:ems="10"
        android:hint="请输入账号"
        android:inputType="textPersonName"
        android:paddingLeft="5dp"
        android:paddingRight="10dp"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/et_password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginRight="5dp"
        android:drawableRight="@drawable/icon_password"
        android:ems="10"
        android:hint="请输入密码"
        android:inputType="textPassword"
        android:paddingLeft="5dp"
        android:paddingRight="10dp"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_confirm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="保存并显示用户信息"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_password" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/et_user"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher_round" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.mydemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    public static final String USER = "user";
    public static final String PASSWORD = "password";
    public static final String MYINFO = "myinfo";

    private EditText etUser;
    private EditText etPassword;
    private Button btnConfirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etUser = findViewById(R.id.et_user);
        etPassword = findViewById(R.id.et_password);
        btnConfirm = findViewById(R.id.btn_confirm);

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存用户信息
                savedInfo();

                //通过对话框展示存储信息
                showInfo();
            }
        });
    }

    private void showInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences(MYINFO,MODE_PRIVATE);

        //创建一个对话框
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("登录信息")
                .setMessage("账户:"+sharedPreferences.getString(USER,MYINFO)+"\n"+
                        "密码:"+sharedPreferences.getString(PASSWORD,MYINFO))
                .setCancelable(false)
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                })
                .create()
                .show();
    }

    private void savedInfo() {

        if (TextUtils.isEmpty(etUser.getText())&&
                TextUtils.isEmpty(etPassword.getText())) {
            Toast.makeText(getApplicationContext(),"账户或密码不能为空!",Toast.LENGTH_SHORT)
                    .show();
        }
        else {
            SharedPreferences.Editor editor =
                    getSharedPreferences(MYINFO,MODE_PRIVATE).edit();

            editor.putString(USER,etUser.getText().toString());
            editor.putString(PASSWORD,etPassword.getText().toString());
            editor.commit();//提交当前数据

        }

    }
}

链接:百度网盘下载 提取码:5mp7

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值