How to count row of a table from sqlite database android - android

I want to count rows of a table in android.I used 2 ways but not success & get a warning message
Launch timeout has expired, giving up wake lock!
Activity idle timeout for HistoryRecord{44e26a30 com.india.screen/.CategoryList}
I have tried-
String query="Select count(*) from Holyplace_Tbl";
Using rawQuery
public void countRows(String query) {
Cursor mcursor = assetDatabaseHelper.executeQuery(query);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
System.out.println("NUMBER IN DB: " + icount);
mcursor.close();
}
Using DatabaseUtils
public int countRows(String query)
{
int sometotal = (int) DatabaseUtils.longForQuery(sqliteDatabaseObj, query, null);
return sometotal;
}
AssetDatabaseOpenHelper.class

Try This
private static final String DB_TABLE_PLACES = "Places";
private SQLiteDatabase mDatabase;
private long fetchPlacesCount() {
String sql = "SELECT COUNT(*) FROM " + DB_TABLE_PLACES;
SQLiteStatement statement = mDatabase.compileStatement(sql);
long count = statement.simpleQueryForLong();
return count;
}
See More Here.

Simplest and Efficient way that i found from How to count number of records in sqlite
DatabaseUtils provides Static utility methods for dealing with
databases and Cursors.
int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);
Or:
int numRows = DatabaseUtils.queryNumEntries(db, "table_name");

You can use a simple RawQuery like this:
private SQLiteDatabase mDatabase;
Cursor c = mDatabase.rawQuery("select COLUMN_NAME from TABLE_NAME",null);
int count = c.getCount();
The Cursor.getCount() method returns the number of rows in the cursor, whch in this case would be the number of items you are looking for.

long numRows = DatabaseUtils.queryNumEntries(db, table);

You can get row count as follows:
c = db.rawQuery("SELECT * FROM Your_tabename", null);
int i = c.getCount();

Related

Sqlite Local database is not accurate

I'm developing android application and I'm storing some data in the local database using sqlite. When I save the database from the device file explorer and browse it using DB browser for sqlite it shows many records there which are correct. BUT i have implement a function that count number of records for specific table and it returns 0 which is wrong value.
I'm lost now cause I think the function is correct
public int numOfRecords(String tableName) {
int numOfRecords = 0;
try {
String query = "SELECT COUNT(*) FROM " + tableName ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
numOfRecords = cursor.getInt(0);
}
db.close();
}
catch (Exception ex ) {
Log.d("test" , "In exception");
}
return numOfRecords;
}
Try this code
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
Or
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}

SQLite + android : Select integer to know if it's 0 or 1

i search since few hours how to select an integer column (as a boolean) and know if it's a 0 was insert or a 1 was insert.
I tried like this :
public boolean getLucide(){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT luciditeCarnetreve FROM Carnetreve WHERE luciditeCarnetreve = ?";
db.rawQuery(query, null);
return true;
}
But the problem in my code it's the method return always true so always 1.
How can i get this with cursor ?
public boolean getLucide()
{
int integervalue = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select luciditeCarnetreve from Carnetreve where luciditeCarnetreve = '"+somevalue+"' ",null);
while(c.moveToNext())
{
integervalue = c.getInt(0);//put the number of coloumn nunbering start from 0
}
c.close();
return integervalue > 0 ? true : false ;
}

simple select query arguments passing issue

I am new with android.
I just wanted to take the count of number of rows in table against particular user in DB (uid is column in db).
For this purpose i made following function:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid=?";
Cursor c = ourDB.rawQuery(query,uid);
}
But its giving me error:
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
also want to know how can i be able to return count from this?
Please help me.
you should use this WAY:
public int getCount(int uid)
{
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if(c.getCount()>0)
c.moveToFirst();
do{
int id = c.getInt(0);
}while(c.moveToNext());
}
Try this way
public int getCount(int uid){
try{
String query = "select count(*)'count' from "+TABLE_MESSAGES+ " WHERE uid="+uid+"";
Cursor c = ourDB.rawQuery(query,null);
if (c.moveToFirst()) {
return Integer.parseInt(cursor.getString(0));
}
}catch (Throwable e) {
e.printStackTrace();
}
return 0;
}
change your query to:
String query = "select count(*) from "+TABLE_MESSAGES+ " WHERE uid="+uid;
Cursor c = ourDB.rawQuery(query);
The method rawQuery(String, String[]) in the type SQLiteDatabase is
not applicable for the arguments (String, int)
Clearly states you are passing int instead of expected String[]
Cursor c = ourDB.rawQuery(query,new String[]{ uid });
use the query as :
"SELECT * FROM <DB_NAME> WHERE uid="+uid
and then use the getCount() method on the cursor
like :
Cursor csr = db.rawQuery("above query string here");
int count = csr.getCount();

