android get count total rows?

时间:2014-05-08 07:32:21

标签: android sqlite

如果有人帮助我使用以下代码,我将不胜感激:

我试图在我的表格中获取总行数:我从按钮调用但它总是崩溃......

public int countjournals() {
        Cursor dataCount = CountryDB.rawQuery("select count(*) from" + TABLE_NAME, null);
        dataCount.moveToFirst();
        int jcount = dataCount.getInt(0);
        dataCount.close();

        Toast.makeText(getApplicationContext(), 
                        "Total:", Toast.LENGTH_LONG).show();
        return jcount;
    }

我在CountyDB中创建了这样的方法:

 public static Cursor rawQuery(String string, Object object) {
    // TODO Auto-generated method stub
    return null;
}

提前致谢

3 个答案:

答案 0 :(得分:1)

首先,您需要实施rawQuery()或删除它。你想要的是SQLiteDatabase' rawQuery()

此外,您需要from和表名之间的空格:

"select count(*) from" + TABLE_NAME

更改为:

"select count(*) from " + TABLE_NAME

答案 1 :(得分:0)

理想情况下,如果不是,它应该有效.... 每次看到

时,rawQuery方法都会返回null
 public static Cursor rawQuery(String string, Object object) {
    // TODO Auto-generated method stub
    return null;
}

答案 2 :(得分:-1)

private int getCount(){
            int count = 0;
            String query = "SELECT * FROM "+"Table_Name";
            Cursor cursor = CountryDB.rawQuery(query, null);

            while(!cursor.isAfterLast()){
                cursor.moveToFirst();

                while (!cursor.isAfterLast()) {
                    int x = cursor.getInt(0);
                    Log.e("", "x = "+x);
                    count++;
                    cursor.moveToNext();
                }
            }

            cursor.close();
            CountryDB.close();

            return count;
        }

确保数据库对象不为null,并且首先创建表,列数据类型为整数。如果您要输入字符串数据,请使用getString(0);

这段代码对我来说很好。