Android如何使用SharedPreferences轻量级储存

SharedPreferences只能用来存一些基本数据类型,并且存下的量比较小

直接附代码 和XMl布局

package com.example.okhttpdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MySharedPreferences extends AppCompatActivity {

    //声明
    EditText et_user;
    Button btn_xianshi;
    TextView tv_text;
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_shared_preferences);
        //找到控件
        et_user = findViewById(R.id.et_user);
        btn_xianshi = findViewById(R.id.btn_xianshi);
        tv_text = findViewById(R.id.tv_user);
        //按钮的点击事件
        btn_xianshi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建preferences
                preferences = getSharedPreferences("text", MODE_PRIVATE);
                //声明一个存储
                SharedPreferences.Editor editor = preferences.edit();
                //直接存数据
                editor.putString("user", et_user.getText().toString());
                editor.commit();

                //拿出数据,需要取到相同的key,第二个参数输入空值就可以

                tv_text.setText(preferences.getString("user", ""));
                //输入时使用edit,输出时使用preferences
            }
        });


    }
}

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"
    android:orientation="vertical"
    tools:context=".MySharedPreferences">
    <EditText
        android:id="@+id/et_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        />
    <Button
        android:id="@+id/btn_xianshi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="显示"
        />
    <TextView
        android:id="@+id/tv_user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        />

</LinearLayout>

效果图
在里面输入内容点击显示

在这里插入图片描述

点击按钮后显示
在这里插入图片描述

原文地址:https://www.cnblogs.com/a1439775520/p/12946969.html