Search code examples
javaandroidsqlitesql-updateandroid-sqlite

Android Java SQLite rowid based on data in another column


Solution has been checked off, but there is another which works. I'll add it below

I've been at this all day. Had help on another aspect of the problem, but I'm stumped again. How can I get the rowid of a row with certain data in a column? I need the rowid returned as an int or string. Example data:

_id|firstname|lastname
1  |Bob      |Dole
2  |Richard  |Simmons
3  |Steven   |King

So, what code should I use if I want to get the rowid if lastname = "Simmons"? After a select statement is run, I thought c.getPosition() would do it, but that's returning -1. Here is what I've got so far:

String where = "SELECT rowid, * FROM masterRecord WHERE masNameCol='" + name + "'"; //name is a variable passed from another activity

        Cursor c =  db.rawQuery(where, null);
        String rowid = "_id = " + c.getPosition(); //This always returns -1. In this example, I need it to be 2
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_MASNAMECOL, rowid);
        newValues.put(KEY_MASTIMECOL, newTime);
        c.close();

        return db.update(masterRecord, newValues, rowid, null) != 0;

Note that if I replace rowid in the return statement with "_id=2", it will work as intended. So I've narrowed it down to just needing to get that number somehow.

Other solution

String where = "SELECT rowid, * FROM " + masterName + " WHERE masNameCol='" + name + "'";

        int rowid = 0;

        Cursor c =  db.rawQuery(where, null);
        c.moveToFirst();  //Needed this line
        if (c.getCount() > 0) {  //And this if statement
            rowid = c.getInt(c.getColumnIndex("_id"));
        }
        ContentValues newValues = new ContentValues();
        newValues.put(KEY_MASNAMECOL, rowid);
        newValues.put(KEY_MASTIMECOL, newTime);
        c.close();

        return db.update(masterName, newValues, "_id =" + rowid, null) != 0;

Solution

  • You can update the table without first fetching its rowid:

    String where = "masNameCol = ?";
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_MASNAMECOL, "somevaluehere"); // what value do you want this column to be updated?
    newValues.put(KEY_MASTIMECOL, newTime);
    return db.update(masterRecord, newValues, where, new String[] {name}) != 0;
    

    Note that if the column masNameCol is not unique, this will update all rows with the value of the variable name.