Reputation: 21
I've been trying to make a Login app. This is 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("");
}
}
}
And this is the getUsername
method inside 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;
}
This crashes my app. If I replace cursor.getString(3)
with a string, the app runs properly.
Upvotes: 0
Views: 970
Reputation: 157467
Don't use magic numbers. Cursor has the method getColumnIndex
E.g.
cursor.getString(cursor.getColumnIndex(UserContract.NewUserInfo.USER_PASSWORD));
and don't forget to call cursor.moveToFirst()
before querying it
Upvotes: 1