0

I want to loop through sqlite database if (johnny) is present in the database or not but my code is not working

if(!cursor.isAfterLast()) 
{
    do 
    {
        for(int i = 0; i<cursor.getCount(); i++)
        {
            if("johnny" == cursor.getString(1))
            { 
                Toast.makeText(getApplicationContext(), "string found!!! =)", Toast.LENGTH_LONG).show();
            }
        }                   
    } 
    while (cursor.moveToNext());
    }       
    cursor.close();
}
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
Jack
  • 151
  • 1
  • 4
  • 21

2 Answers2

5

For comparison use .equals() i.e. change

if("johnny" == cursor.getString(1))

to

if("johnny".equals(cursor.getString(1)))

Edit

You may use where query like this

 Cursor objCursor = db.query("yourtableName",null, "columnName=?",
            new String[] { "johnny" }, null, null, null, null);

 if ((objCursor != null) && (objCursor.getCount() > 0)) {
                      Toast.makeText(getApplicationContext(), "string found!!! =)", Toast.LENGTH_LONG).show();
}

Note: Replace yourtableName with your table name and columnName with table's column name.

Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
  • What is the difference between cursor.getString(1); and cursor.getString(cursor.getColumnIndex(Columnname))? Why to use later and not the previous one? – Pravinsingh Waghela Jul 14 '14 at 13:08
  • 1
    @PDWaghela in getstring(1) = the value of the 1st column and getString(cursor.getColumnIndex(Columnname)) = the value of the Columnname of the row. – Giru Bhai Jul 14 '14 at 13:11
  • Well then Why should one use the getString(cursor.getColumnIndex(Columnname)) and not the Simple cursor.getString(1).? What the difference? is their any performance issue? – Pravinsingh Waghela Jul 14 '14 at 13:45
0

You have to used equal method instead of == to match string in java . or you can create query instead of doing and fetching and comparing in for loop. Like select * from table name where name like something

mcd
  • 1,434
  • 15
  • 31