紧接上文,我们使用SharedPreferences来存储用户注册的信息
先新建一个SharedPreferences类
package com.cbz.blog;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
import java.util.Map;
public class SP {
public static boolean saveUserInfo(Context context,String number,String password){
SharedPreferences sp = context.getSharedPreferences("data", context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("username",number);
edit.putString("pwd",password);
edit.commit();
return true;
}
public static Map<String,String> getUserInfo(Context context){
SharedPreferences sp = context.getSharedPreferences("data", context.MODE_PRIVATE);
String username = sp.getString("username", "");
String password = sp.getString("pwd", "");
Map<String,String> userMap = new HashMap<>();
userMap.put("number",username);
userMap.put("password",password);
return userMap;
}
}
再对之前的Mian函数做一些小小的改动
package com.cbz.blog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private EditText name;
private EditText password;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
//Map<String, String> userInfo = File.getUserInfo(this);
Map<String, String> userInfo = SP.getUserInfo(this);
if (userInfo!=null){
name.setText(userInfo.get("number"));
password.setText(userInfo.get("password"));
}
}
private void initView() {
button = (Button) findViewById(R.id.button);
name=(EditText) findViewById(R.id.name);
password=(EditText)findViewById(R.id.password);
button.setOnClickListener(this);
}
public void onClick(View v){
String number = name.getText().toString().trim();
String passwords = password.getText().toString();
if(TextUtils.isEmpty(number)){
Toast.makeText(this,"输入账号",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(passwords)){
Toast.makeText(this,"输入密码",Toast.LENGTH_LONG).show();
return;
}
Toast.makeText(this,"登录成功",Toast.LENGTH_LONG).show();
//boolean isSaveSucess = File.saveUserInfo(this, number, passwords);
boolean isSaveSucess = SP.saveUserInfo(this, number, passwords);
if (isSaveSucess){
Toast.makeText(this,"保存成功",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this,"保存失败",Toast.LENGTH_LONG).show();
}
}
}
本文由 Bigbo 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Jun 2, 2020 at 06:59 pm