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();
        }


    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章