cursor.moveToFirst()始终返回false

Joã*_*hin 2 android cursor android-cursor

我在这里搜索了一段时间没有任何帮助我.我想这很简单,我做的事情很愚蠢.所以,我有这个DataBaseHelper创建一个表并在其上放置两个值:

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "db";
    public static final String PROPERTY = "property";
    public static final String VALUE = "value";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE configs (property VARCHAR(15), value VARCHAR(10));");

        ContentValues cv=new ContentValues();

        cv.put(PROPERTY, "registered");
        cv.put(VALUE, "true");
        db.insert("configs", PROPERTY, cv);

        cv.put(PROPERTY, "test");
        cv.put(VALUE, "test");
        db.insert("configs", PROPERTY, cv);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的活动即时尝试:

@Override
public void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    layout = (LinearLayout) findViewById(R.id.layoutRegister);

    db = (new DatabaseHelper(this)).getWritableDatabase();
    cursor = db.rawQuery("SELECT * FROM configs", 
            null);

    if (cursor.moveToFirst()) {
        debug = new TextView(this);
        debug.setText(cursor.getString(cursor.getColumnIndex("property")));
        layout.addView(debug);
    }
}
Run Code Online (Sandbox Code Playgroud)

它永远不会进入if.此外,当我尝试像cursor.getCount()这样的东西时,我得到一个android.content.res.Resource $ NotFoundException:字符串资源ID#0x0

我想这是一个简单的错误,但是......有什么帮助吗?= S

Moh*_*ikh 6

我理解你想要在光标有值时设置Text,这样你就可以做到这一点......

cursor = db.rawQuery("SELECT * FROM configs", null);

    if (cursor!=null && cursor.getCount()>0) {
        cursor.moveToFirst();
        debug = new TextView(this);
        debug.setText(cursor.getString(cursor.getColumnIndex("property")));
        layout.addView(debug);
    }
Run Code Online (Sandbox Code Playgroud)

而且

when I try something like cursor.getCount() I get a android.content.res.Resource$NotFoundException: String resource ID #0x0
Run Code Online (Sandbox Code Playgroud)

这是因为当你使用TextView的setText()时,所以如果你将参数作为Integer传递,那么它将在R.class文件中查找,所以如果你想将文本设置为整数,你可以做类似......

debug.setText(""+cursor.getCount());
Run Code Online (Sandbox Code Playgroud)

要么

 debug.setText(String.valueOf(cursor.getCount()));
Run Code Online (Sandbox Code Playgroud)