Raw query to Ormlite (JOINS,GROUPBY) correct way - android

i am using ormlite version 4.46 I am able to get the desired result when i run a raw query but somehow the result is null when i am trying it in ormlite can someone please explain where i am making a mistake.
Snippet:
String query=
"SELECT Products.* FROM "+DBConst.TABLE_PRODUCTS
+" INNER JOIN "+DBConst.TABLE_OFFERS_MAPPING
+" ON Products."+DBConst.PROD_ID+" = OffersMapping."+DBConst.OFFERS_PRODUCT_ID
+" WHERE "+DBConst.OFFERS_OFFER_ID+ " = "+offerId+
" GROUP BY "+DBConst.PROD_PARENT_PRODVAR_ID;
GenericRawResults<Product> rawResults = productDao.queryRaw(query, productDao.getRawRowMapper());
//produces this query:SELECT Products.* FROM Products INNER JOIN OffersMapping ON Products._id = OffersMapping.product_id WHERE offer_id = 141 GROUP BY variant_id
List<Product> prodList = rawResults.getResults();
rawResults.close();
Gives me desired result....
Now to ormlite
Dao<Product, String> productDao = helper.getProductDao();
Dao<OfferMapping, String> offerMappingDao = helper.getOfferMappingDao();
try {
QueryBuilder<Product, String> productQb = productDao.queryBuilder();
QueryBuilder<OfferMapping, String> offerQb = offerMappingDao.queryBuilder();
//to sort the offer id accordingly
offerQb.where().eq(DBConst.OFFERS_OFFER_ID, offerId);
productQb.where().eq(DBConst.PROD_ID, new ColumnArg(DBConst.OFFERS_PRODUCT_ID));
productQb.join(offerQb);
productQb.groupBy(DBConst.PROD_PARENT_PRODVAR_ID);
Constants.showLog("Query", "Query is "+productQb.query());//gets null here
List<Product> prodList = productQb.query();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
Dont know where i am making a mistake...

i am using ormlite version 4.46 I am able to get the desired result when i run a raw query but somehow the result is null when i am trying it in ormlite can someone please explain where i am making a mistake.
Sorry for the late response. I would log the generated query from the ORMLite query-builder and then compare it with your hand generated query. You can log the results of productQb.prepareStatementString() before the query is performed. For more information see the logging documentation.
Let me know if ORMLite is doing something wrong.

Related

Send Data from SQLite to appServer using POST,OKHttp

I have an SQLite Db which stores call logs. Each entry has a number, date, and duration. I have seen that there are many ways we can send the data to the app server. As a JSON String and send one by one from an ArrayList of model class objects.
Which is the correct way to approach this? And how can I create a JSON from these data, I have done as much as getting these data to an ArrayList of objects. since each entry has many data, I am confused about how to do this.
public ArrayList<PhNumber> getCallLogs() {
ArrayList<PhNumber> callLogList;
callLogList = new ArrayList<PhNumber>();
String selectQuery = "SELECT * FROM callInfo where syncStatus = '" + "no" + "'";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
callLogList.add(new PhNumber(Integer.parseInt(cursor.getString(0)), cursor.getString(1),
cursor.getString(2),
cursor.getString(3),
cursor.getString(4)));
Log.e("DbHelper:getCallLogs", callLogList.toString());
} while (cursor.moveToNext());
}
return callLogList;
}
Which is the correct way to approach this?
There is not any one solution . It depends on your use case scenario.
For making JSON , you can do this after getting your data in ArrayList<PhNumber> callLogList
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < callLogList.length(); i++) {
JSONObject jsonobject= new JSONObject();
jsonobject.put("data1",callLogList.get(i).get); //I dont know the field name of your PhNumber so fill accordingly
jsonobject.put("data2",callLogList.get(i).get);
jsonArray.put(jsonobject);
}
I would suggest you to use Retrofit for this, a library that is very easy to use, saves lot of time and code. Serialization and HTTP requests are handled seamlessly using Retrofit.
please refer to this article for simple understanding of Retrofit

Parse - Empty Table Checking

