1

I want to display data from column according to another column, so I used this method in HelperDB to get the Cursor:

public Cursor getData(String EMAIL) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "SELECT * FROM table_users WHERE email LIKE '" + EMAIL +"';" , null );
    return res;
}

And to display(hlp is the HlperDB):

Cursor c = hlp.getData(Email);
tv3 = (TextView) findViewById(R.id.tv3);
tv3.setText(c.getString(c.getColumnIndex(HelperDB.NOTES)));

But it gave this error: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

Can you help me please?

itay azaria
  • 53
  • 1
  • 4

2 Answers2

1

Try this:

Cursor c = hlp.getData(Email);
if(c != null)
    c.moveToFirst();

tv3 = (TextView) findViewById(R.id.tv3);
tv3.setText(c.getString(c.getColumnIndex(HelperDB.NOTES)));
Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61
  • Thanks it worked, but I don't get it - how does it work? the cursor need to be on the first record no? – itay azaria Apr 12 '17 at 19:05
  • "A Cursor object, which is positioned before the first entry." Calling moveToFirst() does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty). Here is a good explanation: http://stackoverflow.com/questions/12445010/what-is-the-use-of-movetofirst-in-sqlite-cursors – Ferdous Ahamed Apr 12 '17 at 19:14
  • @itayazaria Thanks for accepting my answer. If my answer seems useful then please give an up-vote to my answer. Thanks in advance :) – Ferdous Ahamed Apr 27 '17 at 14:01
0

My guess is that your Cursor has no data (is NULL). The API documentations for Cursor.getColumneIndex (link) indicates that it will return -1 if the column does not exist. Then when you try and execute getString() you're passing a -1 and there's your error.

jradich1234
  • 1,410
  • 5
  • 24
  • 29
  • I opened the database with SQLite browser and there is a record with the E-mail I checked in the coode so why is the cursor null? – itay azaria Apr 12 '17 at 18:26
  • Debug your code and ensure that c isn't null before you execute the getColumnIndex. – jradich1234 Apr 12 '17 at 18:29
  • Follow up question. In your SQL statement you're using 'like'. Have you appended a wild card to your EMAIL string? – jradich1234 Apr 12 '17 at 18:30
  • no, which wild card I need to add? I tried the % wild and it still doesn't work – itay azaria Apr 12 '17 at 18:44
  • It's going to depend on how what your stored email address looks like and what's getting passed into the query string. The percent (%) symbol is the correct wild card. You could try appending a percent symbol to the both ends of EMAIL string. That would give you a does the field contain the string effect. – jradich1234 Apr 12 '17 at 18:47
  • no, still didn't work but the first answer worked to me, thanks for the help anyway! – itay azaria Apr 12 '17 at 19:03