我一直试图制作一个登录应用。这是LoginActivity
:
public class LoginActivity extends AppCompatActivity {
EditText UsernameLogin, PasswordLogin;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
public static Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_login_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void loginUser(View view) {
UsernameLogin = (EditText) findViewById(R.id.insert_username);
PasswordLogin = (EditText) findViewById(R.id.insert_password);
String Username = UsernameLogin.getText().toString();
String Password = PasswordLogin.getText().toString();
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getUsername(Username, sqLiteDatabase);
if(cursor.getCount() != 0) {
if(cursor.getString(3).equals(Password)) {
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
Toast.makeText(this, "Login successful!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this, "Wrong Password", Toast.LENGTH_SHORT).show();
PasswordLogin.setText("");
}
} else {
Toast.makeText(this, "Username does not exist", Toast.LENGTH_SHORT).show();
UsernameLogin.setText("");
PasswordLogin.setText("");
}
}
}
这是getUsername
内的UserDbHelper
方法:
public Cursor getUsername (String username, SQLiteDatabase db) {
String[] projections = {UserContract.NewUserInfo.FIRST_NAME, UserContract.NewUserInfo.LAST_NAME,
UserContract.NewUserInfo.USER_PASSWORD, UserContract.NewUserInfo.USER_EMAIL};
String selection = UserContract.NewUserInfo.USER_NAME + " LIKE ?";
String[] selection_args = {username};
Cursor cursor = db.query(UserContract.NewUserInfo.TABLE_NAME, projections, selection, selection_args, null, null, null);
return cursor;
}
这会导致我的应用崩溃。如果我用字符串替换cursor.getString(3)
,则应用程序可以正常运行。
答案 0 :(得分:1)
不要使用魔法数字。 Cursor有方法getColumnIndex
例如
cursor.getString(cursor.getColumnIndex(UserContract.NewUserInfo.USER_PASSWORD));
并且忘记在查询之前忘记致电cursor.moveToFirst()