Ormlite orderBy max(ColumnName) - android

Hi I need to use order by max(columnName) in ORMLite. I have the SQL query but I need to know how this query is used. This is my query:
SELECT * FROM table where place = 'somePlace' group by name
order by MAX (statusDate)
statusDate column contains date in "yyyy-dd-mm" format. The result I got is the list with recentDates.

Use a query builder, and function where and orderBy to preoceed
QueryBuilder<YourObject, Integer> q = yourDaoObject.queryBuilder();
Where<YourObject, Integer> wh = q.where();
wh.eq("place", "some_place");
q.orderBy("statusDate", false);
List<YourListOfObects> yourList = q.query();
But before that you should store a long instead to store your Date https://stackoverflow.com/a/6993420/2122876

i got same names with different dates and i need only the recent date.
If you are trying to get element from Table with the maximum statusDate then you should be doing an descending order-by with a limit of 1. Something like:
QueryBuilder<Foo, Integer> qb = fooDao.queryBuilder();
qb.where().eq("place", "some_place");
qb.orderBy("sttusDate", false); // descending sort
// get the top one result
qb.limit(1);
Foo result = qb.queryForFirst();

I did something like this. Please create your own query builder on the first line.
QueryBuilder<MyRowObject, Integer> queryBuiler = "Get Query builder" //getDaoXXX().queryBuilder();
MyRowObject firstLatestRow = queryBuiler.orderBy("dateColoumn", false).queryForFirst();
Hope this helps

Related

android sqlite query "!=" multiple whereargs [duplicate]

I have a rather big query that is returning data when executed outside android while returning nothing when executed within android.
I split the query in several pieces and determined that the union was ok.
I tried on a smaller set of data with the same behavior.
I've tested with different hardware and API versions.
I'm using the rawQuery method with constant values.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String, java.lang.String[])
This query was meant to replace a FULL OUTER JOIN which is not currently supported.
SELECT IFNULL(stype, gtype) AS type, IFNULL(sdate, gdate) AS date, IFNULL(sroute, groute) AS route FROM (
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM Sensor_Point AS sp LEFT JOIN GPS_Point AS gp ON gp._id IS NULL AND sp.sent=0 AND sp.route=gp.route AND sp.route=1
UNION ALL
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM GPS_Point AS gp LEFT JOIN Sensor_Point AS sp ON sp._id IS NULL AND gp.sent=0 AND sp.route=gp.route AND gp.route=1
) WHERE route=1 ORDER BY date ASC LIMIT 255
Any hints would be greatly appreciated.
Update:
Look's like the problem is finally with the query parameters, if I set it this way:
String[] args = new String[3];
args[0] = args[1] = args[2] = "1";
Cursor data dataBase.rawQuery(SELECT_POINTS, args);
It doesn't work, while it works when hardcoding values directly in the query.
Cursor data = dataBase.rawQuery(SELECT_POINTS, null);
In the Android database API, all query parameters are strings.
(This is a horrible design mistake.)
Your query corresponds to:
... AND sp.route='1'
Try to convert the parameter strings back into a number like this:
... AND sp.route = CAST(? AS INT)
or just put the number directly into the query string.

SQL MAX-MIN in ORMLITE - ANDROID

I want to know how can i use MAX MIN command with ORMLITE.
For example lets say we have this table
Table Name = Example
Column 1 = id
Column 2 = name
In ORMLITE how can i get max id ? I looked here but i didnt't understand exactly..
Can someone show me example about Max min in ORMLITE ?
QueryBuilder<Account, Integer> qb = accountDao.queryBuilder();
qb.selectRaw("MIN(orderCount)", "MAX(orderCount)");
// the results will contain 2 string values for the min and max
results = accountDao.queryRaw(qb.prepareStatementString());
String[] values = results.getFirstResult();
I found this from documentation
This is how I query for max ID in my code:
QueryBuilder<Example, String> builder = dao.queryBuilder();
builder.orderBy("id", false); // true or false for ascending so change to true to get min id
Example example = dao.queryForFirst(builder.prepare());
String id = null;
if (example == null)
id = "-1";
else
id = example.getId();
A couple of alternative answers can also be found here:
ORMLite - return item w/ maximum ID (or value)
You can use:
dao.queryRawValue("select MAX(columnName) from tableName")
It will directly return long value.
refer: http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_5.html#DAO-Methods
queryRawValue(String query, String... arguments)
Perform a raw query that returns a single value (usually an aggregate function like MAX or COUNT). If the query does not return a single long value then it will throw a SQLException.

Android development with sqlite: query result shouldn't be empty

