android配置文件保存到本地(SP)

402 阅读1分钟

权限声明

在这里插入图片描述

<!-- 写入存储权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

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

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="saveToSP"
        android:text="保存到SP"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="getSP"
        android:text="从SP获取"/>
</LinearLayout>

后端代码

//sp保存
    public void saveToSP(View view) {
        //文件名字,存储模式
        SharedPreferences sp = getSharedPreferences("sp_config", Context.MODE_PRIVATE);
        sp.edit().putString("mykey","aaa").apply();
        sp.edit().putString("mykey1","bbb").apply();
    }

    //从使用sp获取数据
    public void getSP(View view) {
        //从文件获取
        SharedPreferences sp = getSharedPreferences("sp_config", Context.MODE_PRIVATE);
        //获取sp全部数据
        Map<String, ?> all = sp.getAll();
        Log.d(TAG, "获取的全部数据--->: "+all);
        //根据key获取value,如果不存在mykey就直接使用默认值
        String string = sp.getString("mykey", "默认");
        String string1 = sp.getString("mykey2", "默认");
        Log.d(TAG, "string--->mykey(存在)--->: "+string);
        Log.d(TAG, "string1--->mykey2(不存在)--->: "+string1);
        Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }

在这里插入图片描述
存储的配置问价放在
在这里插入图片描述
下面的data—>data—>和文件目录相同的—>shared_prefs
在这里插入图片描述