Android SQLITE Query: Getting last 3 entries - android

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

Related

How to get last record from table SQLite

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();

Checking if Cursor contains row results?

I'm having a lot of trouble with checking if a cursor contains any results.
I have a method that "removes" all rows from a given table which is here:
Chevron.class
public void deleteAllRecords(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME,null,null);
}
I then call a method which adds the SUM of the first row of the database which is here:
public Cursor getRecalculate(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select SUM (" + SECOND_FIELD + ") FROM " + TABLE_NAME, null);
return res;
}
My major issue is that if I remove all records from the database, res.getCount() still equals 1 but contains no information but then the method only returns 1 row anyway. So I'm stuck with how to check if the cursor has actual table data or just empty table data.
I've tried stuff like
if(res.getString(0) == null){
.. Do code
}
but that doesn't work.
I get the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ceri.twostep_onecheck/com.example.ceri.twostep_onecheck.ShowGraph}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
If you want to know how many rows there are that match your query constraints, add COUNT(*) to the SELECT statement:
SELECT COUNT(*), SUM(whatever) FROM other_thing;
Then, move the Cursor to the first row via moveToFirst(), and examine the two values (getInt(0) for the count and getInt(1) for the sum).
Use getReadableDatabase() instead of getWritableDatabase().
Try this:
public Cursor getRecalculate() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select SUM (" + SECOND_FIELD + ") FROM " + TABLE_NAME, null);
return res;
}
Read cursor value:
// Move the cursor to the first row if cursor is not empty
if(res.moveToFirst())
{
do
{
// Do something with cursor
}while(res.moveToNext()); // Move cursor to next row until it pass last entry
}
// Close
res.close();
Hope this will help~
Try this
cursor.getCount();
This should return at least one if cursor reads something or it will return zero.

Cursor returning 0

I have a function where I want to get the sum of values on a MySQL database table's row. This is my code:
public int getSum(int var) {
int x=0;
// Select All Query
String selectQuery = "SELECT sum(amount) FROM donations WHERE aid = '"+aid+"'";
SQLiteDatabase db = openOrCreateDatabase("shareity", Context.MODE_PRIVATE, null);
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
x = cursor.getInt(0);
} while (cursor.moveToNext());
}
// return contact list
Log.d("id", "Id" + "," + x);
return x;
}
And I'm calling this in the onCreate() like this:
getSum(idk);
where idk is an integer. But my this returns 0. Can I know why please? The table's row I want to get the sum of, is also integer.
Finally figured it out. The problem was with the SQLite database. I had to use a php file to download the database from the mysql server to the local Sqlite server and then loop through it

Android SqlLite update last inserted row

This is what i am using for insert:
public long insert(String content, Date startAt, Date endAt) {
if (content == null || startAt == null) {
return 0;
}
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
contentValues.put(KEY_START_AT, startAt.getTime());
if (endAt == null) {
contentValues.putNull(KEY_END_AT);
} else {
contentValues.put(KEY_END_AT, endAt.getTime());
}
return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
}
now i want to create update method which will update last inserted row. How can i get last inserted row?
If you have an id attribute that works as a primary key, you can do a raw database query on SqlLite.
Cursor cc = this.mDb.rawQuery("SELECT *" + " FROM " + "<Your DATABASE_NAME> " +
"ORDER BY id " + "DESC LIMIT 1", null);
return cc;
Here,
1. It returns a cursor.
2. mDb is a SQLiteDatabase class instance.
3. ORDER BY id allows the query to sort by id number. As I said, if you have an id as primary key in your table, your latest entry will have the maximum id number.
4. DESC allows to sort by descending order.
5. LIMIT 1 allows to return only 1 row.
6. Always be careful when writing raw queries, white spaces inside the query can be a lot of pain when you do not handle them carefully.
For further queries you can see this tutorial. And obviously Divya's answer is also a good one.
You can use a cursor to retrieve rows and say :
cursor.moveToLast();
OR
cursor.moveToPosition(cursor.getCount() - 1);
When you insert a row in to your table the insert query returns the key of the last inserted row. You can now use this key to update this row.
for example
int newInsertedKey = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
update table_name set column_name = 'Change 2' where columnID = newInsertedKey
An efficient method would be to avoid anymore database queries to get the last updated row.
Maybe he should use something like this
public long getLastId() {
Cursor c = mDb.query(currentTableName, new String[] { "MAX(_id)" },
null, null, null, null, null, null);
try{
c.moveToFirst();
long id = c.getLong(0);
return id;
}catch(Exception e){
return 0;
}
}
where _id is column by which you identify rows

compare sqlite with string

I saved Data in my SQL databank.
Now I want to compare this saved data, with a string
Something like this:
String example = "house";
Now I want to check, if "house" is already in the databank, with a if clause
something like this
if ( example == [SQL Data] ) {
}
else {
}
Now, how can I accomplish this ?
Do something like
String sql = "SELECT * FROM your_table WHERE your_column = '" + example + "'";
Cursor data = database.rawQuery(sql, null);
if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}
stolen from here
Writing my reply to Sharath's comment as an answer, as the code will be messed up in a comment:
Not saying your reply is wrong, but it's really inefficient to select everything from the table and iterate over it outside the database and it shouldn't be suggested as an answer to the question, because it's a bad habbit to do like that in general.
The way I usually do it, if I want to see if some record is present in the database, I do like this. Not gonna argue about using do-while over a normal while-loop, because that's about different preferences ;)
String query = "SELECT * FROM table_name WHERE column_name=" + the_example_string_to_find;
Cursor cursor = db.rawQuery(query, null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
// Do whatever you like with the result.
cursor.moveToNext();
}
}
// Getting Specific Record by name.
// in DB handler class make this function call it by sending search criteria.
Records getRecord(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_Auth_Name, KEY_B_PRICE}, KEY_ID + "=?",
new String[]{name}, null, null, null,null);
if (cursor.getCount() > 0)
cursor.moveToFirst();
Records Records = new Records(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return book
return Records;
}
you need to first fetch all the data from the database and next check the data with what you obtained from the database.
Have a look at the link sample database example
suppose you got a cursor object from the database
cursor = db.rawQuery("SELECT yourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
if(cursor.getString(0).equals(example))
//do something which you want and break
break;
} while (cursor.moveToNext());
}

Categories

Resources