sir, how can i return the rowid of my database depending on the inputs name, number? this code just return the value 0 everytime. my primary key is KEY_ROWID. thanks for help in advance
//get rowid
public long getRowId(String name, String number)
{
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_NUMBER};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NUMBER+ "=" +number, null, null, null, null);
long rowid = c.getColumnIndex(KEY_ROWID);
return rowid;
}
here is how i access it
public void onClick(View arg0) {
nameChanged = sqlName.getText().toString();
numChanged = sqlNumber.getText().toString();
GroupDb info = new GroupDb(EditDetails.this);
info.open();
long rowid = info.getRowId(name, num);
info.updateNameNumber(rowid, nameChanged, numChanged);
Toast.makeText(getApplicationContext(), rowid+" "+nameChanged+" "+numChanged, Toast.LENGTH_LONG).show();
ArrayList<Contact> searchResults = info.getView();
MyCustomBaseAdapter mcba = new MyCustomBaseAdapter(EditDetails.this, searchResults);
mcba.updateResults(searchResults);
Toast.makeText(getApplicationContext(), "Update Successful!", Toast.LENGTH_LONG).show();
info.close();
}
});
From the fine manual:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
[...]
ReturnsA
Cursor
object, which is positioned before the first entry.
So first you have step c
into the result set and you can use moveToFirst
for that:
c.moveToFirst();
Now you need to extract the rowid from the row that the cursor is pointing at. But getColumnIndex
is for mapping a column name to a position in the row:
Returns the zero-based index for the given column name, or -1 if the column doesn't exist.
You're getting a zero from getColumnIndex
because your KEY_ROWID
is the first column in your SELECT query.
I think you're looking for getLong
if you want to extract a long
from the Cursor
's result set:
long rowid = c.getLong(c.getColumnIndex(KEY_ROWID));
If you know the structure of your query (which you do), you could skip the getColumnIndex
call and just use the known index:
long rowid = c.getLong(0);
And if all you're doing is looking up the rowid, you can SELECT just KEY_ROWID
:
String[] columns = new String[]{KEY_ROWID};
There's no need to pull things out of the database that you're ignoring.