How to create DataTableConfig for a class with a ForeignCollection? - android

I have two legacy classes that I want to persist via ormlite 4.48.
Those classes can't be modified, so I can't use the nice annotations.
Fortunately, DatabaseTableConfig came to the rescue.
Here my classes:
public class RedditLink extends RedditType {
// Thing
private String id;
private String name;
private String kind;
private String data;
// Votable
private int ups;
private int downs;
// Uncomment if this ever matters private boolean likes;
// Created
private long created_utc;
// Link
private String author;
private String domain;
private int num_comments;
private boolean over18;
private boolean is_self;
private String permalink;
private String subreddit;
private String subredditId;
private String title;
private String url;
private String selftext;
private String thumbnail;
private RedditLinkList list;
... Getters and setters
}
and
public class RedditLinkList {
private int id;
public static final RedditLinkList EMPTY = new RedditLinkList();
public Collection<RedditLink> links = new ArrayList<RedditLink>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Collection<RedditLink> getLinks() {
return links;
}
public void setLinks(Collection<RedditLink> links) {
this.links = links;
}
}
I get the following error
java.lang.IllegalArgumentException: No fields have a DatabaseField annotation in class rainstudios.kelo.data.model.RedditLinkList
at com.j256.ormlite.table.DatabaseTableConfig.extractFieldTypes(DatabaseTableConfig.java:215)
at com.j256.ormlite.table.DatabaseTableConfig.fromClass(DatabaseTableConfig.java:146)
at com.j256.ormlite.table.TableInfo.<init>(TableInfo.java:53)
at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:151)
at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:128)
at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:107)
at com.j256.ormlite.dao.BaseDaoImpl$4.<init>(BaseDaoImpl.java:907)
at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:907)
at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:70)
at com.j256.ormlite.field.FieldType.configDaoInformation(FieldType.java:297)
at com.j256.ormlite.dao.BaseDaoImpl.initialize(BaseDaoImpl.java:201)
at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:128)
at com.j256.ormlite.dao.BaseDaoImpl.<init>(BaseDaoImpl.java:119)
at com.j256.ormlite.dao.BaseDaoImpl$5.<init>(BaseDaoImpl.java:921)
at com.j256.ormlite.dao.BaseDaoImpl.createDao(BaseDaoImpl.java:921)
at com.j256.ormlite.dao.DaoManager.doCreateDao(DaoManager.java:359)
at com.j256.ormlite.dao.DaoManager.createDao(DaoManager.java:129)
at com.j256.ormlite.table.TableUtils.createTable(TableUtils.java:229)
at com.j256.ormlite.table.TableUtils.createTableIfNotExists(TableUtils.java:84)
at com.octo.android.robospice.persistence.ormlite.InDatabaseObjectPersisterFactory.createTableIfNotExists(InDatabaseObjectPersisterFactory.java:106)
at com.octo.android.robospice.persistence.ormlite.InDatabaseObjectPersisterFactory.initializeTablesIfNeeded(InDatabaseObjectPersisterFactory.java:120)
at com.octo.android.robospice.persistence.ormlite.InDatabaseObjectPersisterFactory.createObjectPersister(InDatabaseObjectPersisterFactory.java:69)
at com.octo.android.robospice.persistence.CacheManager.getObjectPersister(CacheManager.java:183)
at com.octo.android.robospice.persistence.CacheManager.loadDataFromCache(CacheManager.java:68)
at com.octo.android.robospice.request.DefaultRequestRunner.loadDataFromCache(DefaultRequestRunner.java:239)
at com.octo.android.robospice.request.DefaultRequestRunner.processRequest(DefaultRequestRunner.java:88)
at com.octo.android.robospice.request.DefaultRequestRunner$1.run(DefaultRequestRunner.java:201)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Here is the code I use to generate my DatabaseFieldConfig :
//
// Link
//
List<DatabaseFieldConfig> fieldConfigs = new ArrayList<DatabaseFieldConfig>();
DatabaseFieldConfig field1 = new DatabaseFieldConfig("id");
field1.setId(true);
fieldConfigs.add(field1);
DatabaseFieldConfig field2 = new DatabaseFieldConfig("name");
field2.setCanBeNull(false);
fieldConfigs.add(field2);
DatabaseFieldConfig field3 = new DatabaseFieldConfig("url");
fieldConfigs.add(field3);
DatabaseFieldConfig field4 = new DatabaseFieldConfig("title");
fieldConfigs.add(field4);
DatabaseFieldConfig field6 = new DatabaseFieldConfig("author");
fieldConfigs.add(field6);
DatabaseFieldConfig field5 = new DatabaseFieldConfig("subreddit");
fieldConfigs.add(field5);
// #DatabaseField(foreign = true, foreignAutoRefresh = true,
// canBeNull =
// true, columnName = "list_id")
DatabaseFieldConfig field7 = new DatabaseFieldConfig("list");
field7.setForeign(true);
field7.setForeignAutoRefresh(true);
field7.setCanBeNull(true);
field7.setColumnName("list_id");
fieldConfigs.add(field7);
DatabaseTableConfig<RedditLink> link = new DatabaseTableConfig<RedditLink>(
RedditLink.class, fieldConfigs);
//
// List
//
List<DatabaseFieldConfig> fieldListConfigs = new ArrayList<DatabaseFieldConfig>();
DatabaseFieldConfig fieldList1;
fieldList1 = new DatabaseFieldConfig("id");
fieldList1.setColumnName("list_id");
fieldList1.setGeneratedId(true);
fieldListConfigs.add(fieldList1);
DatabaseFieldConfig fieldList2 = new DatabaseFieldConfig("links");
fieldList2.setForeignCollection(true);
fieldList2.setForeignCollectionEager(false);
fieldListConfigs.add(fieldList2);
DatabaseTableConfig<RedditLinkList> list = new DatabaseTableConfig<RedditLinkList>(
RedditLinkList.class, fieldListConfigs);
// Cross references
field7.setForeignTableConfig(list);
fieldList2.setForeignTableConfig(link);
What am I doing wrong?
Note: my app uses ormlite_config.txt cache

