06-数据存储



SharedPreference数据的读写操作:

MainActivity.java:

package com.imooc.sharedpreference;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //1.7======================
    static final String KEY = "MyValue";
    //=========================

    //1.2======================
    private EditText et;
    //=========================
    //1.5======================
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    //=================================

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

        //1.3================================================
        et = (EditText) findViewById(R.id.editTextTextPersonName);
        //===================================================
        //1.5=============================================
        preferences = getPreferences(Activity.MODE_PRIVATE);
        editor = preferences.edit();

        //================================================

        //1.4========================================================================
        findViewById(R.id.readBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String in = preferences.getString(KEY,"当前数值不存在");
                Toast.makeText(getApplicationContext(),in,Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.writeBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1.6====================
                editor.putString(KEY,et.getText().toString());
                if(editor.commit()){
                    Toast.makeText(getApplicationContext(),"写入成功",Toast.LENGTH_SHORT).show();
                }
                //=======================
            }
        });
        //=====================================================================================
    }
}

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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


//1.1=======================================================
   <EditText
    android:id="@+id/editTextTextPersonName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name" />

    <Button
        android:id="@+id/readBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="读取数据"
        tools:layout_editor_absoluteX="14dp"
        tools:layout_editor_absoluteY="131dp" />

    <Button
        android:id="@+id/writeBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="写入数据"
        tools:layout_editor_absoluteX="9dp"
        tools:layout_editor_absoluteY="179dp" />


    //=============================================================

</LinearLayout>

PreferenceActivity使用方法:

 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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="修改首选项" />

</LinearLayout>

MainActivity.java:

package com.example.preferenceactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.3=================================================================
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(),MyPreferenceActivity.class));
            }
        });
    }
}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.preferenceactivity">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".MyPreferenceActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

MyPreferenceActivity.java:

package com.example.preferenceactivity;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.preference.PreferenceActivity;

import androidx.annotation.Nullable;

public class MyPreferenceActivity extends PreferenceActivity{
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

//        1.2==============================================
        addPreferencesFromResource(R.xml.mypreference2);

        //=================================================
    }
}

mypreference2.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    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">-->
    <CheckBoxPreference
        android:key = "checkbox"
        android:title = "是否开启"
        android:summaryOn = "已经开启"
        android:summaryOff = "已经关闭"
    />


<!--    1.1创建xml文件后再创建一个xml文件-->


</PreferenceScreen>
原文地址:https://www.cnblogs.com/juham/p/15249312.html