Realm: How to query with many to many field - android

I recently heard about Realm for android (also available for iOS) in this talk by Joaquim Verques . Very interesting and very powerful tool for persistent data.
I decided to give it a try after the video, researching and reading the documentation.
I found it very easy to use and set up but i end up stuck in the middle of my project because i couldn't manage to successfully make a query with many to many relationships.
I have created a small example for this topic.
My models:
public class Feed extends RealmObject {
#PrimaryKey
private int id;
private String title;
private String description;
private String link;
private Terms terms;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Terms getTerms() {
return terms;
}
public void setTerms(Terms terms) {
this.terms = terms;
}
}
public class Terms extends RealmObject {
private String tag;
private RealmList<Category> categories;
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public RealmList<Category> getCategories() {
return categories;
}
public void setCategories(RealmList<Category> categories) {
this.categories = categories;
}
}
public class Category extends RealmObject {
#PrimaryKey
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
So far so good, now im going to save a list of feeds to realm (make it persistent) and then try to make some query.
public static void test(final Context context,final List<Feed> feedList) {
Realm realm = null;
try {
realm = Realm.getInstance(context);
realm.beginTransaction();
realm.copyToRealmOrUpdate(feedList);
realm.commitTransaction();
RealmResults<Feed> realmResults = realm.where(Feed.class).findAll();// return me all feeds
RealmResults<Feed> realmResults1 = realm.where(Feed.class).equalTo("id", 1).findAll(); // return feed with id 1
RealmResults<Feed> realmResults2 = realm.where(Feed.class).equalTo("terms.tag", "tech").findAll(); // return feeds //with tag = "tech"
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.category.name", "test").findAll(); //exception here
}
} catch (Exception e) {
//Empty
Log.d("Test","",e);
} finally {
if (realm != null)
realm.close();
}
}
}
Everything run well untill the last query and i get this exception:"java.lang.IllegalArgumentException: Invalid query: category does not refer to a class."
So my question is How do i do that kind of query successfully, as i will like realm to return me every feed with terms which has at least 1 category with name = "test"
Thank you very much

Your field is called "categories" and not "category". The third query should be:
RealmResults<Feed> realmResults3 = realm.where(Feed.class).equalTo("terms.categories.name", "test").findAll();

Related

what does a folder named Bean mean in Android?

