Search code examples
javaandroiddatabasesqliteandroid-sqlite

Use a parameter to select data from SQlite database


I wanna use a String d as a parameter to select data from a sqlite database ..

- ID ------ DATE --------- VALUE 
- 1 --------11/04/2020 ----2000 
- 2 --------11/04/2020 ----4000
- 3 --------11/04/2020 ----1000
- 4 --------12/04/2020 ----700
- 5 --------13/04/2020 ----300

My getEntry() method looks like this :

public String getEntry(String d) {
    // This value of storedEntry is returned if there is no data
    String storedEntry = "Nothing!";
    //here we use d to fetch data from table
    String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+DATE+"="+ d;
    SQLiteDatabase db = this.getReadableDatabase();
    String table;
    Cursor cursor = db.rawQuery(queryString, null);
    if(cursor.moveToFirst()) {
        do {
           storedEntry = cursor.getString(2);
        } while (cursor.moveToNext());
    } else {
        //Do nothing!
    }
    return storedEntry;
}

My onClick method looks like this :

showDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DataBaseHelper helper = new DataBaseHelper(HistoryActivity.this);
                String v = helper.getEntry(dateEditText.getText().toString());
                valueTextView.setText(v);
            }
        });

But, it returns an error :

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.darq2.myapplication, PID: 25073
              android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
                  at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
                  at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
                  at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
                  at com.example.darq2.myapplication.DataBaseHelper.getEntry(DataBaseHelper.java:61)

WHY ??


Solution

  • The easy but not safe way to do this is by enclosing the parameter d inside single quotes and then concatenate:

    String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+DATE+"='"+ d + "'";
    

    but as I said this is not safe.
    Use ? placeholders for parameters:

    String queryString = "SELECT * FROM "+TABLE_NAME+" WHERE "+DATE+"=?";
    

    and also change:

    Cursor cursor = db.rawQuery(queryString, null); 
    

    to:

    Cursor cursor = db.rawQuery(queryString, new String[] {d}); 
    

    Also, you should change the format of your dates.
    SQlite recognizes only the format YYYY-MM-DD as a valid date.