I have two class:
public class Questionnaire {
#DatabaseField(generatedId=true, useGetSet=true)
private Long id;
#DatabaseField
private int type;
#DatabaseField
private String title;
#DatabaseField
private String description;
#ForeignCollectionField(eager = true)
private Collection<Question> questions;
// Get and Set omitted
and
public class Question {
#DatabaseField(generatedId=true, useGetSet=true)
private Long id;
#DatabaseField
private int type;
#DatabaseField
private String description;
#DatabaseField(foreign = true, foreignAutoRefresh= true)
private Questionnaire questionario;
//get and set ommited
When I save a Questionnaire with a List of Questions. The objects are persisted, but I lose the relationship.
I save in this way:
ForeignCollection<Question> questions =
getDao(Questionnaire.class).getEmptyForeignCollection("questions");
for(Question question : DataUtil.getAllQuestions()) {
questions.add(question);
}
Questionnaire questionnarie = new Questionnaire();
questionnarie.setQuestions(questions);
questionnarie.setTitle("Normal");
questionnarie.setDescription("Questionário normal");
getDao(Questionnaire.class).createOrUpdate(questionarie);
When I retrieved this register from database, a Question data doesn't have a reference for Questionnaire, and my Questionnaire doesn't have question list filled.
Any help will be appreciated.
The problem is that you are not setting the questionario field on your Question objects. The relationship is from the Question to the associated Questionnaire. There is nothing in the Questionnaire table that points the other way. See the documentation on foreign objects.
I would recommend doing something like the following:
Dao<Questionnaire, Long> dao = getDao(Questionnaire.class);
ForeignCollection<Question> questions =
dao.getEmptyForeignCollection("questions");
Questionnaire questionnarie = new Questionnaire();
questionnarie.setQuestions(questions);
questionnarie.setTitle("Normal");
questionnarie.setDescription("Questionário normal");
dao.createOrUpdate(questionarie);
for(Question question : DataUtil.getAllQuestions()) {
// you must set the questionnarie field on the Question
// if it is a generated-id, it must be set _after_ it has been created
question.setQuestionnaire(questionnarie);
questions.add(question);
}
Related
When I trying to get item index by below code.
Company company = getDefaultCompany();
companyArrayAdapter.getPosition(company);
I always to get result of -1. I don't understand what's wrong?
Because
companyArrayAdapter also have type Company.
private ArrayAdapter<Company> companyArrayAdapter;
Next you can see Company class declaration.
#DatabaseTable(tableName=Company.TABLE_NAME)
public class Company {
public static final String TABLE_NAME = "company";
#DatabaseField(id = true, columnName = "id")
private UUID id;
#DatabaseField(canBeNull=false)
private String name;
#DatabaseField
private String address;
#DatabaseField
private String phone;
#ForeignCollectionField(eager = false)
private ForeignCollection<Contract> contracts;
public Company(){
}
}
ArrayAdapter uses List.indexOf() method which and it can't compare your custom Company class objects and always returns "Not Found" index (-1).
So you should override getPosition() method int your custom adapter which extends ArrayAdapter:
#Override
public int getPosition(#Nullable Company company) {
/* here write logic of finding your company in companies list and retur index*/
return index;
}
P.S
If you had snippet of your custom adapter I would give you more detailed answer.
you can iterate through the loop of the list
var list=adapter.your_list
var toMatch=yourObject
for((index,elem) in list.withIndex()){
if(elem.someUniqueProperty == toMatch.someUniqueProperty){
var needed_index=index
}
}
I have the following Class:
#DatabaseTable
public class BodyWeight implements Serializable {
#DatabaseField(generatedId = true, useGetSet = true, columnName = "id")
private Long id;
#DatabaseField
private String name;
#DatabaseField
private double goal;
#DatabaseField
private String primaryunit;
#DatabaseField
private String secondaryunit;
#DatabaseField
private int secondarysize;
#DatabaseField
private Collection<Collection<Double>> data;
How could I add a list of list of doubles primitives to database? What is the process? Should I create more classes for the List of list of doubles?
One possible way would be to keep Collection<Collection<Double>> data in your class and store it as JSON string in database with using custom persister. Like this
#DatabaseField(persisterClass = MyCustomPersister.class)
Collection<Collection<Double>> data;
Where MyCustomPersister should implement com.j256.ormlite.field.DataPersister or one of available implementations. Basically just two methods:
#Override
public Object resultToSqlArg();
#Override
public Object sqlArgToJava();
How could I add a list of list of doubles primitives to database? What is the process?
This is pretty complex. One way is just to make the type be serializable.
#DatabaseField(dataType = DataType.SERIALIZABLE)
private Collection<Collection<Double>> data;
That, like #unnamed_b's answer will store it in place as a serialized block of bytes. This won't work if you have a large number of doubles however.
If you want to store it as objects in another table then you are going to have to define these objects. Something like:
#DatabaseField(generatedId = true)
private long id;
#ForeignCollectionField
private Collection<DoubleCollection> data;
ORMLite only handles straight collections so we need to define the sub-collection:
#DatabaseTable
public class DoubleCollection {
#DatabaseField(generatedId = true)
private long id;
#ForeignCollectionField
private Collection<DoubleWrapper> data;
}
If you need to store a collection of doubles then you need to define a wrapper to hold an id and your double value.
#DatabaseTable
public class DoubleWrapper {
#DatabaseField(generatedId = true)
private long id;
#DatabaseField
private double value;
}
I'm having issue on joining tables on ormlite. On the first load i have my pojo ready for insertion of data from api using retrofit and gson as the tools.
Here's my pojos:
public class ParticipantDetailsModel {
#DatabaseField(id = true)
private int id;
#DatabaseField
private String first_name;
#DatabaseField
private String last_name;
}
public class Trainings implements Serializable {
#DatabaseField
private int participant_id;
#DatabaseField
private int batch_id;
#DatabaseField
private int graduation_program_id;
#DatabaseField
private int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true, foreignAutoCreate = true)
private ParticipantDetailsModel participant;
}
On that Pojo i am actually getting duplicate field id which is "participant_id". So what i did is to rename this field from private ParticipantDetailsModel participant to private ParticipantDetailsModel participants, just for me to get the data. but once i query im not getting any values:
QueryBuilder<Trainings, String> qb1 = dao1.queryBuilder();
QueryBuilder<ParticipantDetailsModel, String> qb2 = dao2.queryBuilder();
qb1.where().eq("id", item.getId()).and().in("participant_id", parId);
List<Trainings> u = qb1.join(qb2).query();
do you have any idea what im missing?
heres my db:
enter image description here
Have a look at the Ormlite documentation
2.12 Foreign Object Fields
...
Notice that the name of the field is not account but is instead account_id. You will
need to use this field name if you are querying for it. You can set the column name using
the columnName field in the DatabaseField annotation
To set the columnName use:
public static final String ID_COLUMN = "ID";
#DatabaseField(columnName = ID_COLUMN)
private int id;
To make the query work, you have to set a Where clause on qb2 as well.
qb1.where().eq("id", item.getId());
qb2.where().in("id", parId);
List<Trainings> u = qb1.join(qb2).query();
Realm not saving (or possibly not returning) String values of related object...
i have 3 models:
public class Customer extends RealmObject {
#Expose
#PrimaryKey
private Long id;
#Expose
private Long historicalId;
#Expose
private String versionUUID;
#Expose
private String nameCompany;
#Expose
private String email;
#Expose
private String phoneNumber;
#Expose
private String notes;
#Expose
private boolean active;
#Expose
private boolean currentVersion;
#Expose
private Date lastUpdated;
#Expose
private Date dateCreated;
public Customer() {
}
and
public class Project extends RealmObject {
#PrimaryKey
private Long id;
private Long historicalId;
private String versionUUID;
private String name;
private String description;
private String addressLineOne;
private String addressLineTwo;
private String addressCity;
private String addressState;
private String addressZip;
private String notes;
private Date lastUpdated;
private Date dateCreated;
private boolean active;
private boolean currentVersion;
private Customer customer;
private String customerVersion;
public Project() {
}
and lastly (added for the comment question)
public class Receipt extends RealmObject {
#PrimaryKey
private String id;
private String name;
private String vendor;
private Double amount;
private String description;
private Date dateCreated;
private Date lastUpdated;
private Date dateSynced;
private byte[] imageByteArray;
private Project project;
private String projectVersion;
private int imgWidht;
private int imgHeight;
public Receipt() {
}
i am saving the data via:
public static void syncAllDataToRealm(Context context){
Globals globals = Globals.getInstance();
Realm realm = Realm.getInstance(context);
realm.beginTransaction();
realm.copyToRealmOrUpdate(globals.getAllCustomers());
realm.copyToRealmOrUpdate(globals.getAllProjects());
realm.commitTransaction();
testRealCommit(context);
}
and i am verifying the data via
private static void testRealCommit(Context context){
Realm realm = Realm.getInstance(context);
RealmQuery<Customer> customerRealmQuery = realm.where(Customer.class);
RealmResults<Customer> customerRealmResults = customerRealmQuery.findAll();
logger.debug(LogUtility.generateMessage(TAG, "===== CUSTOMER ======= "));
for(Customer c: customerRealmResults){
logger.debug(LogUtility.generateMessage(TAG, c.getId() + " - " + c.getNameCompany()));
}
logger.debug(LogUtility.generateMessage(TAG, "===== CUSTOMER GLOBAL======= "));
for(Customer c: Globals.getInstance().getAllCustomers()){
logger.debug(LogUtility.generateMessage(TAG, c.getId() + " - " + c.getNameCompany()));
}
RealmQuery<Project> projectRealmQuery = realm.where(Project.class);
RealmResults<Project> projectRealmResults = projectRealmQuery.findAll();
logger.debug(LogUtility.generateMessage(TAG, "===== PROJECT ======="));
for(Project p: projectRealmResults){
logger.debug(LogUtility.generateMessage(TAG, p.getId() + " - " + p.getName()));
}
}
for some reason:
c.getNameCompany()
returns a null in the above code... if i dont add the project data to realm it works fine....
realm is bein set up in my Application file via:
RealmConfiguration config = new RealmConfiguration.Builder(context)
.name("receiptbucket.realm")
.schemaVersion(2)
.build();
Realm.setDefaultConfiguration(config);
any ideas???
found out something else... if i swap the commit order, adding all customers after adding all projects it works
realm.copyToRealmOrUpdate(globals.getAllProjects());
realm.copyToRealmOrUpdate(globals.getAllCustomers());
short term fix but i would like to know why i have to do it this way for the customer data to stick...
(New Issue)
now when i call copyOrUpdate for the Receipt it wipes all the customer data Projects Customer....
From your last description, I think the problem is the Project list returned by globals.getAllProjects() contains some Customer which has null value for nameCompany .
The reason is your Customer class has an id which is annotated with #PrimaryKey, when realm.copyToRealmOrUpdate(globals.getAllProjects()) called, Realm will create or update related objects recursively. (That is the whole point of update here).
If it finds a customer which has the same id and already saved in the Realm, it will just use all new values from Project.customer to update the one existed in the Realm. If the Procject.customer.nameCompany is null, you will have the problem you described above.
The solution would be make the globals.getAllProjects() return the latest value you want to update, since there is no way for Realm to understand whether the null values are something you want to ignore or update to.
i was able to overcome the last error by querying realm and reattaching the Customer that was getting nulled out to the Project which is part of the Receipt....
so then i started playing.... I was loading realm from Global data... I stopped that and loaded realm right when i got the data from my rest service...
upon doing that everything started just working correctly, lol...
I'm using realm to store my data on Android. Awesome framework! Now the only problem I'm now having is:
I got a array list strings with id's of Countries in my database.
Now I retrieve my Drinks that contains a relationship to countries.
Is there a way that I could to do a query like this:
String [] ids;
realm.where(Drinks.class).equalsTo("country.id", ids);
Something like that?
Or do I really need to do a query to get me all drinks and then filter the list manually?
EDIT:
My classes:
public class Drinks extends RealmObject {
#PrimaryKey
private String id;
private String name;
private Country country;
}
public class Country extends RealmObject {
#PrimaryKey
private String id;
private String name;
}
What you want to do is possible with link queries in theory (searching for "country.id"), however link queries are slow. Also you'd need to concatenate a bunch of or() predicates together, and I would not risk that with a link query.
I would recommend using the following
public class Drinks extends RealmObject {
#PrimaryKey
private String id;
private String name;
private Country country;
#Index
private String countryId;
}
public class Country extends RealmObject {
#PrimaryKey
private String id;
private String name;
}
And when you set the Country in your class, you also set the countryId as country.getId().
Once you do that, you can construct such:
RealmQuery<Drinks> drinkQuery = realm.where(Drinks.class);
int i = 0;
for(String id : ids) {
if(i != 0) {
drinkQuery = drinkQuery.or();
}
drinkQuery = drinkQuery.equalTo("countryId", id);
i++;
}
return drinkQuery.findAll();
Since the Realm database has added RealmQuery.in() with the version 1.2.0
I suggest using something like this.
//Drinks
public class Drinks extends RealmObject {
#PrimaryKey
private String id;
private String name;
private String countryId;
//getter and setter methods
}
//Country
public class Country extends RealmObject {
#PrimaryKey
private String id;
private String name;
//getter and setter methods
}
The code to use inside activity/fragments to retrieve drink list
String[] countryIdArray = new String[] {"1","2","3"} //your string array
RealmQuery<Drinks> realmQuery = realm.where(Drinks.class)
.in("countryId",countryIdArray);
RealmResults<Drinks> drinkList = realmQuery.findAll();
In latest version of Realm 7+, you can use anyOf to match a field against a list of values.
anyOf("name", new String[]{"Jill", "William", "Trillian"})
in older versions, use in instead of anyOf and with kotlin use oneOf instead of in.
see this issue
To match a field against a list of values, use in. For example, to find the names “Jill,” “William,” or “Trillian”, you can use in("name", new String[]{"Jill", "William", "Trillian"}). The in predicate is applicable to strings, binary data, and numeric fields (including dates).
Doc.-> https://realm.io/docs/java/latest#queries