Sqlite Local database is not accurate - android

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;
}

Related

CursorIndexOutOfBoundException: Index -1 requested, with a size of 1

How do i do a select statement which retrieves 2 String and 1 integer value. I am receiving this error. My app keep crashing at cursor.getString(0); In my log, i do get this message Log.d("TAG","Row found");
Login.java
private void getQRCodeInformation(){
//database helper object
DatabaseHelper db;
//initializing views and objects
db = new DatabaseHelper(this);
Cursor cursor = db.getQRCodeInformation();
if(cursor.getCount() == 0) {
Log.d("TAG","Nothing found");
}
else{
Log.d("TAG","Row found");
if(cursor != null && cursor.moveToFirst()){
//cursor.getString(0);
//cursor.getString(1);
//cursor.getInt(1);
Log.d("TAG","Data found");
}
}
}
DatabaseHelper.java
public Cursor getQRCodeInformation(){
SQLiteDatabase db = this.getReadableDatabase();
String sql = "SELECT "+COLUMN_0_UserDetail+" , "+COLUMN_4_UserDetail+" , "+COLUMN_5_UserDetail+ " FROM "+ TABLE_NAME_UserDetail;
Cursor c = db.rawQuery(sql, null);
return c;
}
you just need to get index of column
int index = cursor.getColumnIndex(COLUMN_NAME);
then
String columnValue = cursor.getString(index);
Good luck :)

How to prevent app crashed after delete empty database

i had been trying to prevent accidentally click on delete button when the data base is empty. It will crash after click.
Database handler
public void deleteLastMessage(Class a) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_MSG + " = ?",
new String[] { String.valueOf(a.get_message()) });
db.close();
}
public String getLastString() {
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
LastString = cursor.getString(0);
cursor.close();
db.close();
return LastString;
}
Activity
public void deleteMessage(View v) {
LastMessage = new SubliminalClass(db.getLastString());
db.deleteLastMessage(LastMessage);
It work fine when there are data to delete, it crashed when there is no data.
My data is a column of string.
Referred to this Application crashes while reading an empty table in android but to no avail.
I have tried this below but still crashed when there is no data.
public boolean checkdb(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Boolean rowExists;
String nullString="";
if (nullString.equals(getLastString())) //todo change this
// DO SOMETHING WITH CURSOR
rowExists = false;
else
{
// I AM EMPTY
rowExists = true;
}
return rowExists;
}
Anyone can help me solve this?
Try this
Check the table row count is greater than zero then do the delete operation.
//Add in your activity
int rowCount = db.getRowCount();
db.close();
if(rowCount>0)
{
db.deleteLastMessage(LastMessage);
}else{
}
//Add in DBhelperClass
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteLastMessage(Class a) {
try{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_MSG + " = ?",
new String[] { String.valueOf(a.get_message()) });
db.close();
} catch (Exception e){
e.printStackTrace();
}
}
You could add try/catch around your delete code.
Also the checkdb function could be like this
public boolean checkdb(){
SQLiteDatabase db = this.getReadableDatabase();
Log.d(TAG,"Got Readable DB")
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Boolean rowExists = false;
String nullString="";
if(mCursor != null){
Log.d(TAG,"Cursor is not null")
try{
rowExists = mCursor.getCount() > 0;
Log.d(TAG,"rowExists is " + rowExists);
mCursor.close();
} catch (Exception e){
e.printStackTrace();
}
}
return rowExists;
}

Cursor Index Out Of Bounds Exception - Android SQLite

I'm attempting to query my SQLite database but I'm getting the error "Cursor Index Out Of Bounds Exception: Index 0 requested, with a size of 0". When I run the same query in SQLite Man, I get the result I'm looking for.
public int getHighScore () {
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
int score = cursor.getInt(0);
cursor.close();
return score;
}
Please check if cursor is not null then you want to fetch record from cursor.Use this line to fetch record:
cursor.getInt(cursor.getColumnIndex("score")))
use this code :
public int getHighScore () {
int score=0;
String query = "SELECT score FROM " + SCORE_TABLE + ";";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor != null && cursor.moveToFirst()) {
score = cursor.getInt(cursor.getColumnIndex("score")));
}
cursor.close();
return score;
}

Sqlite Check if Table is Empty [duplicate]

This question already has answers here:
How can i check to see if my sqlite table has data in it?
(13 answers)
Closed 4 years ago.
Well, I have a databse and it has lots of table. but generally tables are empty.
I want check if a database table is empty.
IF table is empty, program will fill it.
public static long queryNumEntries (SQLiteDatabase db, String table)
I will use it but it requre API 11.
you can execute select count(*) from table and check if count> 0 then leave else populate it.
like
SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave
else
//populate table
Do a SELECT COUNT:
boolean empty = true
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM YOURTABLE", null);
if (cur != null && cur.moveToFirst()) {
empty = (cur.getInt (0) == 0);
}
cur.close();
return empty;
public boolean isEmpty(String TableName){
SQLiteDatabase database = this.getReadableDatabase();
long NoOfRows = DatabaseUtils.queryNumEntries(database,TableName);
if (NoOfRows == 0){
return true;
} else {
return false;
}
}
Optimal Solutions
public boolean isMasterEmpty() {
boolean flag;
String quString = "select exists(select 1 from " + TABLE_MASTERS + ");";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(quString, null);
cursor.moveToFirst();
int count= cursor.getInt(0);
if (count ==1) {
flag = false;
} else {
flag = true;
}
cursor.close();
db.close();
return flag;
}
Here is a better option:
public boolean validateIfTableHasData(SQLiteDatabase myDatabase,String tableName){
Cursor c = myDatabase.rawQuery("SELECT * FROM " + tableName,null);
return c.moveToFirst();
}
This is how you can do it -
if(checkTable("TABLE"))
{
//table exists fill data.
}
Method to check table -
public static boolean checkTable(String table) {
Cursor cur2 = dbAdapter.rawQuery("select name from sqlite_master where name='"
+ table + "'", null);
if (cur2.getCount() != 0) {
if (!cur2.isClosed())
cur2.close();
return true;
} else {
if (!cur2.isClosed())
cur2.close();
return false;
}
}
I think, this solution is better:
boolean flag;
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext(), DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION);
try {
sqLiteDatabase = databaseHelper.getWritableDatabase();
} catch (SQLException ex) {
sqLiteDatabase = databaseHelper.getReadableDatabase();
}
String count = "SELECT * FROM table";
Cursor cursor = sqLiteDatabase.rawQuery(count, null);
if (cursor.moveToFirst()){
flag = false;
} else {
flag = true;
}
cursor.close();
sqLiteDatabase.close();
return flag;
moveToFirst() check table and return true, if table is empty. Answer that is marked correct - uses extra check.

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()

Categories

Resources