0

I have a method as below:

public boolean ReadingMade(int id, String readingdate)
{

    String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "="  +id + " And " + READINGDATE +"=" + readingdate;
    Log.e("LOG", selectQuery);      
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);
    if(c.moveToFirst()){
        c.close();
    return true;
    }
    else
    {
        c.close();
        return false;
    }

}

I want to pass the string argument using a value from edit-text e.g

EditText readDate= (EditText)findViewById(R.id.editText1);
if (db.ReadingMade(id,readDate.getText().toString()) ==true)
        {

I get a string like one below

Select * From MeterReading Where TenantMeter_id=1 And ReadingDate=2014-01-20

Yet sq-lite expects

Select * From MeterReading Where TenantMeter_id=1 And ReadingDate='2014-01-20'

How do i pull it off?

1
  • Dear user, all the answers below are correct, you can mark any of these answers as accepted (ofcourse, if it helped you)...!!! Commented Feb 4, 2014 at 8:43

3 Answers 3

1

Just change

    String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "="  +id + " And " + READINGDATE +"=" + readingdate;

to

    String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "="  +id + " And " + READINGDATE +"= '" + readingdate+"'";
Sign up to request clarification or add additional context in comments.

1 Comment

Click on the tick mark that you can see beside my answer.
1

If I have not misunderstood you, that should work

"='" + readingdate + "'"

Comments

1

Use ? placeholders for literals to prevent the need to escape special characters in literals and to avoid SQL injection attacks:

String selectQuery = "Select * From " + TABLE_METERREADING + " Where " +TENANTMETER_ID+ "=? And " + READINGDATE +"=?";
// ...
String[] args = new String[] { Integer.toString(id), readingdate };
Cursor c = db.rawQuery(selectQuery, args);

(There's a performance benefit to ? args as well but it's normally not visible in the way Android SQLite API is used.)

2 Comments

This is the correct answer. Other answers leave you open to injection attacks and miss the utility of the ? parameter replacement feature in db.
Thank you. I am going to change.

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.