Fetching single value from SQLite in android
Asked Answered
A

2

6

I'm developing my firs app for android right now, I am using multiple tables to get and insert data. during the development and found myself fetching data from the table with has only two columns STATS(_id, stat_name). What my problem is? I have an activity with 10 buttons, and every button correlates with one stat_name. When users presses one of the buttons application is "going" to STATS table to get correct _id and then is inputting this _id to another table GAME_STATS(_id, PlayerId (fk), GameId(fk), StatsId(fk)(andmore)) on STATS._id = GAME_STATS.StatsId and I basicly have to do similar operation for PlayerId.

Right now, I'm doing it this way:

public String getStatId(String statName){
    String statId = "Error";
    Cursor c = mDb.query(STAT_TABLE, new String[] {AbstractDbAdapter.STAT_ID, AbstractDbAdapter.STAT_NAME}, AbstractDbAdapter.STAT_NAME+ " = " +statName, null, null, null, null);
    int count = c.getCount();
    if(count == 1){
        c.moveToFirst();
        statId = c.getString(c.getColumnIndex(AbstractDbAdapter.STAT_ID));
    }
    c.close();
    mDb.close();
    Log.d("FootballApp","StatId =" +statId);
    return statId;      
}

What my problem is, that I know that there SHOULD be only one value returned, and I still have to use Cursor, to do so. Also, in my opinion, it looks way to complicated and time consuming wo write all that code just to get one id from one table. I have 9 tables in my application, and I will have to write similar method every time I need _id from different table when I have, for example, only name.

Can someone tell me if there is easier way to do all that? Please :) thanks! :)

Acetylide answered 14/7, 2012 at 1:8 Comment(0)
T
9

I think it doesn't get much simpler than that. However you can make the method more generic so you can reuse the code:

public String getFromDb(String tableName, String select, String selectBy, String selectName){
    String selection = "Error";
    Cursor c = mDb.query(tableName, new String[] {select}, selectBy + "=" + selectName, null, null, null, null);
    if(c.getCount() == 1){
        c.moveToFirst();
        selection = c.getString(c.getColumnIndex(select));
    }
    c.close();
    mDb.close();
    Log.d("FootballApp", select + "=" + selection);
    return id;      
}

Example usage:

int statID = getFromDb(STAT_TABLE, AbstractDbAdapter.STAT_ID, AbstractDbAdapter.STAT_NAME, statName);
Trudge answered 14/7, 2012 at 1:31 Comment(1)
For more secure code replace selectBy + "=" + selectName, null with selectBy + "=?", new String[]{selectName}Helminthic
J
8

That is about as simple as it gets, but Cursor.moveToFirst() returns false if the cursor is empty so you can cut out the c.getCount() call and just say if(c.moveToFirst()) instead. That will save you a little bit of typing :)

Jerkin answered 14/7, 2012 at 1:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.