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


    }
}

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