I have a rather big query that is returning data when executed outside android while returning nothing when executed within android.
I split the query in several pieces and determined that the union was ok.
I tried on a smaller set of data with the same behavior.
I've tested with different hardware and API versions.
I'm using the rawQuery method with constant values.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String, java.lang.String[])
This query was meant to replace a FULL OUTER JOIN which is not currently supported.
SELECT IFNULL(stype, gtype) AS type, IFNULL(sdate, gdate) AS date, IFNULL(sroute, groute) AS route FROM (
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM Sensor_Point AS sp LEFT JOIN GPS_Point AS gp ON gp._id IS NULL AND sp.sent=0 AND sp.route=gp.route AND sp.route=1
UNION ALL
SELECT sp.type AS stype, sp.date AS sdate, -1 AS gtype, gp.date AS gdate, sp.route AS sroute, gp.route AS groute
FROM GPS_Point AS gp LEFT JOIN Sensor_Point AS sp ON sp._id IS NULL AND gp.sent=0 AND sp.route=gp.route AND gp.route=1
) WHERE route=1 ORDER BY date ASC LIMIT 255
Any hints would be greatly appreciated.
Update:
Look's like the problem is finally with the query parameters, if I set it this way:
String[] args = new String[3];
args[0] = args[1] = args[2] = "1";
Cursor data dataBase.rawQuery(SELECT_POINTS, args);
It doesn't work, while it works when hardcoding values directly in the query.
Cursor data = dataBase.rawQuery(SELECT_POINTS, null);
In the Android database API, all query parameters are strings.
(This is a horrible design mistake.)
Your query corresponds to:
... AND sp.route='1'
Try to convert the parameter strings back into a number like this:
... AND sp.route = CAST(? AS INT)
or just put the number directly into the query string.

How to update column with ORMLite

I have an already created database for Android application and I'm using ORMLite for query to SQLLite.
I have added a column in category and I want to insert data in that column.
I have row, e.g.
catId=5 catname="food" catType=?
I want to update catType on the basis of catId. How can I update this catType column with the catId in ORMLite.
I am using this approach:
Dao<Category, Integer> catDao = getHelper().getCategoryDao();
QueryBuilder<Category, Integer> queryBuilder = catDao.queryBuilder();
queryBuilder.where().eq("categoryId", 5);
PreparedQuery<Category> pq = queryBuilder.prepare();
Category category = catDao.queryForFirst(pq);
category.setCategoryType("BarType");
catDao.createOrUpdate(category);
Please provide me a better solution.
I want to update catType on the basis of catId. How can I update this catType column with the catId in ORMLite.
ORMLite also supports an UpdateBuilder. Here's how you could use it:
UpdateBuilder<Category, Integer> updateBuilder = catDao.updateBuilder();
// set the criteria like you would a QueryBuilder
updateBuilder.where().eq("categoryId", 5);
// update the value of your field(s)
updateBuilder.updateColumnValue("catType" /* column */, "BarType" /* value */);
updateBuilder.update();
See the UpdateBuilder docs for more examples.
Dao<Category, Integer> catDao = getHelper().getCategoryDao();
List <Category> categoryList = catDao.queryForAll();
for (Category c: categoryList ) {
c.setCategoryType("BarType");
catDao.update(c);
}

OrmLite Select within select using SelectArg to escape characters

I'm using the QueryBuilder to construct the inner SQL that later is used in a raw SQL to avoid escaping invalid characters manually.
SelectArg friendsIN = new SelectArg(friendsUsernames);
QueryBuilder<MyObject, Integer> qb = myObjectDao.queryBuilder();
qb.selectRaw("username", "MAX(time) AS latestTime").groupBy("username").where()
.in("username", friendsIN);
String innerSelect = pq.getStatement();
friendsUsernames is defined as ArrayList<String>.
Then I use the innerSelect to build the outer select:
String select = "SELECT w.id FROM (" + innerSelect +") AS x INNER JOIN myObject AS w on w.username = x.username AND w.time = x.latestTime";
GenericRawResults<String[]> results = myObjectDao.queryRaw(select);
But, as expected, the innerString has '?' and when I call queryRaw on myObjectDao I don't get any result. I tried to give friendsUsername as an array to queryRaw:
GenericRawResults<String[]> results =
myObjectrDao.queryRaw(select,
friendsUsernames.toArray(new String[friendsUsernames.size()]));
But I get the following error:
android.database.sqlite.SQLiteBindOrColumnIndexOutOfRangeException:
bind or column index out of range: handle 0x17a22e8
Any suggestions on how to accomplish this kind of queries with OrmLite?
Yeah that's not going to work. There is only one ? in your query and yet you are trying to pass in an array of user-names. There must be a 1-to-1 correspondence between the number of ? SQL arguments and the number of arguments passed to the queryRaw(...) method exactly.
If the friendsUsernames is a fixed size then you should be able to do something like the following which will generate SQL something like "in (?, ?, ?, ?)":
List<SelectArg> friendsInList = new ArrayList<SelectArg>();
for (int i = 0; i < NUM_FRIENDS; i++) {
// it doesn't matter what the value is since you just want the ?
fieldsInList.add(new SelectArg());
}
...in("name", friendsInList);
However if the list of names is dynamic then you are going to have to do this on the fly since, again, the number of ? must match the number of arguments passed to the queryRaw(...) method exactly.

Categories

Resources