I've seen an Android project structure in the image below. What does "Bean" mean in this structure? or Why does that folder name "Bean"?
Bean in java is basically a single class encapsulate many objects into a single object and there properties can be manipulated by using getter and setter method.We also call it model class. The below code snippet is an example of bean class.
public class Book implements Serializable{
private String isbn;
private String title;
private String author;
private String publisher;
private int pages;
/**
* Default constructor
*/
public Book() {
this.isbn = "";
this.title = "";
this.author = "";
this.publisher = "";
this.pages = 0;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(final String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(final String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(final String author) {
this.author = author;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(final String publisher) {
this.publisher = publisher;
}
public int getPages() {
return pages;
}
public void setPages(final int pages) {
this.pages = pages;
}
}
In your case i think the package you pointed contained all the bean classes

Realm optional way for foreign key

I am new to Realm. Actually, Realm doesn't provide us functionality for Foreign key and I want to use the functionality of Foreign key.
So Here is my model :
public class CategoryInfo extends RealmObject {
#SerializedName("name")
String name;
#SerializedName("id")
int id;
#SerializedName("sub_category")
RealmList<SubCategoryInfo> subCategoryList;
public Data() {
}
public Data(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSubCategory(RealmList<SubCategoryInfo> subCategoryList) {
this.subCategoryList = subCategoryList;
}
public RealmList<SubCategoryInfo> getSubCategoryList() {
return subCategoryList;
}
}
public class SubCategoryInfo extends RealmObject {
#SerializedName("sub_cat_name")
String subCatName;
#SerializedName("sub_id")
int subId;
int catId;
public String getSubCatName() {
return subCatName;
}
public void setSubCatName(String subCatName) {
this.subCatName = subCatName;
}
public int getSubId() {
return subId;
}
public void setSubId(int subId) {
this.subId = subId;
}
public void setCatId(int catId) {
this.catId = catId;
}
}
So now when I am getting a response from API side I am updating my object by below code to add catId in SubCatInfo class.
List<CategoryInfo> catInfoList = catResult.getData();
for(CategoryInfo catInfo:catInfoList){
List<SubCategoryInfo> subCatList = catInfo.getSubCategoryList();
if (subCatList != null) {
for (SubCategoryInfo subCatInfo:SubCategoryInfo) {
subCatInfo.setCatId(catInfo.getId());
}
}
}
So What I want is that when I will delete any category from the main table, subCategory should be automatically deleted. So By what way I can achieve this functionality?
Thank you in advance.

Missing object when using #SerializedName with Retrofit call

I'm developing an Android app which connects to a Springboot server.
The app (using okhttp3 and retrofit) calls the server which returns an array list in an object (Photo Response) below.
The list is populating but the object MediaContentGroup does not populate in any photo object even though the fields of id and title do.
I've debugged through my server to ensure that I am using the correct object names when using #SerializedName.
I'm pretty new to Android development and using springboot, so if anyone could help me to understand why the MediaContentGroup object is always null, I would really appreciate it.
Is there any possible way I've set it to only accept Strings??
Thanks
public class PhotoResponse {
#SerializedName("photoFeed")
#Expose
private PhotoFeed photoFeed;
public PhotoFeed getPhotoFeed() {
return photoFeed;
}
}
public class PhotoFeed {
#SerializedName("photoList")
#Expose
private List<Photo> photoList = new ArrayList<>();
public List<Photo> getPhotoList() {
return photoList;
}
}
public class Photo {
public final static int HD_720_WIDTH = 1280;
public final static int HD_720_HEIGHT = 720;
#SerializedName("id")
#Expose
private String id;
#SerializedName("title")
#Expose
private String title;
#SerializedName("mediaContentGroup")
#Expose
private MediaContentGroup mediaContentGroup;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setMediaContentGroup(MediaContentGroup mediaContentGroup){
this.mediaContentGroup = mediaContentGroup;
}
public MediaContentGroup getMediaContentGroup(){
return this.mediaContentGroup;
}
public String getImageUrl() {
return mediaContentGroup.getImages().get(0).getUrl();
}
public String getThumbUrl() {
return mediaContentGroup.getThumbnails().get(0).getUrl();
}
}
public class MediaContentGroup {
#SerializedName("images")
#Expose
public List<MediaContent> images = new ArrayList<>();
public void setImages(List<MediaContent> images){ this.images = images;}
public List<MediaContent> getImages() {
return images;
}
#SerializedName("thumbnails")
#Expose
public List<Thumbnail> thumbnails = new ArrayList<>();
public void setThumbnails(List<Thumbnail> thumbnails){ this.thumbnails = thumbnails;}
public List<Thumbnail> getThumbnails() {
return thumbnails;
}
}
public class Thumbnail {
#SerializedName("url")
#Expose
private String url;
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}

Professional way to handle model classes when using GSON and SQLight Android app

In My application I get data from a web service and display those data in recycler view. After that I'm planing to add those data in to local sqlite database and display those data when user open application without internet connection.
Here's a simple model class I'm using to pars JSON result using GSON
public class Repo implements Parcelable {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String url;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.name);
dest.writeString(this.url);
}
public Repo() {
}
protected Repo(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.name = in.readString();
this.url = in.readString();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public static final Creator<Repo> CREATOR = new Creator<Repo>() {
#Override
public Repo createFromParcel(Parcel source) {
return new Repo(source);
}
#Override
public Repo[] newArray(int size) {
return new Repo[size];
}
};
}
I can create a almost identical model class to represent SQLite data. In here I'm using ORMlite. But this is very similar situation for other ORMs.
#DatabaseTable(tableName = Repo.TABLE_NAME)
public class Repo {
public static final String TABLE_NAME = "repo";
#DatabaseField(columnName = "repo_id")
private long repoId;
#DatabaseField(columnName = "name")
private String name;
public long getRepoId() {
return repoId;
}
public String getName() {
return name;
}
public void setRepoId(long repoId) {
this.repoId = repoId;
}
public void setName(String name) {
this.name = name;
}
}
But by the time I'm trying to save these data in to SQLite database I already have data objects set in GSON model classes. It's kind a redundant thing copy object from GSON model and setting that values in to SQLite model. So I came up with below solution by trying to use single model class to represent both.
#DatabaseTable(tableName = Repo.TABLE_NAME)
public class Repo implements Parcelable {
public static final String TABLE_NAME = "repo";
#DatabaseField(columnName = "repo_id")
#SerializedName("id")
#Expose
private Integer id;
#DatabaseField(columnName = "name")
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String url;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.name);
dest.writeString(this.url);
}
public Repo() {
}
protected Repo(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.name = in.readString();
this.url = in.readString();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public static final Creator<Repo> CREATOR = new Creator<Repo>() {
#Override
public Repo createFromParcel(Parcel source) {
return new Repo(source);
}
#Override
public Repo[] newArray(int size) {
return new Repo[size];
}
};
}
I have try this with different type of model class where it only had String type fields. Since GSON uses types like Integer,Boolean That stopping me from using same model for SQLite because database does not identify Integer as a type, in order to work it need to be int.
So what is the professional way to handle this ? Don't I have any other option other than going back to the method of creating two separate model class to represent SQLite and GSON.
Yout approach is absolutely correct, but i think you are putting too much effort reinventing the wheel
You can easily achieve the described task using Room

Sugar ORM doesnt store data

I am using Sugar ORM 1.3.1 and i am trying to save the following objects
public class Article extends SugarRecord<Article> implements Serializable {
#JsonProperty("Categories")
private List<Category> categories = new ArrayList<Category>();
#JsonProperty("Contents")
private List<Content> contents = new ArrayList<Content>();
#JsonProperty("Country")
private CountryRelated country;
#JsonProperty("Description")
private String description;
#JsonProperty("ExpiryDate")
private String expiryDate;
#JsonProperty("ExtraFields")
private List<ExtraField> extraFields = new ArrayList<ExtraField>();
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("ImageURL")
private String imageURL;
#JsonProperty("Name")
private String name;
#JsonProperty("PortalID")
private int portalID;
#JsonProperty("PublishDate")
private String publishDate;
#JsonProperty("Region")
private Region region;
#JsonProperty("Related")
private List<Related> related = new ArrayList<Related>();
#JsonProperty("Newsbite")
private boolean newsbite;
#JsonProperty("ShareURL")
private String shareURL;
#JsonProperty("Tags")
private List<Tag> tags = new ArrayList<Tag>();
#JsonProperty("Type")
private int type;
public Article() {
}
public Article(List<Category> categories, List<Content> contents, List<ExtraField> extraFields, CountryRelated country, String description, String expiryDate, int identifier, String imageURL, String name, boolean newsbite, int portalID, String publishDate, Region region, List<Related> related, String shareURL, List<Tag> tags, int type) {
this.categories = categories;
this.contents = contents;
this.extraFields = extraFields;
this.country = country;
this.description = description;
this.expiryDate = expiryDate;
this.identifier = identifier;
this.imageURL = imageURL;
this.name = name;
this.newsbite = newsbite;
this.portalID = portalID;
this.publishDate = publishDate;
this.region = region;
this.related = related;
this.shareURL = shareURL;
this.tags = tags;
this.type = type;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Content> getContents() {
return contents;
}
public void setContents(List<Content> contents) {
this.contents = contents;
}
public List<ExtraField> getExtraFields() {
return extraFields;
}
public void setExtraFields(List<ExtraField> extraFields) {
this.extraFields = extraFields;
}
public CountryRelated getCountry() {
return country;
}
public void setCountry(CountryRelated country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNewsbite() {
return newsbite;
}
public void setNewsbite(boolean newsbite) {
this.newsbite = newsbite;
}
public int getPortalID() {
return portalID;
}
public void setPortalID(int portalID) {
this.portalID = portalID;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Related> getRelated() {
return related;
}
public void setRelated(List<Related> related) {
this.related = related;
}
public String getShareURL() {
return shareURL;
}
public void setShareURL(String shareURL) {
this.shareURL = shareURL;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Category.class
public class Category extends SugarRecord<Category> implements Serializable {
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("Name")
private String name;
public constructor + getters and setters }
Content.class and CountryRelated.class have same structure
after i do article.save() my lists doesnt save . Am i doing something wrong or it doesnt save lists at all ???
I few things to look at.
First. I do not believe that the database will handle a column with the type of List or a type of other Object. When I tried running your code, I received:
Class cannot be read from Sqlite3 database. Please check the type of field categories(java.util.List)
These should be types the database can store. Try serializing your List(s) to Strings to insert them in the db. You can try doing this in your getter and setter. The setter takes the list of objects and converts it to a serialized String, the getter takes the serialized String and converts it back to a list of objects.
In the instance of SugarOrm, you can reference another table and it will create a relationship outlined here:
http://satyan.github.io/sugar/creation.html#why
Notice the "Author" type is just referencing a record from another table in the database.
Second I usually try and set my default values inside my default constructor. so something like:
... property declarations...
public Article() {
this.name = "Default Value";
}
Hope this helps you finish troublshooting!

Categories

Resources