SharedPreferences存储

目录

1.获得SharedPreferences对象

1.1 使用getSharedPreferences()方法获取

1.2 使用getPreferences()方法获取

2.向SharedPreferences文件中存储数据

3. 读取SharedPreferences文件中存储的数据

4.运用


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

1.获得SharedPreferences对象

SharedPreferences接口位于android.content包中,用于使用键值(key-value)对的方式来存储数据。在应用程序结束后,数据仍旧会保存。数据是以XML文件格式保存在Android手机系统下的“/data/data/<应用程序包名>/shared_prefs”目录中,该文件被成为SharedPreferences(共享的首选项)文件。

通常情况下,可以通过两种方式获得SharedPreferences对象。

1.1 使用getSharedPreferences()方法获取

如果需要多个使用名称来区分的SharedPreferences文件,则可以使用getSharedPreferences()犯法获取,该方法的基本语法如下:

getSharedPreferences(String name,int mode);

//name:共享文件的名称(不包括扩展名),该文件为XML格式。对于使用同一个名称获得的多个SharedPreferences引用,其指向同一个对象。
//made:用于指定访问权限,它的参数值可以是MODE_PROVATE(表示只能被本应用程序读和写,其中写入的内容会覆盖源文件的内容)、MODE_MULTI_PROCESS(表示可以跨进程、跨应用读取)。

1.2 使用getPreferences()方法获取

如果Activity仅需要一个SharedPreferences文件,则可以使用getPreferences()方法获取。因为只有一个文件,所以不需要提供名称。该方法的语法格式如下:

getPreferences(int mode);
//mode的取值与上面getSharedPreferences()方法中的mode取值一样

2.向SharedPreferences文件中存储数据

步骤如下

(1)调用SharedPreferences类的edit()方法获得SharedPreferences.Editor对象。

SharedPreferences.Editor editor=getSharedPreferences("demo",MODE_PRIVATE).edit();
//获得私有类型的SharedPreferences.Editor对象

(2)向SharedPreferences.Editor对象中添加数据。

editor.putString("username",username);
editor.putBoolean("status",false);
editor.putInt("age",10);

(3)使用commit()提交数据,从而完成数据存储操作。

editor.commit();

3. 读取SharedPreferences文件中存储的数据

从SharedPreferences文件中读取数据时,主要使用SharedPreferences类的getXX()方法。

SharedPreferences sp=getSharedPreferences("demo",MODE_PRIVATE);
String username=sp.getString("username","demo");
Boolean status=sp.getBoolean("status",false);
int age=getInt("age",18);

4.运用

该代码有很多不足的地方,实践过程中我发现,只用成功登录过一次,那么后面还想要再继续登录,那么就要修改文件名。

MainActivity.java

package com.example.datastorage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        EditText editText=findViewById(R.id.EditText);
        TextView textView=findViewById(R.id.TextView);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ed=editText.getText().toString().trim();
                SharedPreferences sharedPreferences=getSharedPreferences("demo",MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                editor.putString("name",ed);
                boolean isSaveSuccess=editor.commit();
                if(isSaveSuccess){
                    Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_SHORT).show();
                }
            }
        });
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp=getSharedPreferences("demo",MODE_PRIVATE);
                String str=sp.getString("name","无");
                textView.setText(str);
            }
        });

    }
}

 MainActivity.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/EditText"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginTop="108dp"
        android:textSize="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/TextView"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_marginBottom="364dp"
        android:text="textview"
        android:textSize="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="88dp"
        android:layout_marginLeft="88dp"
        android:layout_marginBottom="252dp"
        android:text="保存"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="68dp"
        android:layout_marginRight="68dp"
        android:layout_marginBottom="252dp"
        android:text="读取"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

查看“demo.xml”文件

然后找到data——>data——>包名+你自己设置的类名——>shared_prefs——>demo.xml

demo.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<!--active会根据输入的变动-->
<map>
    <string name="name">active</string>
</map>

运行结果

 

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值