Sorting Sqlite data while display - android

I have "date"(TEXT) column in db.I want to display dates in ascending order(i.e. group by date).but according to current date.
i.e dates greator or equal than current date should be displayed first and past dates should get appended at last in listview automatically.I used SimpleCursorAdapter to display list.
So how should I do this?

Write the proper query and you should be fine. If you are looking for that particular query as an answer to your question, tag it as sql or sqlite as well.

You can sort data items when you try to query..here a cursor object set with parameters(just an example),the 7th parameter With "ASC" means that the return data will be in ascending oder
cursor cur = yourdata.query(TableName, coloumns, null, null,null, null, table.COLUMN_NAME + " ASC");
if you want an example you can try this code example
Click me

Related

How to read a group of records from database by using aCursor?

I have a sqlite database table. I need to get records from this table which are grouped by a date column. here's the query I am running:
select id as _id,sum(price) as price,sum(quantity) as quantity,sum(quantity*purchase_price) as cost,date from sales where date between '2018-08-24' and '2018-09-01' group by date order by date desc
this should return something like:
date price quantity cost
2018-08-24 345 13 250
2018-08-26 425 15 450
this is a sample data that is returned from the query grouped by the date. This is basically a sales report which tells that on 2018-08-24 you got $345, sold 13 items and spend $250.
I am receiving the result from the query using cursor, so I got a cursor object containing all this data. My question is that how can I access all this information from the cursor?
I tried accessing it using the regular way like this:
cursor.getInt(cursor.getColumnIndexOrThrow("quantity"));
cursor.getInt(cursor.getColumnIndexOrThrow("price"));
cursor.getInt(cursor.getColumnIndexOrThrow("cost"));
cursor.getString(cursor.getColumnIndexOrThrow("date"));
but this will just return the first row from the grouped records. just the first!
I think you are missing a loop over your cursor results. You can create a list for your results and get the cursor value into that list. maybe this can help you:
if (cursor.moveToFirst()) {
do{
//Get_sales_values_from_Cursor
cursor.getInt(cursor.getColumnIndexOrThrow("quantity"));
cursor.getInt(cursor.getColumnIndexOrThrow("price"));
cursor.getInt(cursor.getColumnIndexOrThrow("cost"));
cursor.getString(cursor.getColumnIndexOrThrow("date"));
//move_to_next_row
} while (cursor.moveToNext());
}
you can even define a list and add your cursor values to that, So you can have all your statistics in a list.
Best regards.

How to get 5 last record in the sqlite db in android?

Since the db does not have create date and some ordering field (but in my observation the last row is the latest record),
so how can i get the five last record in some condition e.g.
five record that their schoolid == 1?
Thanks
public Cursor select()
{
String orderBy = FIELD_pubKey+" DESC";
Cursor cursor = iReadDatabase.query(TABLE_NAME, null, null, null, null, null, orderBy);
cursor.moveToFirst();
return cursor;
}
There's no such thing as a last record or a first or a 42nd.
Which records appears last in the result of a query is dependent on the query plan, or an Explicit order by if you add one.
Select * From Table Where ...
The rows will be returned in whatever order the engine considers suitable at the time.
If you need them in specific order, then add an order by clause to the query, anything else is asking for it.
Something like
Select * From Table Order by SomeColumn desc limit 5
will do what you require.
Now what column you need to order by I've no idea, but you need one that will do the job, assuming automatic primary key, but note it is possible to mess with that.

Getting the MAX date in SQLite

