从SQlite Db获取一个元素,App强行关闭

时间:2016-01-26 09:03:48

标签: android sqlite android-sqlite android-query

所以我是SQLite和编程世界的新手。我希望我的应用程序从DB中找到用户名,如果找到,则显示其名称,否则显示未找到。但不知何故,我的searchUname方法强制关闭我的应用程序。

这里是从

调用方法的地方
 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;
}

并且这是我的searchUname方法。

    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 个答案:

答案 0 :(得分:0)

您正在尝试获取未返回的列( 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;
}