How to get row count in sqlite using Android?

I am creating task manager. I have tasklist and I want when I click on particular tasklist name if it empty then it goes on Add Task activity but if it has 2 or 3 tasks then it shows me those tasks into it in list form.
I am trying to get count in list. my database query is like:
public Cursor getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
if(cursor!=null && cursor.getCount()!=0)
cursor.moveToNext();
return cursor;
}
In My activity:
list_tasklistname.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
Cursor c = db.getTaskCount(id);
System.out.println(c.getCount());
if(c.getCount()>0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
task = adapter.getItem(position);
int taskList_id = task.getTaskListId();
taskListID.putExtra("TaskList_ID", taskList_id);
startActivity(taskListID);
}
else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
});
db.close();
}
but when I am clicking on tasklist name it is returning 1, bot number of tasks into it.
Using DatabaseUtils.queryNumEntries():
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
Use android.database.DatabaseUtils to get number of count.
public long getTaskCount(long tasklist_Id) {
return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}
It is easy utility that has multiple wrapper methods to achieve database operations.
c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.
public int getTaskCount(long tasklist_Id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.rawQuery(
"SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) }
);
int count = 0;
if(null != cursor)
if(cursor.getCount() > 0){
cursor.moveToFirst();
count = cursor.getInt(0);
}
cursor.close();
}
db.close();
return count;
}
I know it is been answered long time ago, but i would like to share this also:
This code works very well:
SQLiteDatabase db = this.getReadableDatabase();
long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
BUT what if i dont want to count all rows and i have a condition to apply?
DatabaseUtils have another function for this: DatabaseUtils.longForQuery
long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
new String[] { String.valueOf(tasklist_Id) });
The longForQuery documentation says:
Utility method to run the query on the db and return the value in the first column of the first row.
public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
It is performance friendly and save you some time and boilerplate code
Hope this will help somebody someday :)
Change your getTaskCount Method to this:
public int getTaskCount(long tasklist_id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
cursor.moveToFirst();
int count= cursor.getInt(0);
cursor.close();
return count;
}
Then, update the click handler accordingly:
public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
// Get task list id
int tasklistid = adapter.getItem(position).getTaskListId();
if(db.getTaskCount(tasklistid) > 0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
taskListID.putExtra("TaskList_ID", tasklistid);
startActivity(taskListID);
} else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
In order to query a table for the number of rows in that table, you want your query to be as efficient as possible. Reference.
Use something like this:
/**
* Query the Number of Entries in a Sqlite Table
* */
public long QueryNumEntries()
{
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(db, "table_name");
}
Do you see what the DatabaseUtils.queryNumEntries() does? It's awful!
I use this.
public int getRowNumberByArgs(Object... args) {
String where = compileWhere(args);
String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
Cursor c = getWriteableDatabase().rawQuery(raw, null);
try {
return (c.moveToFirst()) ? c.getInt(0) : 0;
} finally {
c.close();
}
}
Sooo simple to get row count:
cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
looking at the sources of DatabaseUtils we can see that queryNumEntries uses a select count(*)... query.
public static long queryNumEntries(SQLiteDatabase db, String table, String selection,
String[] selectionArgs) {
String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : "";
return longForQuery(db, "select count(*) from " + table + s,
selectionArgs);
}
Once you get the cursor you can do
Cursor.getCount()

Get row count from SQLite

I am trying to get a row count from sqlite for my android application but for some reason its always returning Zero even though I have a enough amount of rows in my DB.
Here is the Code:
DatabaseConnector database1 = new DatabaseConnector(getApplicationContext());
int TotalPosts = database1.getIds();
public int getIds()
{
String selectQuery = "SELECT COUNT(Pst_id) AS CountTotal FROM student_posts";
SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
count = c.getColumnIndex("CountTotal");
return count;
}
Thanks.
Try like below:
public int getIds()
{
String selectQuery = "SELECT Pst_id FROM student_posts";
SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
Cursor c = database.rawQuery(selectQuery, null);
c.moveToFirst();
int total = c.getCount();
c.close();
return total;
}
Try c.getCount()..
Reference
Hope this helps..

Categories

Resources