Android登录按钮点击崩溃排查:SharedPreferences代码错误修复
问题排查与修复方案
崩溃核心原因
- SharedPreferences键名拼写错误:注册时存储密码使用的键是
"password",但登录读取时误写为"passowrd"(多了一个字母o),导致读取到的密码为null。调用String.contains(null)会直接抛出NullPointerException,引发应用崩溃。 - 空值未处理+逻辑判断错误:若用户未注册就登录,读取到的用户名/密码会是
null,直接调用字符串匹配方法会触发空指针;同时用contains判断登录逻辑不合理(比如输入"test"能匹配存储的"test123"),应该用完全匹配校验。
修复后的登录模块代码
package com.example.newshrd; 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; import android.widget.Toast; public class login extends AppCompatActivity { EditText editText1; EditText editText2; Button button2; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); editText1 = findViewById(R.id.userlog); editText2 = findViewById(R.id.passwordlog); button2 = findViewById(R.id.btnlog); sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE); } public void onloghere(View view){ String userInput = editText1.getText().toString().trim(); String passInput = editText2.getText().toString().trim(); // 修正键名,读取正确的存储数据 String savedUser = sharedPreferences.getString("username", null); String savedPass = sharedPreferences.getString("password", null); // 先判断是否存在注册数据,再执行匹配校验 if (savedUser != null && savedPass != null) { if (userInput.equals(savedUser) && passInput.equals(savedPass)) { Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "请先注册账号", Toast.LENGTH_SHORT).show(); } } }
额外优化建议
- 变量命名规范化:比如将
userlog改为userInput,提升代码可读性。 - 输入内容去空格:调用
trim()去除输入前后的空格,避免用户误输入空格导致登录失败。 - 注册模块增加校验:判断用户名/密码是否为空,避免存储无效的空字符串。
内容的提问来源于stack exchange,提问作者zaid tahir
相关产品推荐
相关产品推荐

