Android使用SharedPreferneces存储数据
实现效果:
java代码:
package com.henu.sharedpreferences;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvcontent = (TextView) findViewById(R.id.tv_content);
EditText etcontent = (EditText) findViewById(R.id.et_content);
if(tvcontent.getText().toString().trim().equals("")){
SharedPreferences sp = this.getSharedPreferences("data", MODE_PRIVATE);
tvcontent.setText(sp.getString("content", ""));
etcontent.setText(sp.getString("content", ""));
}
}
public void save(View v) {
EditText etcontent = (EditText) findViewById(R.id.et_content);
SharedPreferences sp = this.getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("content", etcontent.getText().toString().trim());
editor.commit();
Toast.makeText(this, "存入成功", Toast.LENGTH_SHORT).show();
}
public void display(View v) {
TextView tvcontent = (TextView) findViewById(R.id.tv_content);
SharedPreferences sp = this.getSharedPreferences("data", MODE_PRIVATE);
tvcontent.setText(sp.getString("content", ""));
Toast.makeText(this, "取出成功", Toast.LENGTH_SHORT).show();
}
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_content"
android:layout_width="match_parent"
android:layout_height="60dp"
android:textSize="35dp"
android:layout_marginTop="40dp"></EditText>
<Button
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="存入SHAREDPREFERENCES"
android:layout_gravity="center"
android:onClick="save"
android:textSize="35dp"></Button>
<Button
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="从SHAREDPREFERENCES取出"
android:layout_gravity="center"
android:onClick="display"
android:textSize="33dp"></Button>
<TextView
android:textSize="35dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="@+id/tv_content"></TextView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
**注意:**在写Button的android:onClick="save"点击事件不要忘了在定义函数时 public void save(View v) 加入形参 View v。