我的活动中有editText的(用户名,名字,姓氏和电子邮件地址),供用户注册。用户有权通过单击搜索按钮来搜索他输入的用户名是否已存在。如果用户名已存在,则将显示与该用户名相关的所有信息,例如用户名。但是,如果用户单击按钮,如果它不存在,我的应用程序崩溃,我收到CursorIndexOutOfBoundsException错误。我该如何调试那个?
MainActivity.java
btn_Search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String searchableUser = txt_User.getText().toString();
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
String searchUser = consUserRegistration.getUser().toString();
String searchFirst = consUserRegistration.getFirstName().toString();
String searchLast = consUserRegistration.getLastName().toString();
String searchEmail = consUserRegistration.getEmail().toString();
txt_User.setText(searchUser);
txt_First.setText(searchFirst);
txt_Last.setText(searchLast);
txt_Email.setText(searchEmail);
}
});
DatabaseHandler.java
public ConsUserRegistration searchUser(String username){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Constants.TABLE_USER, new String[] {Constants.KEY_USER, Constants.KEY_FIRST,
Constants.KEY_LAST, Constants.KEY_EMAIL}, Constants.KEY_USER + " =? ",
new String[] { String.valueOf(username) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
ConsUserRegistration search = new ConsUserRegistration (cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
return search;
}
答案 0 :(得分:1)
所以...如果您的光标为空或没有元素会发生什么?你还在尝试访问它......
尝试类似......
if (cursor != null && cursor.moveToFirst()) {
...
答案 1 :(得分:1)
试试这个:
MainActivity.java
btn_Search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String searchableUser = txt_User.getText().toString();
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
if (consUserRegistration != null){
String searchUser = consUserRegistration.getUser().toString();
String searchFirst = consUserRegistration.getFirstName().toString();
String searchLast = consUserRegistration.getLastName().toString();
String searchEmail = consUserRegistration.getEmail().toString();
txt_User.setText(searchUser);
txt_First.setText(searchFirst);
txt_Last.setText(searchLast);
txt_Email.setText(searchEmail);
}else{
Toast.makeText(getApplicationContext(), "Username Not Found", Toast.LENGTH_LONG).show();
}
}
});
DatabaseHandler.java
public ConsUserRegistration searchUser(String username){
ConsUserRegistration search;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Constants.TABLE_USER, new String[] {Constants.KEY_USER, Constants.KEY_FIRST,
Constants.KEY_LAST, Constants.KEY_EMAIL}, Constants.KEY_USER + " =? ",
new String[] { String.valueOf(username) }, null, null, null);
if (cursor != null && cursor.moveToFirst()){
search = new ConsUserRegistration (cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getString(3));
}else{
search = null;
}
return search;
}