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)
[...]
Returns
A 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.
Related
How to get specific value from DB by id.
This is my table: TABLE-RECORDS-(name of table) and KEY-ID , KEY-PRICE ... I'm trying to get KEY-PRICE by KEY-ID and can not. How to do it?
I don't know if this is exactly what you are looking for, but this is the query.
SELECT key-price FROM table-record WHERE key-id='id number you need';
// please change the column names of database if i have mistaken
public Cursor getCursor(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String from[] = {"key-price"};//this is the edit1
String where = "key-id=?";//this is the edit2
String[] whereArgs = new String[]{String.valueOf(id)+""}; //this is the edit3
Cursor cursor = db.query(true, table-records, from, where, whereArgs, null, null, null, null);
return cursor;
}
//just call this function and see the magic
private int getPrice(int id) {
Cursor c = getCursor(id);
int price=-1;
if(c != null)
{
while(c.moveToNext){
//assuming price is an integer
price = c.getInt(0);//edit 4
// use these strings as you want
}
}
return price;
}
I have a table with 3 columns "ID", "NAME" & "STATUS". I would like to execute a query on my database where I can get only one entry of "ID" which is located at the top row. I have a working sql query,
"SELECT TOP 1 ID from SAMPLE_TABLE WHERE Status='PENDING' ORDER BY ID ASC;"
This is so far what I implemented in android,
// Getting pending items
public int pendingContact() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor mCount = db.query(
TABLE_CONTACTS ,
new String[] { "id" } ,
"status = ?" ,
new String[] { "PENDING" } ,
null ,
null ,
null
);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
Al through it gives the desired output but I would like to know if there is any other way of doing this more efficiently.
You can use Limit
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
limit - Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
You can do this:
Cursor mCount = db.query(TABLE_CONTACTS, new String[] { "id" }, "status = ?", new String[] { "PENDING" }, null, null, "id ASC", "1");
This will keep you from acquiring more data than you need.
When you use ORDER BY, the database will read and sort all PENDING items before it can return the first one.
When using MIN, nothing but the smallest value must be stored temporarily:
SELECT MIN(id) FROM Contacts WHERE Status = 'PENDING'
In code:
Cursor mCount = db.rawQuery("SELECT MIN(id) FROM Contacts WHERE Status = ?",
new String[] { "PENDING" });
here is my code:
public String getFriendName(int aFindexnum){
String sql = "SELECT * FROM peopleTable WHERE "+KEY_CBINDEX+"="+aFindexnum;
Cursor cursor = ourDatabase2.rawQuery(sql, null);
String Fname = cursor.getString(1);
cursor.close();
return Fname;
}
I am trying to search for an integer and than return other Value that is String in my sqldatabase
So i am passing in that aFindexnum which is the integer value in the Db and i want to find it
my problem was when i tried to do something like that:
public String getFriendName(int aFindexnum){
String aFindex = getString(aFindexnum);
String sql = "SELECT * FROM peopleTable WHERE "+KEY_CBINDEX+"=?";
Cursor cursor = ourDatabase2.rawQuery(sql, new String[] {aFindex});
String Fname = cursor.getString(1);
cursor.close();
return Fname;
}
String aFindex = getString(aFindexnum); <<if i will turn this with
parse into String will it work ?
public long createEntry( String name, String phonenum ,int phoneindex) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_PHONENUM, phonenum);
cv.put(KEY_CBINDEX, phoneindex);
return ourDatabase2.insert(DATABASE_TABLE, null, cv);
}
this is the entry of the sql Db, so u can see in the third column i am putting an int and i want to search for it and get the name and the phone.
thanks.
getString() in an activity gets a string from resources. Referring to a resource id with the name of an index number looks suspicious. If I understood your code and question, this
Cursor cursor = ourDatabase2.rawQuery(sql, new String[] {aFindex});
should be
Cursor cursor = ourDatabase2.rawQuery(sql, new String[] { String.valueOf(aFindexnum) });
and you can remove the first problematic getString().
When you query and get a Cursor, you'll have to move it to a valid row before accessing column data. Add
if (cursor.moveToFirst()) { ... }
If I understood your code and question,
By reading your sql String code you want row which matches KEY_CBINDEX value
If in your database data type of KEY_CBINDEX column is int then you can get integer value
By replacing
cursor.getString(1);
with
int intValue = cursor.getInt(cursor.getColumnIndex(KEY_CBINDEX));
or if is string, then replace with
int intValue = Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_CBINDEX)));
You have to replace it in your second code block.
I am trying to create a method to retrieve the max id of a specific table.
This is the code that doesn't work:
private long getMaxId()
{
String query = "SELECT MAX(id) AS max_id FROM mytable";
Cursor cursor = db.rawQuery(query, new String[] {"max_id"});
int id = 0;
if (cursor.moveToFirst())
{
do
{
id = cursor.getInt(0);
} while(cursor.moveToNext());
}
return id;
}
The exception being thrown is this:
E/AndroidRuntime(24624): android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x200408
I suppose the problem is this line:
id = cursor.getInt(0);
Does anybody have an idea of how to fix this?
Thanks.
Try replacing:
Cursor cursor = db.rawQuery(query, new String[] {"max_id"});
with
Cursor cursor = db.rawQuery(query, null);
From the rawQuery description , for the 2nd argument:
You may include ?s in where clause in
the query, which will be replaced by
the values from selectionArgs. The
values will be bound as Strings.
Since you dont have any placeholders in your SQL query, maybe it is the source of the problem.
I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work.
This is my method:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}
I have tried with MAX, but I must be using it wrong. Is there another way?
Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID.
You can check its documentation here.
I hope this helps.
Use
SELECT last_insert_rowid();
to get the last inserted rowid.
If you are using AUTOINCREMENT keyword then
SELECT * from SQLITE_SEQUENCE;
will tell you the values for every table.
To get the last row from the table..
Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();
Use moveToLast() in Cursor interface.
From android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* #return whether the move succeeded.
*/
boolean moveToLast();
Simple example:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
Or you can get the last row when insertion(Which is #GorgiRankovski have mentioned):
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
Also their is a multiple ways you can do this using query:
One is expressed by #DiegoTorresMilano
SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1
(If you want each and every value, use * instead of id)
If you want the last_insert_id just afert a insert you can use that :
public long insert(String table, String[] fields, String[] vals )
{
String nullColumnHack = null;
ContentValues values = new ContentValues();
for (int i = 0; i < fields.length; i++)
{
values.put(fields[i], vals[i]);
}
return myDataBase.insert(table, nullColumnHack, values);
}
The insert method returns the id of row just inserted or -1 if there was an error during insertion.
long id = db.insert("your insertion statement");
db is an instance of your SQLiteDatabase.
Try this:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
/**
* #return
*/
public long getLastInsertId() {
long index = 0;
SQLiteDatabase sdb = getReadableDatabase();
Cursor cursor = sdb.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLENAME},
null,
null,
null,
null
);
if (cursor.moveToFirst()) {
index = cursor.getLong(cursor.getColumnIndex("seq"));
}
cursor.close();
return index;
}
I use this
public int lastId(){
SQLiteDatabase db =
this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from resep", null );
res.moveToLast();
return res.getInt(0);
}
In your DbHelper class,
public long getLastIdFromMyTable()
{
SQLiteDatabase db = this.getReadableDatabase();
SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
return st.simpleQueryForLong();
}