Im using SQLite as data storage for my Android App. I have created one table with column of type datetime. When I do the insert of records or selects statements I use the format dd.MM.yyyy (10.08.2012) for dates.
Now, I have issue with getting the row with the latest / MAX date. I have tried using the MAX(date_column) statement, but it returns wrong date back. I have following dates in my table and it returns 31.07.2012 in stead of 04.08.2012. Anyone know what I'm doing wrong?
04.08.2012
03.08.2012
02.08.2012
01.08.2012
31.07.2012
30.07.2012
Here is part of the code:
String selection = "measurementDate = (SELECT MAX(measurementDate) FROM Measurements)";
Cursor cursor = database.query("Measurements", allColumns, selection, null, null, null, null);
cursor.moveToFirst();
...
Could it be because of 31?
Try to see if this helps:
SELECT measurementDate FROM Measurements ORDER BY measurementDate desc LIMIT 1
It's probably due to the comparison being made on the stored string rather than treating it as a date.
You could store the string in differently, YYYYMMDD, which should compare them correctly or, if you can modify the table, store the dates as milliseconds and format back to a string when needed.
This might help

SQLite query returns nothing

I have this query in SQLite that I want to return a value based on the date passed. The date is in the database as a String. I know that there is data in the database with that date, but it just returns nothing. I dont know why. When I make the query without comparisson parameters, it returns all the data normally, but using the WHERE clause in the query method, it stops returning. Maybe its just a matter of the SQL syntax. Anyways, here is the statement:
Cursor cursor = db.query(TABLE, new String[] {"_id", "value"}, "current_date = ? ", new String[] {date}, null, null, null);
EDIT
I've made this query in SQLite Database Browser, and it doesn't return any values. Even if its there.
I've seen that this is quite funny and confused. I've tested on Database Browser and also on phone, when I pass the current day, the 'Today' day, it gets the data, but when I pass another day that isnt today, it returns nothing. Very, very weird.
And in Database Browser, I've selected the column that contains the date and it returns only the 'Today' date, even if before there are another dates.
if your date is stored in database in format 'dd-mm-yyyy',then try using it like-
Calendar cal=Calendar.getInstance();
Cursor cursor = db.query(TABLE, new String[] {"_id", "value"}, "date = ? ", String.format("%1$td-%1$tm-%1$tY",cal), null, null, null);
For other formats,please refer http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
The column name was 'current_date' and this is a SQLite function name. So it didn't get the other dates, just the current date.

How to go through every record in SQLite db?

I think it's kinda easy one but still I'm new to android programming so please have patience. I want to know how can I get the number of records (rows) in a specific table in my db. I need this so I can create a loop to go through every record and add each one of it to the specific Array and display it later on. This is the source:
db.openDataBase(); // open connection with db
Cursor c = db.getTitle(5); // loop here through db, right now I'm fetching only one record
startManagingCursor(c);
//adding areas to the list here
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
db.close();
Does anyone can help me with this please? Thx in advance!
SELECT COUNT(*) FROM tablename
To get the number of rows in the cursor, use getCount.
To get the amount of total rows in a table, either use reinierposts solution, or do a select which select all rows in the table and get the count from the cursor. I'm guessing his solution is quicker though unless you actually need all the rows in the table.
Such a query would be:
SELECT * FROM footable;
You don't really need to get a count of how many first; instead, create a db.getTitles() function that returns all of the rows and returns a Cursor, then loop over the Cursor. Right now you probably have a query that looks something like SELECT ColumnA, ColumnB FROM Titles WHERE id = 5; just copy the function, remove the parameter and take off the WHERE clause so it looks like just SELECT ColumnA, ColumnB FROM Titles.
Then your code would look something like this:
db.openDataBase(); // open connection with db
Cursor c = db.getTitles();
startManagingCursor(c);
//adding areas to the list here
if (c != null && c.moveToFirst()) {
do {
Area o1 = new Area();
o1.setOrderName(c.getString(1) + c.getString(2));
m_areas.add(o1);
} while (c.next());
}
db.close();
We check if the function returned a cursor at all, then move to the beginning of the cursor and start looping, going to the next item each time through. For more information on the Cursor interface see the API here, or to learn more about database access and related design practices better in general I suggest going through the Notepad tutorial.

Categories

Resources