Related

Select rows comparing two column value in ormlite while using raw query

I have the following database table
#DatabaseTable(tableName = "Order_Details")
public class DB_OrderDetails {
#DatabaseField(generatedId = true)
private int id;
#DatabaseField()
private int order_id_from_order_table;
#DatabaseField()
private String medicine_code;
#DatabaseField()
private String medicine_name;
#DatabaseField()
private String medicine_type;
#DatabaseField()
private int number_of_units_ordered;
#DatabaseField()
private String generic_name;
#DatabaseField()
private String manufacturer_name;
#DatabaseField()
private double ordering_cost;
... }
I am using ormlite for my local db operations. i want to get the result for
SELECT * FROM Order_Details WHERE (medicine_code='xxxx' AND manufacturer_name='yyyy')
and want to get the result returned in
List<DB_OrderDetails>
can anybody suggest me a way to do it?
Use an object of the Where class to build your query.
List<DB_OrderDetails> list;
try {
Dao<DB_OrderDetails, String> dbOrderDetailsStringDao = dbHelper.getOrderDetailsDao();
QueryBuilder<DB_OrderDetails, String> queryBuilder = dbOrderDetailsStringDao.queryBuilder();
Where where = queryBuilder.where();
where.eq("medicine_code", "xxxx");
where.and();
where.eq("manufacturer_name", "yyyy");
PreparedQuery<DB_OrderDetails> preparedQuery = queryBuilder.prepare();
list = dbOrderDetailsStringDao.query(preparedQuery);
} catch (SQLException e) {
e.printStackTrace();
}

GreenDao how to filter data and retrieve it

