Android SQLite查询始终为空

时间:2011-03-27 23:32:22

标签: android sql sqlite

现在我正在我的应用Ship an application with a database

中使用此解决方案

在我的主要活动中,我只是想测试以确保数据库正常工作,所以我只是简单地查询得到一些名字,我所做的就是添加3行(评论我添加了它们):

       DatabaseHelper myDbHelper;
       SQLiteDatabase myDb = null;

       myDbHelper = new DatabaseHelper(this);
       /*
        * Database must be initialized before it can be used. This will ensure
        * that the database exists and is the current version.
        */
        myDbHelper.initializeDataBase();
        Cursor c;
        String s = null;
        try {
           // A reference to the database can be obtained after initialization.
           myDb = myDbHelper.getWritableDatabase();
//the next 3 lines are all I added
           c = myDb.rawQuery("select name from breads", null);
           s = c.getString(1);
           c.close();
           /*
            * Place code to use database here.
            */
        } catch (Exception ex) {
           ex.printStackTrace();
        } finally {
           try {
               myDbHelper.close();
           } catch (Exception ex) {
               ex.printStackTrace();
           } finally {
               myDb.close();
           }
       }

但是,s仍然是空的。如果我在控制台中执行完全相同的查询select name from breads,我将获取数据。有没有人有任何想法?

1 个答案:

答案 0 :(得分:4)

myDb = myDbHelper.getWritableDatabase();
//the next 3 lines are all I added
c = myDb.rawQuery("select name from breads", null);
c.moveToFirst(); // ADD THIS
s = c.getString(1);
c.close();