所以我是SQLite和编程世界的新手。我希望我的应用程序从数据库中找到用户名,如果找到,则显示它的名称,否则显示未找到。但不知何故,我的搜索Uname方法正在强制关闭我的应用程序。
这是调用该方法的位置
else if (v.getId() == R.id.bsubmit){
EditText xa = (EditText)findViewById(R.id.et1);
String stru = xa.getText().toString();
String user = helper.searchUname(stru);
if (user.equals(stru)){
TextView tv = (TextView)findViewById(R.id.tv4);
tv.setText(user);
}
else{
TextView tv = (TextView)findViewById(R.id.tv4);
tv.setText("not found");
}
}
这是我的数据库
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_UNAME = "uname";
private static final String COLUMN_PASS = "pass";
private static final String COLUMN_POINT = "pnt";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"uname text not null , pass text not null , pnt integer not null );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
这是我的搜索Uname方法。
public String searchUname (String stru){
db = this.getReadableDatabase();
String query = "select uname from "+TABLE_NAME;
Cursor c = db.rawQuery(query , null);
String a = "not found";
String b;
c.moveToFirst();
do{
b = c.getString(1);
if (b.equals(stru)){
a = b;
break;
}
}
while (c.moveToNext());
return a;
}
您正在尝试获取未返回的列 (1)
b = c.getString(1);
您只返回 1 列,因此您可以像这样检索它:
b = c.getString(0);
由于列索引从 0 开始
更好的是,按名称而不是按索引检索列:
b = c.getString(c.getColumnIndex("uName"));
[编辑]
您可以像这样改进方法逻辑:
public String searchUname (String stru)
{
db = this.getReadableDatabase();
String query = "select uname from " + TABLE_NAME + " WHERE uname = '" + stru + "'";
Cursor c = db.rawQuery(query , null);
String a = "not found";
if c.moveToFirst();
{
a = c.getString(c.getColumnIndex("uName"));
}
return a;
}