I have a table with entries such as:
private Long id;
private String Date;
private String Time;
private String newEntry;
private String description;
private byte[] images;
I use this for a calendar and I want it to display only entries from that day. How do I go about doing that?
Currently it retrieves all the entries and displays it ina listview:
List<Box> list = BoxRepository.getAllBoxes(getApplicationContext());
Toast.makeText(getBaseContext(), "Size = " + list.size(), Toast.LENGTH_SHORT).show();
arrayEntry.clear();
for (Box box : list)
arrayEntry.add(box);
adapterEntry.notifyDataSetChanged();
}
My guess was that I could add a method here but I failed:
public static long insertOrUpdate(Context context, Box box) {
return getBoxDao(context).insertOrReplace(box);
}
public static void clearBoxes(Context context) {
getBoxDao(context).deleteAll();
}
public static void deleteBoxWithId(Context context, long id) {
getBoxDao(context).delete(getBoxForId(context, id));
}
public static List<Box> getAllBoxes(Context context) {
return getBoxDao(context).loadAll();
}
public static Box getBoxForId(Context context, long id) {
return getBoxDao(context).load(id);
}
private static BoxDao getBoxDao(Context c) {
return ((DatabaseManager) c.getApplicationContext()).getDaoSession().getBoxDao();
}
I don't now how you format the date, but it should be something like that:
helper = new DaoMaster.DevOpenHelper(this, "your database", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
boxDao= daoSession.getBoxDao();
QueryBuilder queryBuilder = boxDao.queryBuilder()
.where(BoxDao.Properties.Date.eq("something to compare"));
List<Box> list = queryBuilder.list();
Also, you could use the Date type for the Box.Date property in order to use the Date comparators:
QueryBuilder queryBuilder = boxDao.queryBuilder()
.where(BoxDao.Properties.Date.eq(new Date()));
or
QueryBuilder queryBuilder = boxDao.queryBuilder()
.where(BoxDao.Properties.Date.between(date1, date2));

Objectify projection queries returning null

I can't seem to get my projection query to return anything but null, not sure what I'm doing wrong.
Here's the code where I set up and call the query:
Query query1 = OfyService.ofy().load().type(CargoEntity.class).
project("imageUrl", "latitude", "longitude").distinct(false); //filter("group", group);
// Execute the query:
List<Entity> results = query1.list();
logger.warning("(Query from datastore results.isEmpty()) : " + (results.isEmpty()));
logger.warning("(Group = ) : " + group);
if (!results.isEmpty()) {
logger.warning("(Query from datastore results.size()) : " + (results.size()));
//Create STRTree-Index.
STRtree strTree = new STRtree();
GeometryFactory gf = new GeometryFactory();
//Loop through the result list from DataStore.
for (Entity result : results) {
STRLeaf leaf = new STRLeaf((float)result.getProperty("latitude"), (float)result.getProperty("longitude"), (String)result.getProperty("imageUrl"));
Coordinate coord = new Coordinate(leaf.getLongitude(), leaf.getLatitude());
Point point = gf.createPoint(coord);
//Add result to index.
strTree.insert(point.getEnvelopeInternal(), leaf);
}
I'm really new to this so it could be something obvious that i'm missing. I do see the indexes in the developers console though. Here's what the properties in my Entity looks like:
#Entity
#Index
#Cache
public class CargoEntity {
//datastore key
#Id
private String imageUrl;
private float latitude;
private float longitude;
private String group;
#Unindex
private int rating;
#Unindex
private Blob image;
#Unindex
private String email;
#Unindex
private String userName;
#Unindex
private String description;
#Unindex
private Date date;
#Unindex
private String blobKey;
#Unindex
private String type;
#Unindex
private boolean flag;
#Unindex
private int photoOrientation;
public CargoEntity() {
}
//getters and setters below
So apparently I was adding the Entity id to the projection query which is not allowed (or it is allowed but returns null). This post answered the problem.
Google App Engine projection query returns 0 results

How to delete an object where it consist with multiple objects in ORM-Lite

I am using ORM-lite for an Android application, Model class is as follows,
#DatabaseTable(tableName = "pageimage")
public class PageImage
{
#DatabaseField(generatedId = true)
private int pageimageId;
#DatabaseField(foreign = true, foreignAutoRefresh = true, uniqueCombo=true)
private Page page;
#DatabaseField(foreign = true, foreignAutoRefresh = true, uniqueCombo=true)
private Image image;
#DatabaseField
private int order;
//implementation
}
PageImage object is created with combination of Page and Image objects referenced to Page and Image tables. i have searched a lot but still unable to find a away to delete a PageImage object where Page id = "some value" and Image id = "some value" .
Appreciate any ideas.
You can use DeleteBuilder to do that.
private void deletePageItem(Page page, Image image) {
try {
Dao<PageItem, ?> dao = mOpenHelper.getDao(PageItem.class);
DeleteBuilder<PageItem, ?> deleteBuilder = dao.deleteBuilder();
deleteBuilder.where().eq(PageItem.COLUMN_IMAGE, image).and().eq(PageItem.COLUMN_PAGE, page);
deleteBuilder.delete();
} catch (SQLException e) {
e.printStackTrace();
}
}
where mOpenHelper is entity extended from OrmLiteSqliteOpenHelper
PageItem.java
#DatabaseTable(tableName = "pageimage")
public class PageItem {
public static final String COLUMN_PAGE = "page";
public static final String COLUMN_IMAGE = "image";
#DatabaseField(generatedId = true)
private int pageimageId;
#DatabaseField(columnName = COLUMN_PAGE, foreign = true, foreignAutoRefresh = true, uniqueCombo = true)
private Page page;
#DatabaseField(columnName = COLUMN_IMAGE, foreign = true, foreignAutoRefresh = true, uniqueCombo = true)
private Image image;
#DatabaseField
private int order;
}

Ormlite - deleting nested objects from ForeignCollection but not from database

I have ContactItem which contains ForeignCollection of GroupItem:
public class ContactItem implements Parcelable{
#DatabaseField(generatedId = true)
private Integer id;
#DatabaseField(dataType = DataType.STRING, columnName = Constants.CONTACT_NAME)
private String name;
#DatabaseField(dataType = DataType.STRING, columnName = Constants.CONTACT_NUMBER)
private String number;
#DatabaseField(dataType = DataType.INTEGER, columnName = Constants.CONTACT_ICON)
private int icon;
#DatabaseField(dataType = DataType.INTEGER, columnName = Constants.CONTACT_DAYS)
private int days;
#DatabaseField(foreign=true,canBeNull = true,foreignAutoRefresh = true,columnName = Constants.CONTACT_GROUP)
private GroupItem group;
#ForeignCollectionField(columnName = Constants.CONTACT_GROUP_LIST)
private ForeignCollection<GroupItem> groups;
}
and GroupItem, which contains ForeignCollection of ContactItem:
public class GroupItem implements Parcelable{
#DatabaseField(generatedId = true)
private Integer id;
#DatabaseField(dataType = DataType.STRING, columnName = Constants.GROUP_NAME)
private String name;
#DatabaseField(dataType = DataType.INTEGER, columnName = Constants.GROUP_ICON)
private int icon;
#DatabaseField(dataType = DataType.INTEGER, columnName = Constants.GROUP_COUNT)
private int count;
#DatabaseField(foreign=true,canBeNull = true,foreignAutoRefresh = true, columnName = Constants.GROUP_CONTACT)
private ContactItem contact;
#ForeignCollectionField(eager = true, columnName=Constants.GROUP_CONTACTS_LIST)
private ForeignCollection<ContactItem> contacts;
#DatabaseField(dataType = DataType.INTEGER, columnName = Constants.GROUP_DAYS)
private int days;
}
and i need to delete ContactItem from GroupItem's ForeignCollection of ContactItems. I do it like that:
public void removeContactFromGroup(GroupItem group, ContactItem contact)
{
DatabaseHandler db = new DatabaseHandler(context.getApplicationContext());
Dao<GroupItem,Integer> daoGroup = null;
Dao<ContactItem,Integer> daoContact = null;
GroupItem newGroup = null;
try {
daoGroup = db.getGroupDao();
daoContact = db.getContactDao();
UpdateBuilder<GroupItem, Integer> updateBuilder = daoGroup.updateBuilder();
newGroup = daoGroup.queryForId(group.getId());
if ( newGroup.getContactCollection().contains(contact))
{
}
}
catch(Exception e)
{
Log.i(" saveGroupContacts database problem","It is cause problem");
e.printStackTrace();
}
}
but it delets ContactItem from whole database. But I need to remove it only from ForeignCollection. How can I implement this?
I solved my issue by maybe not elegant, but workable solution : I simply set my nested object in those, which contains it to null and update object-container with dao :
public void removeContactFromGroup(GroupItem group, ContactItem contact)
{
DatabaseHandler db = new DatabaseHandler(context.getApplicationContext());
Dao<GroupItem,Integer> daoGroup = null;
Dao<ContactItem,Integer> daoContact = null;
GroupItem newGroup = null;
ContactItem contactFromDb = null;
try {
daoGroup = db.getGroupDao();
daoContact = db.getContactDao();
UpdateBuilder<GroupItem, Integer> updateBuilder = daoGroup.updateBuilder();
newGroup = daoGroup.queryForId(group.getId());
contactFromDb = daoContact.queryForId(contact.getId());
contactFromDb.setContactGroup(null);
daoContact.update(contactFromDb);
}
catch(Exception e)
{
Log.i(" saveGroupContacts database problem","It is cause problem");
e.printStackTrace();
}
}
Worked for me.

Categories

Resources