0

why does when i use a string as a where condition in my database, my program just force close. though it is working fine if i use number as a query condition. please help me, thanks

public ArrayList<Contact> getAvailableList() 
{
    // TODO Auto-generated method stub
    ArrayList<Contact> results = new ArrayList<Contact>();
    String[] columns = new String[]{KEY_NAME, KEY_NUMBER, KEY_STATUS};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=available" , null, null, null, KEY_NAME);
    String sName = "";
    String sNum = "";
    String status = "";
    int iName = c.getColumnIndex(KEY_NAME);
    int iNumber = c.getColumnIndex(KEY_NUMBER);
    int iStatus = c.getColumnIndex(KEY_STATUS);
    Contact contact;
    for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext())
    {
        contact = new Contact();
        sName += c.getString(iName);
        sNum += c.getString(iNumber);
        status += c.getString(iStatus);
        contact.setName(sName);
        //contact.setPhoneNumber(sNum);
        contact.setPhoneNumber("0".concat(sNum));
        contact.setStatus(status);
        results.add(contact);
        sName = "";
        sNum = "";
        status = "";
    }
    return results;
}

2 Answers 2

2

You need to wrap strings in SQL with quotes, like this:

//                                                       Add these  v         v
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"='available'", 
        null, null, null, KEY_NAME);

Or if you want to use dynamic data, you should use the selectionArgs parameter:

String status = "available";
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=?", 
        new String[] {status}, null, null, KEY_NAME);

This approach simplifies keeping track of matching quotes in complex Java/SQL Strings, more importantly it protect you from SQL injections.

Sign up to request clarification or add additional context in comments.

Comments

1

You forgot ' ' around available

  Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"='available'" , null, null, null, KEY_NAME);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.