Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching single value from SQLite in android

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! :)

like image 738
mancuss Avatar asked Jul 14 '12 01:07

mancuss


People also ask

How to insert and retrieve data from SQLite database in Android?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.


1 Answers

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);
like image 79
Caner Avatar answered Sep 22 '22 10:09

Caner