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;
}
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;
}
I would like to check whether a record exists or not.
Here is what I've tried:
MainActivity.class
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Ontext changed " + new String(s.toString()));
strDocumentFrom = s.toString();
if(s.toString().isEmpty()){
} else {
try{
strTransactionDate = dbHelper.getTransactionDateByDocumentNumber(strDocumentFrom);
//strTotalAmount = dbHelper.getTotalAmountByDocumentNumber(strDocumentFrom);
//strVan = dbHelper.getVanByDocumentNumber(strDocumentFrom);
//etTransactionDate.setText(strTransactionDate);
//etTotalAmount.setText(strTotalAmount);
//Log.d("Van", "" + strVan);
//etVan.setText(strVan);
} catch (SQLiteException e) {
e.printStackTrace();
Toast.makeText(ReceivingStocksHeader.this,
"Document number does not exist.", Toast.LENGTH_SHORT).show();
}
}
DBHelper.class
// TODO DISPLAYING RECORDS TO TRANSRCVHEADER
public String getTransactionDateByDocumentNumber(String strDocumentNumber){
String[] columns = new String[]{KEY_TRANSACTIONDATE};
Cursor c = myDataBase.query(TBL_INTRANS,
columns, null,
null, null, null, null, null);
if(c != null){
c.moveToFirst();
String date = c.getString(0);
return date;
} else {
Log.d("Error", "No record exists");
}
return null;
}
But it doesn't get it to the catch block to display the toast.
What am I doing wrong in here?
public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
I hope this is useful to you...
This function returns true if record already exists in db. Otherwise returns false.
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally: You can get an error when searching by String that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40". Those dashes (-) will cause an unrecognized token error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
Raw queries are more vulnerable to SQL Injection. I will suggest using query() method instead.
public boolean Exists(String searchItem) {
String[] columns = { COLUMN_NAME };
String selection = COLUMN_NAME + " =?";
String[] selectionArgs = { searchItem };
String limit = "1";
Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null, limit);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
Source: here
SELECT EXISTS with LIMIT 1 is much faster.
Query Ex: SELECT EXISTS (SELECT * FROM table_name WHERE column='value' LIMIT 1);
Code Ex:
public boolean columnExists(String value) {
String sql = "SELECT EXISTS (SELECT * FROM table_name WHERE column='"+value+"' LIMIT 1)";
Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();
// cursor.getInt(0) is 1 if column with value exists
if (cursor.getInt(0) == 1) {
cursor.close();
return true;
} else {
cursor.close();
return false;
}
}
You can use SELECT EXISTS command and execute it for a cursor using a rawQuery,
from the documentation
The EXISTS operator always evaluates to one of the integer values 0
and 1. If executing the SELECT statement specified as the right-hand
operand of the EXISTS operator would return one or more rows, then the
EXISTS operator evaluates to 1. If executing the SELECT would return
no rows at all, then the EXISTS operator evaluates to 0.
I have tried all methods mentioned in this page, but only below method worked well for me.
Cursor c=db.rawQuery("SELECT * FROM user WHERE idno='"+txtID.getText()+"'", null);
if(c.moveToFirst())
{
showMessage("Error", "Record exist");
}
else
{
// Inserting record
}
One thing the top voted answer did not mention was that you need single quotes, 'like this', around your search value if it is a text value like so:
public boolean checkIfMyTitleExists(String title) {
String Query = "Select * from " + TABLE_NAME + " where " + COL1 + " = " + "'" + title + "'";
Cursor cursor = database.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Otherwise, you will get a "SQL(query) error or missing database" error like I did without the single quotes around the title field.
If it is a numeric value, it does not need single quotes.
Refer to this SQL post for more details
SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.
if(cursor.getCount()<=0){
Log.v("tag","if 1 "+cursor.getCount());
return false;
}
Log.v("tag","2 else "+cursor.getCount());
return true;
if you not use cursor.moveToLast();
cursor.getCount() always give same integer (1) or current position of cursor.
Code :
private String[] allPushColumns = { MySQLiteHelper.COLUMN_PUSH_ID,
MySQLiteHelper.COLUMN_PUSH_TITLE, MySQLiteHelper.COLUMN_PUSH_CONTENT, MySQLiteHelper.COLUMN_PUSH_TIME,
MySQLiteHelper.COLUMN_PUSH_TYPE, MySQLiteHelper.COLUMN_PUSH_MSG_ID};
public boolean checkUniqueId(String msg_id){
Cursor cursor = database.query(MySQLiteHelper.TABLE_PUSH,
allPushColumns, MySQLiteHelper.COLUMN_PUSH_MSG_ID + "=?", new String [] { msg_id }, null, null, MySQLiteHelper.COLUMN_PUSH_ID +" DESC");
if(cursor.getCount() <= 0){
return false;
}
return true;
}
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
because of possible data leaks best solution via cursor:
Cursor cursor = null;
try {
cursor = .... some query (raw or not your choice)
return cursor.moveToNext();
} finally {
if (cursor != null) {
cursor.close();
}
}
1) From API KITKAT u can use resources try()
try (cursor = ...some query)
2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'
3) dont use moveToFirst() is used when you need to start iterating from beggining
4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.
Try to use cursor.isNull method.
Example:
song.isFavorite = cursor.isNull(cursor.getColumnIndex("favorite"));
You can use like this:
String Query = "Select * from " + TABLE_NAME + " where " + Cust_id + " = " + cust_no;
Cursor cursorr = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursorr.close();
}
cursor.close();
private boolean checkDataExistOrNot(String columnName, String value) {
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String query = "SELECT * FROM" + TABLE_NAME + " WHERE " + columnName + " = " + value;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false; // return false if value not exists in database
}
cursor.close();
return true; // return true if value exists in database
}
I prefer to do it this way because it's fast and less expensive than other methods:
Cursor cursor = db.rawQuery("SELECT 1 FROM table WHERE condition = 1 LIMIT 1", null);
try {
if (cursor.moveToNext()) {
//Record exists
} else {
//Record doesn't exists
}
} finally {
cursor.close();
}
My version:
public boolean isTitleExists(String title, String type) {
int isExists = 0;
try {
String query = "SELECT EXISTS (SELECT 1 FROM titles WHERE title = ? and type = ?)";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, title);
statement.setString(2, type);
ResultSet rs = statement.executeQuery();
rs.next();
isExists = rs.getInt(1);
rs.close();
statement.close();
} catch (SQLException e) {
Common.console("isTitleExists error: " + e.getMessage());
}
return isExists == 1;
}
In my application i am showing data from database in a table view.My requirement is that from database i have to retrieve the data which will fall in the current month.I Have written the query but it is coming as 0.Actually i have 1 entry in the database with today's date,so my query should return that data,but it is showing as 0.Please help me.Thanks in advance.
My query is as follows:
public String addgroupincome(String grp) throws SQLException
{
long sum=0;
Cursor cursor1 = db.rawQuery(
"SELECT SUM("+(KEY_TOTAL)+") FROM incomexpense WHERE date= Strftime('%Y-%m','now') AND category='Income' AND groups='"+grp+"'",null);
if(cursor1.moveToFirst())
{
sum = cursor1.getLong(0);
}
cursor1.close();
String housetotal=String.valueOf((long)sum);
return housetotal;
}
I am getting that total and showing in atextview in table layout..
final String houtotal=db.addgroupincome(group1);
housetotal.setText(houtotal);
Most probably nothing wrong with the query but the way you pass the query result to ListView. Can you show how you do it? Perhaps I could help.
Or you could take a look here or here
public int getCount() {
DBHelper dbHelper = DBHelper.getDBAdapterInstance(this);
int count = 0;
try {
dbHelper.openDataBase();
String query = "select count(1) from t_model where upper(brandName) = upper('"
+ selectedBrand + "') order by modelName ASC";
Cursor cursor = dbHelper.selectRecordsCursor(query, null);
if (cursor.moveToFirst()) {
count = cursor.getInt(0);
}
cursor.close();
cursor = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
return count;
}
and for the TextView should be as simple as
TextView tvCount = (TextView) findViewById(R.id.tvCount);
tvCount.setText("Count : " + getCount);
If you are having trouble debugging your query. Try http://sqlitebrowser.sourceforge.net/ or http://www.sqliteexpert.com/
Why don't you try by giving column names of your table in your query..might it work out for you..specify the columns which you want to retrive..
if (cursor.moveToNext()) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
Log.i(ID, cursor.getInt(0) + "");
cursor.moveToNext();
}
cursor.close();
} else {
cursor.close();
return null;
}
Try This Method....
Is there a nice way in Android to see if a column exists in a table in the application database? (I know there are questions similar to this one already, but there don't seem to be any that are Android specific.)
cursor.getColumnIndex(String columnName) returns -1 if, the column doesn't exist. So I would basically perform a simple query like "SELECT * FROM xxx LIMIT 0,1" and use the cursor to determine if the column, you are looking for, exists
OR
you can try to query the column "SELECT theCol FROM xxx" and catch an exception
My function based on #martinpelants answer:
private boolean existsColumnInTable(SQLiteDatabase inDatabase, String inTable, String columnToCheck) {
Cursor mCursor = null;
try {
// Query 1 row
mCursor = inDatabase.rawQuery("SELECT * FROM " + inTable + " LIMIT 0", null);
// getColumnIndex() gives us the index (0 to ...) of the column - otherwise we get a -1
if (mCursor.getColumnIndex(columnToCheck) != -1)
return true;
else
return false;
} catch (Exception Exp) {
// Something went wrong. Missing the database? The table?
Log.d("... - existsColumnInTable", "When checking whether a column exists in the table, an error occurred: " + Exp.getMessage());
return false;
} finally {
if (mCursor != null) mCursor.close();
}
}
Simply call:
boolean bla = existsColumnInTable(myDB,"MyTable","myColumn2check");
I actually wrote this function that seems pretty clean:
private boolean field_exists( String p_query )
{
Cursor mCursor = mDb.rawQuery( p_query, null );
if ( ( mCursor != null ) && ( mCursor.moveToFirst()) )
{
mCursor.close();
return true ;
}
mCursor.close();
return false ;
}
I call it like this:
if ( field_exists( "select * from sqlite_master "
+ "where name = 'mytable' and sql like '%myfield%' " ))
{
do_something ;
}
Here is my solution to the issue which adds to flexo's solution a little.
You can put this method in any class, perhaps your SQLiteOpenHelper extending class.
public static boolean columnExistsInTable(SQLiteDatabase db, String table, String columnToCheck) {
Cursor cursor = null;
try {
//query a row. don't acquire db lock
cursor = db.rawQuery("SELECT * FROM " + table + " LIMIT 0", null);
// getColumnIndex() will return the index of the column
//in the table if it exists, otherwise it will return -1
if (cursor.getColumnIndex(columnToCheck) != -1) {
//great, the column exists
return true;
}else {
//sorry, the column does not exist
return false;
}
} catch (SQLiteException Exp) {
//Something went wrong with SQLite.
//If the table exists and your query was good,
//the problem is likely that the column doesn't exist in the table.
return false;
} finally {
//close the db if you no longer need it
if (db != null) db.close();
//close the cursor
if (cursor != null) cursor.close();
}
}
If you use ActiveAndroid
public static boolean createIfNeedColumn(Class<? extends Model> type, String column) {
boolean isFound = false;
TableInfo tableInfo = new TableInfo(type);
Collection<Field> columns = tableInfo.getFields();
for (Field f : columns) {
if (column.equals(f.getName())) {
isFound = true;
break;
}
}
if (!isFound) {
ActiveAndroid.execSQL("ALTER TABLE " + tableInfo.getTableName() + " ADD COLUMN " + column + " TEXT;");
}
return isFound;
}
At the risk of just posting the same solution but shorter. Here's a cut down version based on #flexo's
private boolean doesColumnExistInTable(SupportSQLiteDatabase db, String tableName, String columnToCheck) {
try (Cursor cursor = db.query("SELECT * FROM " + tableName + " LIMIT 0", null)) {
return cursor.getColumnIndex(columnToCheck) != -1;
} catch (Exception Exp) {
// Something went wrong. we'll assume false it doesn't exist
return false;
}
}
And in Kotlin
private fun doesColumnExistInTable(db: SupportSQLiteDatabase, tableName: String, columnToCheck: String): Boolean {
try {
db.query("SELECT * FROM $tableName LIMIT 0", null).use { cursor -> return cursor.getColumnIndex(columnToCheck) != -1 }
} catch (e: Exception) {
// Something went wrong. we'll assume false it doesn't exist
return false
}
}
this is my testing code:
String neadle = "id"; //searched field name
String tableName = "TableName";
boolean found = false;
SQLiteDatabase mDb = ActiveAndroid.getDatabase();
Cursor mCursor = mDb.rawQuery( "SELECT * FROM sqlite_master WHERE name = '"+tableName+"' and sql like '%"+neadle+"%'" , null);
mCursor.moveToFirst();
String fie = ",";
if (mCursor.getCount() > 0) {
String[] fields = mCursor.getString(mCursor.getColumnIndex("sql")).split(",");
for (String field: fields) {
String[] fieldNameType = field.trim().split(" ");
if (fieldNameType.length > 0){
fie += fieldNameType[0]+",";
}
}
}else {
//table not exist!
}
if (mCursor != null) mCursor.close();
// return result:
found = fie.contains(","+neadle+",");