-1

in database.

public int getCnt() {
    String countQuery = "SELECT * FROM " + TABLE_LOG;
    SQLiteDatabase db = this.getReadableDatabase();    
    Cursor cursor = db.rawQuery(countQuery, null)
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

also tried

 public long getCnt() {
    SQLiteDatabase db = this.getReadableDatabase();
    long cnt = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM " + TABLE_LOG, null);
    return cnt;
}

in main

int x =0; // long for other func..
x = dbh.getCnt();  
 Toast.makeText(getApplicationContext(),String.valueOf(x),Toast.LENGTH_SHORT).show();

    if(x==0){
        //do some stuff
        }
    else{
        //do some other stuff
    }

it works but only when the table has 0 rows, when it encounter any row i dont know what went wrong but app stops ,, and please let me know if any other info is required

Mohit
  • 11
  • 6
  • Check https://developer.android.com/reference/android/database/DatabaseUtils.html#queryNumEntries(android.database.sqlite.SQLiteDatabase, java.lang.String, java.lang.String) – Raghunandan Oct 26 '16 at 17:26
  • 1
    the second snippet needs as space between FROM and " or it will be something like `SELECT COUNT(*) FROMTABLE_LOG` instead of `SELECT COUNT(*) FROM TABLE_LOG` – denispyr Oct 26 '16 at 17:27
  • `long longForQuery (SQLiteDatabase db, String query, String[] selectionArgs)` Utility method to run the query on the db and return the value in the first column of the first row. – Raghunandan Oct 26 '16 at 17:28
  • not working!!!! – Mohit Oct 27 '16 at 03:04

2 Answers2

1

Try something like this.

Cursor cur = db.rawQuery("SELECT SUM(myColumn) FROM myTable", null);

if(cur.moveToFirst())
{
    return cur.getInt(0);
}
Victor Hugo Montes
  • 1,270
  • 1
  • 17
  • 28
  • where to store the returned value and how? and it should get the total number of rows. – Mohit Oct 27 '16 at 03:06
  • 1
    cursor.moveToFirst(); and int count = cursor.getCount(); This two lines are useful to you for get a number of rows in a table. You can return count value for further use. – Kailas Bhakade Oct 27 '16 at 10:01
  • That's exactly what it does. Just remember to replace myColumn and myTable according your needs. The total of rows will be given by cur.getInt(0); – Victor Hugo Montes Oct 27 '16 at 10:32
1

First off, it is very inefficient to load the data in the rows if you simply want the count. You should use queryNumEntries if you want the count.

Shadesblade
  • 782
  • 5
  • 5