SharedPreferences用法
效果:
EditText用于用户输入要存储的内容,点击第一个Button键存入。
点击第二个按钮,TextView从该数据结构中取出被存入的内容。
直接贴代码:
MainActivity.java:
package com.example.savedatashared;
import androidx.appcompat.app.AppCompatActivity;
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 {
EditText et_Context;
TextView tv_Context;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//将信息保存到快速存取的数据结构中
public boolean saveInfo(String userName){
boolean _bool = false;
//启动快速存取
sharedPreferences = MainActivity.this.getSharedPreferences("data",MODE_PRIVATE);
//开始写入
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("editText",userName);
_bool = editor.commit();
return _bool;
}
public void SaveInfoOnclick(View view){
et_Context = findViewById(R.id.Context);
if(saveInfo(et_Context.getText().toString().trim())){
Toast.makeText(MainActivity.this,"成功了",Toast.LENGTH_SHORT).show();
}
}
public void ShowInfOnclick(View view){
tv_Context = findViewById(R.id.ShowContext);
tv_Context.setText(sharedPreferences.getString("editText",""));
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:padding="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/Context"
android:layout_width="0dp"
android:layout_weight="1"
android:hint="Input,please!"
android:layout_height="66dp"></EditText>
<Button
android:onClick="SaveInfoOnclick"
android:id="@+id/SaveContext"
android:text="存入SharedPreferences"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="66dp"></Button>
</LinearLayout>
<LinearLayout
android:padding="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/ShowContext"
android:layout_width="0dp"
android:layout_weight="1"
android:hint="Input,please!"
android:layout_height="66dp"></TextView>
<Button
android:onClick="ShowInfOnclick"
android:text="从SharedPreferences取出"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="66dp"></Button>
</LinearLayout>
</LinearLayout>