Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android sqlite how to check if a record exists

Tags:

android

sqlite

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?

like image 925
neknek mouh Avatar asked Dec 06 '13 03:12

neknek mouh


People also ask

How do you check if data exists in a table sqlite?

SELECT EXISTS(SELECT 1 FROM myTbl WHERE u_tag="tag" LIMIT 1); Selecting 1 is the accepted practice if you don't need something from the record, though what you select shouldn't really matter either way. Put an index on your tag field. If you do not, a query for a non-existent tag will do a full table scan.


2 Answers

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.

like image 200
dipali Avatar answered Oct 13 '22 00:10

dipali


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; } 
like image 35
Chad Bingham Avatar answered Oct 12 '22 23:10

Chad Bingham