0

I have these tables in an Android based application where I'm using OrmLite for the database management.

enter image description here

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.

4

1 回答 1

1

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 ...
} 
于 2013-07-22T14:02:11.467 回答