1 效果图
解释:点击“Save data”后打印日志“saved”,点击“Restore data”后打印Log.d("MainActivity", "name is " + name);Log.d("MainActivity", "age is " + age); Log.d("MainActivity", "married is " + married);
2 MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button saveData = findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 调用SharedPreferences对象的edit()方法获取SharedPreferences.Editor对象
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
// 1 向SharedPreferences.Editor对象中添加数据
editor.putString("name", "Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
// 2 调用apply()方法提交数据
editor.apply();
Log.d("MainActivity", "saved");
}
});
Button restoreData = findViewById(R.id.restore_data);
restoreData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 通过getSharedPreferences()方法得到SharedPreferences对象
SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
// 获取前面存储的数据
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);
// 打印日志
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "age is " + age);
Log.d("MainActivity", "married is " + married);
}
});
3 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/save_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save data"
/>
<Button
android:id="@+id/restore_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Restore data"
/>
</LinearLayout>