How to get last record from table SQLite - android

I have problem with receiving last data from table in Android SQLite.
Adding values works great but I struggle with receiving last date from table, here is code:
int getKoniec() {
SQLiteDatabase db = this.getReadableDatabase();
String sortOrder = TABELA_koniec + " DESC LIMIT 1";
Cursor cursor = db.query(
TABELA,
new String[] { "koniec" },
null,
null,
null,
null,
sortOrder
);
if(cursor != null) {
cursor.moveToFirst();
}
int koniecINT = cursor.getInt(0);
Log.v("VALUE: ","" + koniecINT);
cursor.close();
return koniecINT;
}
While adding values 10,9,8,7.. output (return koniecINT) is always 10.
Can you help me to solve this problem? Thanks

Try this query
select * from table_name order by row_id desc limit 1
or
mCursor.moveToLast();

Related

Android SQLITE Query: Getting last 3 entries

I am trying to get the last 3 entries made to the database. Im using the following code but im only getting the last entry not the last 3.
String query = "Select * from " + TABLE_DETAILS + " DESC limit 3;";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
cursor.moveToFirst();
System.out.println(Integer.parseInt(cursor.getString(2)));
cursor.close();
} else {
}
db.close();
Thanks
You'll need to loop with the cursor to get all result rows, e.g. instead of
if (cursor.moveToFirst()) {
...
loop like this
while (cursor.moveToNext()) {
System.out.println(cursor.getString(2));
}
cursor.close();
To change the ordering, add ORDER BY <expression> to your query, for example
SELECT ... ORDER BY _id DESC LIMIT 3

Android sqlite return number of rows from query

I am trying to build a method to determine if a user exists in an Android sqlite database before inserting, I have tried to build this method to return the number of rows, however If I try a search for like matches like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " LIKE '" + screenName + "%'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get the number of rows returned no problem however the minute I look for an exact match like this
String[] columns = new String[] { SCREEN_NAME, NAME, PROFILE_IMAGE_URL,
USER_ID };
Cursor c = friendsDatabase.query(DATABASE_TABLE, columns, SCREEN_NAME
+ " = '" + screenName + "'", null, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();
return count;
I get 0 rows every time no matter if it matches or not, Im not sure if theres something wrong with my SQL or maybe im using the wrong arguments to make the statement, any help would go a long way thanks
Try this code it might work
Using Raw Query
Cursor mCount= db.rawQuery("select count(*) from "+ DATABASE_TABLE +" where "+SCREEN_NAME+"='" + SCREEN_NAME + "'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
Or using the same code but differently
db.query(DATABASE_TABLE , columns, SCREEN_NAME=?, new String[] { SCREEN_NAME}, null, null, null);
c.moveToFirst();
Integer count= c.getCount();
c.close();

How to delete specific data from a particular column in SQLite?

My app has a sqlite table which has the following columns:
CONTACT_ID = "_id",
CONTACT_NAME = "con_name",
CONTACT_USERID = "con_userid",
CONTACT_ACCID = "con_accid".
The content of the column con_accid is of type String. The primary key of the table is id. I want to delete data of particular con_accid. For example, I want to delete item names of all items which have con_accid as "raja". I have tried the following different queries but both are not working:
Cursor cursor = database.query(ContactsDB.TABLE_CONTACTS, allColumns,
ContactsDB.CONTACT_ACCID + "= ' " + comment +"'" , null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.i(TAG, "delete");
ContactsInfo _comment = cursorToComment(cursor);
long id = _comment.getId();
database.delete(ContactsDB.TABLE_CONTACTS, ContactsDB.CONTACT_ID + "=" + id , null);
cursor.moveToNext();
}
}
and this:
String query = "SELECT * FROM todo WHERE con_accid='" + comment;
Cursor cursor = database.rawQuery(query,null);
This should delete all rows in your database where con_accid = raja:
database.delete(TABLE_CONTACTS, CONTACT_ACCID + " = ?", new String[] {"raja"});
Check "database" instance is created with .getWritableDatabase(). And your query should work without any issue.

SQLiteDatabase Query in android

Am having a table card with colums id,name, content,status, date.
i want to take id,name,content condition is status <= cards.STATUS also have to sort it by date
How i have to do this.
am doing like,
private Cursor c;
String[] cols = { id,name, content };
c = cardsDB.query(CARDS_TABLE_NAME, cols, "status <=" + Card.STATUS, null, null, null, "date desc");
if (c.moveToFirst()) {
do {
CardArray.add(new Card(c.getInt(0), c.getInt(1), c.getString(2)));
} while (c.moveToNext());
}
c.close();
When you have the complicated query , its better to use raw query not query method.
This is an example of how to implement a raw query:
String query= "Select id,name ,content from CARDS_TABLE_NAME Where status <= ? date desc";
Cursor c= database.rawQuery(query, new String[]{Card.STATUS});

Android- Getting a single value from a database table using cursor

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.
Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:
public Cursor getMyNameInfo() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "MyNames";
qb.setTables(sqlTables);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToFirst();
return c;
}
Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).
Remember to check that the Cursor has valid data first though.
EDIT:
Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.
String theName = c.getString(getColumnIndex("Name"));
Cursor cursor = dbHelper.getdata();
System.out.println("colo" + cursor.getColumnCount() + ""
+ cursor.getCount());
cursor.moveToFirst();
if (cursor != null) {
while (cursor.isAfterLast() == false) {
String chktitle = title.trim().toString();
String str = cursor.getString(cursor.getColumnIndex("title"));
System.out.println("title :: "
+ cursor.getString(cursor.getColumnIndex("title")));
System.out.println("date :: "
+ cursor.getString(cursor.getColumnIndex("date")));
System.out.println("desc :: "
+ cursor.getString(cursor.getColumnIndex("desc")));
if (chktitle.equals(str) == true) {
tvAddfavorite.setText("Remove Favorite");
break;
}
cursor.moveToNext();
}
}
cursor.close();
Add a WHERE clause:
qb.appendWhere("_id = 2");
Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.
public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tableName);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToPosition(position);
String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
return neededValue;
}
Hope it helps anyone.

Categories

Resources