Check if values exits in database - android

I want to check if a couple of values exists in the database. If they do, the method should return TRUE or FALSE if the cursor is null. But the problem is that it returns TRUE all the time despite the values are not in the database! What have I missed?
// This method check if the combination image path and contact name already exists in database
public boolean checkContentDatabase(String imageFilePath, String contactName) {
String query = "Select * from " + DB_TABLE+ " where " + TABLE_IMAGE_PATH + "='" + imageFilePath + "' and " + TABLE_CONTACT_NAME + "='" + contactName +"' ;";
Cursor c = db.rawQuery(query, null);
if(c != null) // Exists in database
{
return true;
}
else
{
return false;
}
}

Replace your if condition with:
if(c.getCount() > 0)
{
return true;
}
else
{
return false;
}

use c != null && c.getCount() > 0 instead of c != null

public boolean checkContentDatabase(String imageFilePath, String contactName) {
String query = "Select * from " + DB_TABLE+ " where " + TABLE_IMAGE_PATH + "='" + imageFilePath + "' and " + TABLE_CONTACT_NAME + "='" + contactName +"' ;";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.isAfterLast() == false) {
return true;
}
else
{
return false;
}
}

The cursor is not null, because its been created successfully. Only your result set does not exist. Try using "SELECT 1 FROM..." and then check if the result equals 1.

Related

My function always return false SqlCipher

I use database to encrytp/decypt sqlcipher. Now I write function witch check if this card if exist in table Card. When I debug my method always return false.
public boolean checkIfExistCard(String numberCard, String expirationDate) {
net.sqlcipher.database.SQLiteDatabase db = this.getReadableDatabase(DATABASE_PASSWORD);
Cursor cursor = db.query(CardColumn.CardEntry.TABLE_CARD,
new String[]{CardColumn.CardEntry.CARD_NUMBER, CardColumn.CardEntry.CARD_EXPIRATION_DATA},
CardColumn.CardEntry.CARD_NAME + " = ? and " + CardColumn.CardEntry.CARD_EXPIRATION_DATA + " = ?",
new String[]{numberCard, expirationDate},
null, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.close();
db.close();
return true;
}
cursor.close();
db.close();
}
return false;
}
public boolean checkIfExistCard(String numberCard, String expirationDate) {
boolean isAvailable=false;
net.sqlcipher.database.SQLiteDatabase db = this.getReadableDatabase(DATABASE_PASSWORD);
Cursor cursor = db.query(CardColumn.CardEntry.TABLE_CARD,
new String[]{CardColumn.CardEntry.CARD_NUMBER, CardColumn.CardEntry.CARD_EXPIRATION_DATA},
CardColumn.CardEntry.CARD_NAME + " = ? and " + CardColumn.CardEntry.CARD_EXPIRATION_DATA + " = ?",
new String[]{numberCard, expirationDate},
null, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isAvailable=true;
}
else {
isAvailable=false;
}
cursor.close();
db.close();
}
return isAvailable;
}
Maybe you missed a space in your query.
In this line:
CardColumn.CardEntry.CARD_NAME + " = ? and " + CardColumn.CardEntry.CARD_EXPIRATION_DATA + " = ?",
After the last ? sign put a space before the " sign.
I solved my problem :) I make mistake in Cursor should be CardColumn.CardEntry.CARD_NUMBER instead CardColumn.CardEntry.CARD_NAME
It's works :)
Cursor cursor = db.query(CardColumn.CardEntry.TABLE_CARD,
new String[]{CardColumn.CardEntry.CARD_NUMBER, CardColumn.CardEntry.CARD_EXPIRATION_DATA},
CardColumn.CardEntry.CARD_NUMBER + " = ? and " + CardColumn.CardEntry.CARD_EXPIRATION_DATA + " = ?",
new String[]{numberCard, expirationDate},
null, null, null, null);

SQL in android dosent work

I want to update a row in a SQL table in a column (`click'). I can see the row in debug but it isn't recognized.
If click==0 so change to click==1.
Does someone know what is my mistake?
My code is:
public void UpdateClicked2(String name, int table) {
ContentValues values = new ContentValues();
String selectQuery = "SELECT * FROM " + MySQLiteGUESTS.TABLE_NAME
+ " WHERE " + MySQLiteGUESTS.COLUMN_TABLE + "=" + table;
Cursor cursor = database.rawQuery(selectQuery, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
GuestInfo comment = cursorToComment(cursor);
if (comment.getName().toString() != name)
cursor.moveToNext();
else {
if (comment.getClick() == 1) {
values.put(MySQLiteGUESTS.COLUMN_CLICK, 0);
} else
values.put(MySQLiteGUESTS.COLUMN_CLICK, 1);
}
}
String newString = MySQLiteGUESTS.COLUMN_NAME + " = " + name;
database.update(MySQLiteHelper.TABLE_NAME, values, newString, null);
}
if (comment.getName().toString() != name)
Instead of this
Use this:
if (comment.getName().toString().equals(name))
{
}

Android sqlite how to check if a record exists

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

Searching SQLite database inside Android app

I got a searching function inside my app.
It works almost properly, my problem is it is only catching results that similiar to the searchWord from the begining.
For example:
If searchWord is "ada", the results will be contains all the records that START WITH "ada" but not those that contains "ada" somewhere inside them.
I know it must be just a little modification but this is the first piece of database handling i ever did.
So how must i modify this to search for any contains, and not for starts with?
code:
public Cursor getMatchingFromContacts(String searchWord) throws SQLException {
String queryString = "SELECT _id, full_name FROM "
+ SF_CONTACT_TABLE;
if (searchWord != null) {
searchWord = searchWord.trim() + "%";
queryString += " WHERE " + FULL_NAME + " LIKE ?";
}
String params[] = { searchWord };
if (searchWord == null) {
params = null;
}
try {
Cursor cursor = db.rawQuery(queryString,
params);
if (cursor != null) {
cursor.moveToFirst();
return cursor;
}
} catch (SQLException e) {
Log.e("AutoCompleteDbAdapter", e.toString());
throw e;
}
return null;
}
Just modify your block here:
if (searchWord != null) {
searchWord = "%" + searchWord.trim() + "%";
queryString += " WHERE " + FULL_NAME + " LIKE ?";
}
Try this..
if (searchWord != null)
{
searchWord = "%" + searchWord + "%";
queryString += " WHERE " + FULL_NAME + " LIKE ?";
}

Finializing a cursor hasnot deactivated

I have created a function in an application that checks for username and password from the database but i get that error
07-02 00:31:09.619: E/Cursor(345): Finalizing a Cursor that has not been deactivated or closed. database = /data/data/sbn.project.gp/databases/users, table = null, query = SELECT name,password FROM users WHERE name='khaled'and password='1234'
here it is my code
public Boolean check(String nameS, String passwordS) {
// TODO Auto-generated method stub
Cursor c = null;
Boolean check = true;
c = ourDatabase.rawQuery("SELECT name,password FROM users WHERE name='"
+ nameS + "'" + "and password='" + passwordS + "'", null);
if (c.getCount() > 0) {
check = false;
return check;
}
c.close();
return check;
}
It's because you didnt close the cursor if check is false , do this instead :
public Boolean check(String nameS, String passwordS) {
Cursor c = null;
Boolean check = true;
c = ourDatabase.rawQuery("SELECT name,password FROM users WHERE name='"
+ nameS + "'" + "and password='" + passwordS + "'", null);
if (c.getCount() > 0) {
check = false;
}
c.close();
return check;
}

Categories

Resources