在我的活动中,我有editText的(用户名,名字,姓氏和电子邮件地址)。当用户输入现有用户名时,他可以通过单击搜索按钮进行搜索,并且用户拥有的数据将显示在editText中。
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;
}
但是当用户单击搜索按钮并且没有输入用户名EditText中的任何字符时,我在DatabaseHandler中遇到CursorIndexOutOfBoundsException
错误:ConsUserRegistration search = new ConsUserRegistration(cursor.getString(0 ),cursor.getString(1),cursor.getString(2),cursor.getString(3));
此外,我无法从数据库中检索数据,因为它正在崩溃。
答案 0 :(得分:1)
更改
db.searchUser(searchableUser);
ConsUserRegistration consUserRegistration = new ConsUserRegistration();
到
ConsUserRegistration consUserRegistration = db.searchUser(searchableUser);
答案 1 :(得分:-2)
按钮按钮_搜索(按钮)findViewById(r.I'd.itsIdInYourXml);
按钮可能需要声明或定义,还需要查看整个代码