我想检查输入的用户名是否已存在于我的数据库中。如果没有,那么加起来到数据库。如果存在用户名,我创建了能够给出正确结果的函数。问题是当我输入我的数据库中不存在的名称时,应用程序停止。当我输入一个存在于数据库中的名称时,它就像我一样。 请告诉我为什么应用程序会停止。
我使用此查询选择数据库
// Check if user already exist or not
public Cursor isAlreadyExist(String name){
Cursor cursor = null;
SQLiteDatabase db = this.getWritableDatabase();
cursor = db.rawQuery("SELECT " + NAME_USER + " FROM " + TABLE_USER
+ " WHERE " + NAME_USER + "=" + name, null);
return cursor;
}
从数据库获取用户名的函数,
// Check if user already exist
public String isAlreadyExist(String name) {
Cursor cursor = db.isAlreadyExist(name);
cursor.moveToFirst();
String names = cursor.getString(cursor.getColumnIndex(db.NAME_USER));
return names;
}
使用此功能,
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String name = username.getText().toString();
if(name.equals(isAlreadyExist(name))){
//db.addNewUser(username.getText().toString(), util.computeSHAHash(password.getText().toString()));
Toast.makeText(MainActivity.this, "already", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "User not exist", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:2)
问题在于 cursor.moveToFirst(); 当游标为空时,需要检查游标大小是否大于零然后我们需要moveToFirst。更新此方法并检查。
从数据库获取用户名的函数,
public String isAlreadyExist(String name)
{
String names = "";
Cursor cursor = db.isAlreadyExist(name);
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
names = cursor.getString(cursor.getColumnIndex(db.NAME_USER));
}
return names;
}
答案 1 :(得分:0)
1. 在使用moveToFirst()函数之前检查游标是否为空
2. 初始化字符串
编写此功能
public String isAlreadyExist(String name) {
Cursor cursor = db.isAlreadyExist(name);
cursor.moveToFirst();
String names = cursor.getString(cursor.getColumnIndex(db.NAME_USER));
return names;
}
作为
public String isAlreadyExist(String name) {
Cursor cursor = db.isAlreadyExist(name);
String names="";
if(cursor!=null){
cursor.moveToFirst();
names = cursor.getString(cursor.getColumnIndex(db.NAME_USER));
}else{
names = "User does not exist";
}
return names;
}