Android-Droid
Android-Droid

Reputation: 14565

android save sql query result as cursor exception

I have a little issue with that piece of code :

public static int localUserIdByServerUserId(int serverUserId, String serverName){

        dbHelper = new DataBaseHelper(context, "opalqnka_sys_tpl.sqlite", null, 1);
        dbHelper.getDatabase();
        dbHelper.executeQuery("users", "objectId", "2");
        dbHelper.executeQuery("users","serverName","opalqnka");
        dbHelper.executeQuery("users", "objectId", "3");
        dbHelper.executeQuery("users","serverName","opalqnka");
        dbHelper.executeQuery("users", "objectId", "3");

        String query = "SELECT id FROM users WHERE objectId = "+serverUserId+" AND serverName = '"+serverName+"' LIMIT 1";
        ArrayList<String> result = new ArrayList<String>();
        cursor = dbHelper.executeSQLQuery(query);
        cursor.moveToFirst();
        while(!cursor.isAfterLast()) {
            result.add(cursor.getString(cursor.getColumnIndex("id")));
             cursor.moveToNext();
        }

        int uuid = Integer.parseInt(result.get(cursor.getInt(cursor.getColumnIndex("id"))));
        Log.w("localUSerByIdServerUserId","LocalUserByIdServerUserId result : "+uuid);
        cursor.close();
        return uuid;
    }

It's throwing me an android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 at this line :

int uuid = Integer.parseInt(result.get(cursor.getInt(cursor.getColumnIndex("id"))));

I'm not really familiar with database that's why I'm asking maybe stupid questions here. So if anybody has a solution for my problem, thanks in advance!

Upvotes: 0

Views: 643

Answers (2)

kalpana c
kalpana c

Reputation: 2739

First clear what you want. The crashing issue occur coz of not getting any value in result. first you check the record add in result. Print log like this

Log.e("",""+result.toString());

If there is only one record the you can get like this:

int uuid = Integer.parseInt(result.get(0));

If there is more than one record the you can use for loop and get more than one ids:

for(int i=0; i<result.size();i++)
    int uuid = Integer.parseInt(result.get(i));

Upvotes: 2

Android-Droid
Android-Droid

Reputation: 14565

You can do something like this :

cursor.moveToFirst();
    while(!cursor.isAfterLast()) {
        result.add(cursor.getString(cursor.getColumnIndex("id")));
        cursor.moveToNext();
    }

    Log.i("result ","Result : "+result.toString());
    Log.i("CURSOR ","Cursor Position : "+cursor.getPosition());
    Integer uuid = Integer.parseInt(result.get(cursor.getColumnIndex("id")));

Upvotes: 0

Related Questions