基于AndroidStudio的数据存储(SharedPreferences存储)的简单应用
前言
在手机的登录界面输入用户名和密码,点击登录按钮后会将数据存储在本地系统文件中。下次再打开这个登录界面时,系统会自动来判断本地是否已经存在数据,若存在数据则直接显示在EditTextView框中
一、登录界面设计
效果图:
代码:
<?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">
<EditText
android:id="@+id/txtusername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名:" />
<EditText
android:id="@+id/txtpasssword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码:" />
<Button
android:id="@+id/btlogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录" />
</LinearLayout>
二、MainActivity_10_5 中
代码:
package com.example.upclass;
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;
public class MainActivity_10_5 extends AppCompatActivity {
private EditText txtusername, txtpassword;
private Button btlogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_10_5);
txtusername = findViewById(R.id.txtusername);
txtpassword = findViewById(R.id.txtpasssword);
btlogin = findViewById(R.id.btlogin);
//按钮点击之后才出现的
final SharedPreferences sharedPreferences = getSharedPreferences("login", MODE_PRIVATE);
btlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", txtusername.getText().toString());
editor.putString("password", txtpassword.getText().toString());
editor.apply();
}
});
String username = sharedPreferences.getString("username", "");
String password = sharedPreferences.getString("password", "");
if (!username.equals("") && !password.equals("")) {
txtusername.setText(username);
txtpassword.setText(password);
}
}
}
注意:第一次运行这个项目时,本地是没有用户名和密码这个数据的。需要先输入数据,最后点击登录,本地便会生成数据。
例:
本地记录:
退出后再次打开这个软件后,便会发现用户名和密码是显示在上面的。