Realm query with List - android

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

Related

Room: error: Not sure how to convert a Cursor to this method's return type (void)

I have this query set up to return all the records from these tables and display the information on a recyclerview in android. the DB is set up using the Room persistence library aka SQLITE.
#Query
("SELECT moodBeforetable.userId,
moodBeforetable.moodBefore,
moodBeforetable.cbtId,
cbtTable.automaticThought,
cbtTable.twistedThinkingPK,
cbtTable.challengeThought,
cbtTable.rationalThought,
cbtTable.date,
moodAfterTable.moodAfter,
twistedThinkingTable.twistedThinkingPK,
twistedThinkingTable.allOrNothing,
twistedThinkingTable.blamingOthers,
twistedThinkingTable.catastrophizing,
twistedThinkingTable.emotionalReasoning,
twistedThinkingTable.fortuneTelling,
twistedThinkingTable.labelling,
twistedThinkingTable.magnifyingTheNegative,
twistedThinkingTable.mindReading,
twistedThinkingTable.minimisingThePositive,
twistedThinkingTable.overGeneralisation,
twistedThinkingTable.selfBlaming,
twistedThinkingTable.shouldStatement
FROM moodBeforetable
JOIN cbtTable ON moodBeforetable.cbtId = cbtTable.cbtId
JOIN twistedThinkingTable ON cbtTable.cbtId = twistedThinkingTable.cbtId
JOIN moodAfterTable ON moodAfterTable.cbtId = cbtTable.cbtId
WHERE moodBeforetable.date >= datetime('now', '-1 year')
AND moodBeforetable.userId = :userId
ORDER BY :date DESC")
LiveData<List<MoodBeforeTable>> moodLogsAll (int userId, String date);
When I try to compile the app I get the following error:
The query returns some columns which are not used by com.example.feelingfit.persistence.tables.MoodBeforeTable.
You can use #ColumnInfo annotation on the fields to specify the mapping.
Could anyone help me debug this and find out why the app wont compile?
Problem is Room cannot map the result from your custom query to existing MoodBeforeTable. It is because your return type is List<MoodBeforeTable> but you have used joins using TwistedThinkingTable and MoodAfterTable and so on.
What you should do is create a new POJO like below:
public class MoodLogPojo() {
private int userId;
private String moodBefore;
zprivate int cbtId;
private String automaticThought;
private int twistedThinkingPK;
private String challengeThought;
private String rationalThought;
private String date;
private String moodAfter;
private int twistedThinkingPK;
private String allOrNothing;
private String blamingOthers;
private String catastrophizing;
private String emotionalReasoning;
private String fortuneTelling;
private String labelling;
private String magnifyingTheNegative;
private String mindReading;
private String minimisingThePositive;
private String overGeneralisation;
private String selfBlaming;
private String shouldStatement;
// generate getters and setters too
public void setSelfBlaming(Stirng selfBlming) {
this.selfBlming = selfBlming
}
public String getSelfBlaming() { return selfBlaming; }
// and so on ...
}
Then use this class as the return type like :
LiveData<List<MoodLogPojo>> moodLogsAll (int userId, String date);.
NOTE: Mind the MoodLogPojo class. Modify it accoring to the corresponding data types from each Entity.

Problems with ArrayAdapter

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
}
}

How to store a object array by using Room in Android?

I want to cache a song-list in my app, the Song-list structure is like below:
#Entity
public class Songlist {
String _id;
String desc;
List<SongDesc> songWithComment;
.....
public static class SongDesc {
String comment;
Song song;
}
}
#Entity
pulbic class Song {
String name;
String type;
......
}
The lib of operating sqlite3 is android.arch.persistence.room, but it dosen't allow object references in a table.Is there any way to cache a song-list by using Room in Android?
Also if you want to store some custom objects, you can use #Embedded annotation like in example bellow :
class Address {
public String street;
public String state;
public String city;
#ColumnInfo(name = "post_code")
public int postCode;
}
#Entity
class User {
#PrimaryKey
public int id;
public String firstName;
#Embedded
public Address address;
}
If you want to save an ArrayList of some type into the database, you shuld use TypeConverter to convert the ArrayList from and into a simpler recognizable type to the database engine, like a String.
See this:
Android Room Database: How to handle Arraylist in an Entity?
and https://commonsware.com/AndroidArch/previews/room-and-custom-types

ORMlite how to add Collection<Collection<Double>>?

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;
}

Manually updating a foreign key.

I am pretty much aware of the absence of foreign keys in Realm. But I encountered this issue. I receive data in a normalised way and I have to figure out how to properly persist the relations.
Example:
class User{
private int id;
private Email email;
}
class Email{
private int id;
private String address;
}
And I receive something like:
{user={id:1, emailId:1}}
How can I store this type of data in my existing realm object ?
You will have to parse the JSON yourself to setup the links. From your description it isn't clear if you User and Email is already in Realm, but if that is the case I would do something like this:
class User{
#PrimaryKey
private int id;
private Email email;
}
class Email{
#PrimaryKey
private int id;
private String address;
}
JSONObject json = new JSONObject("{id:1, emailId:1}");
realm.beginTransaction();
User user = realm.where(User.class).equalTo("id", json.getInt("id")).findFirst();
Email email = realm.where(Email.class).equalTo("id", json.getInt("emailId")).findFirst();
user.setEmail(email);
realm.commitTransaction();

Categories

Resources