How to check if table is empty using parse , I'm having a problem with the code below :
private String[] getMaxDateMessage() throws ParseException {
final String[] msgData = new String[3];
ParseObject ob = null;
String[] userIds = {currentUserId, recipientId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(userIds));
query.whereContainedIn("recipientId", Arrays.asList(userIds));
query.orderByDescending("createdAt");
if(query.hasCachedResult())
{
ob = query.getFirst();
if (ob.isDataAvailable()) {
//for (int i = 0; i < 1; i++) {
//createdDate[0] = messageList.get(i).get("createdAt").toString();
msgData[0] = ob.getCreatedAt().toString();
msgData[1] = ob.get("senderId").toString();
msgData[2] = ob.get("recipientId").toString();
// }
}
}
The thing is that the table is empty , so the query should return null , but no exception is been throwed , it just crashes the app .
So how can I check if the table is empty before trying to fetch any data ?
Update : The solution that I have found is to use query.count().
If the count returns a value that is not 0 then the table is not empty .
Using query.count() to determine if the table is empty is not an optimal solution. While this is perfectly fine when actually run against an empty table, using query.count() will almost always result in a sub-optimal query when there's more than one object in the table. The reason for this is quite clear: you only care about the first object matched by this query, yet a query.count() will scan the whole table in order to return the total of objects that match your query.
Therefore, the ideal solution is to simply use query.getFirst() and check if you get any results. You should be able to handle the case where ob is not a ParseObject, e.g. the collection is either empty or no objects match your query.

OrmLite: Advanced where logic

I have these tables in an Android based application where I'm using OrmLite for the database management.
What I want to have an x number of array list depending on how many of the product type FOLDER I have.
So in this case I want to a list of products where the productId equals parentId.
So I want a list where
if(productType = FOLDER) {
if(productId = parentId){
//add product
}
}
Basically what I want to end up with, in this case three lists with each containing a list of products where parentId is the same for every product.
I've tried many things, and some works better than others, but a code I want to run actually throws a nullpointer.
DatabaseHelper dbHelper = getHelper();
List<Product> productsParents = null;
try {
Dao<Product, Integer> dao = dbHelper.getDao();
PreparedQuery<Product> prepQu = dao.queryBuilder().where()
.eq("parentId", dao.queryBuilder().selectColumns("productId").where()
.eq("productType", ProductType.FOLDER).prepare()).prepare();
productsParents = dao.query(prepQu);
} catch (SQLException e) {
...
}
This code isn't working because productParents returns null, and it does not do what I want, even though it's a slight hint. If someone know how to do this in code that would be sufficient also, or more likely a mix of java and ormlite.
Have you had a chance to RTFM around building queries? The ORMLite docs are pretty extensive:
http://ormlite.com/docs/query-builder
Your problem is that a prepared query cannot be an argument to the eq(...) method. Not sure where you saw an example of that form.
So there are a couple ways you can do this. The easiest way is to do a different query for each productType:
Where<Product, Integer> where = dao.queryBuilder().where();
where.eq("parentId", parentId).and().eq("productType", ProductType.FOLDER);
productsParents = where.query();
// then do another similar query again with ProductType.PRODUCT, ...
If you want to do just one query then you can get all products that match the parentId and then separate them using code:
Where<Product, Integer> where = dao.queryBuilder().where();
where.eq("parentId", parentId);
productsParents = where.query();
List<Product> productFolders = new ArrayList<Product>();
List<Product> productProducts = new ArrayList<Product>();
...
for (Product product : productsParents) {
if (product.getProductType() == ProductType.FOLDER) {
productFolders.add(product);
} else if (product.getProductType() == ProductType.PRODUCT) {
productProducts.add(product);
} else ...
}

Sql lite gets all data sent to webservice JSon format in android?

I am creating local database I want to send all data sent to web service.
For example product name one column. Lots of product name is there. I want to send it.
& Product name = briyani,egg,rice
I got all details from database below i have mention code:
public String fetchMyRowid(String column_name)
{
String query = "select "+column_name+" From " + TABLErestaurant;
mCursor =db.rawQuery(query, null);
StringBuffer buf = new StringBuffer();
if (mCursor.moveToNext()) {
buf.append(mCursor.getString(0));
String str = buf.toString();
System.out.println("**************"+str);
}
return buf.toString();
}
}
return buf.toString();
}
In class :
HashMap<String, String> paramsvalue = new HashMap<String, String>(); paramsvalue.put("product_name", dataBase.fetchMyRowid(DatabaseHelper.columnproductname));
But I have some issue. I got only one product name. I need all product name. Can any one suggest solution for this.
wel come to stackoveflow,
Please check below link in that i have first select all table's recode then i have created one another method for get all columns value by row. after that i have marge all data in to JSON. this is idea you have to do similar way...
https://stackoverflow.com/a/10600440/1168654

Android ormlite like() function is not working

I am new to this, please help me.
I am trying to use ormlite like(column name,value) function, but this is not working for me. But when I test full text it is working like "eq" function.
My Code is,
try {
QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
qb.where().like("madeCompany", filterKey);
PreparedQuery<MakeDTO> pq = qb.prepare();
return makeDao.query(pq);
} catch (SQLException e) {
throw new AppException(e);
}
Thanks.
An old question, but something I just solved (ORMLite's documentation isn't that clear). you need to wrap your query parameter in "%"'s in order to tell ORMLite which side of your query string can match any number of characters.
For example, if you want your query to match any madeCompany that contains your string use the following:
try {
QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
qb.where().like("madeCompany", "%"+filterKey+"%");
PreparedQuery<MakeDTO> pq = qb.prepare();
return makeDao.query(pq);
} catch (SQLException e) {
throw new AppException(e);
}
Pretty simple, you're asking it to be exactly the string 'madeCompany', if you want to do partial matching you need to use the % wildcard etc.
public Where<T,ID> like(java.lang.String columnName,
java.lang.Object value)
throws java.sql.SQLException
Add a LIKE clause so the column must mach the value using '%' patterns.
Throws:
java.sql.SQLException
Where.like(java.lang.String, java.lang.Object)
The answers above can resolved the like query problem, but has SQL injection risk. If the value of 'filterKey' is ', it will cause SQLException, because the SQL will be SELECT * FROM XXX WHERE xxx LIKE '%'%'. You could use SelectArg to avoid, example for this case:
try {
String keyword = "%"+filterKey+"%";
SelectArg selectArg = new SelectArg();
QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
qb.where().like("madeCompany", selectArg);
PreparedQuery<MakeDTO> pq = qb.prepare();
selectArg.setValue(keyword);
return makeDao.query(pq);
} catch (SQLException e) {
throw new AppException(e);
}
Reference: http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_3.html#index-select-arguments

Categories

Resources