MainActivity
package com.example.sharedpreferences;
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 {
private Button main_bu_cun;
private Button main_bu_du;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main_bu_cun=findViewById(R.id.main_bu_cun);
main_bu_du=findViewById(R.id.main_bu_duqu);
//存数据
main_bu_cun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
editor.putString("name","tom");
editor.putInt("age",28);
editor.putBoolean("married",false);
editor.apply();
}
});
//读取数据
main_bu_du.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences preferences=getSharedPreferences("data",MODE_PRIVATE);
String name=preferences.getString("name","");
int age=preferences.getInt("age",0);
Boolean married=preferences.getBoolean("married",false);
Log.d("MainActivity","name is"+name);
Log.d("MainActivity", "age is"+age);
Log.d("MainActivity", "maaried is"+married);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/main_bu_cun"
android:text="save data"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/main_bu_cun"
android:id="@+id/main_bu_duqu"
android:text="restore data"
/>
</RelativeLayout>