Android存储之一利用SharePreferences存储数据

布局文件:
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

   <CheckBox
       android:id="@+id/cb"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="启动后呈现对话框"></CheckBox>

</LinearLayout>

1.首先获取SharedPreferences对象;

SharePreferences sharedPreferences = getSharedPreferences("aaa", Context.MODE_PRIVATE);

第一个参数的aaa是自己定义的,随便叫,取值时候要用的。
2.获取SharedPreferences.Editor对象;

 SharedPreferences.Editor editor = sharedPreferences.edit();

用SharedPreferences对象调用edit()方法,

3.用Editor 存值;

 editor.putBoolean("aaa", isChecked);
 editor.commit();//切记一定要提交

一定要提交,一定要提交,一定要提交

4.取值:

boolean b=sharedPreferences.getBoolean("aaa", false)

以上就实现了存值和取值的过程;

下面有个代码的实现可以参考下:

package com.example.myview;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private CheckBox cb;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sharedPreferences = getSharedPreferences("aaa", Context.MODE_PRIVATE);
        cb = findViewById(R.id.cb);

        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("aaa", isChecked);
                editor.commit();

            }
        });
        cb.setChecked(sharedPreferences.getBoolean("aaa", false));

        if (cb.isChecked()) {
            AlertDialog builder = new AlertDialog.Builder(this).setTitle("你好").setMessage("欢迎使用我").setNegativeButton("取消",null).show();
        }


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值