Realm query with child arrays - android

Here's the Object I'm working with:
public class NavigationMenuModule extends RealmObject implements Parcelable {
#PrimaryKey
public String sectionKey;
public RealmList<ItemModule> modules;
public RealmList<Article> spotlightSponsored;
public RealmList<Article> items;
}
The child Article Object:
public class Article extends RealmObject {
#PrimaryKey
public String contentId;
public String leadImageURL;
public String summary;
public String headline;
}
How would I structure this realm call:
get NavigationMenuModule item by sectionKey
get spotlightSponsored within that NavigationMenuModule that matches the article's contentId
The method below works but I feel like there's probably a "neater" way:
public static Article getArticle(String sectionKey, String articleId) {
Realm realm = Realm.getDefaultInstance();
NavigationMenuModule navigationMenuModule = realm.where(NavigationMenuModule.class).equalTo("sectionKey", sectionKey).findFirst();
if (navigationMenuModule != null && !navigationMenuModule.spotlightSponsored.isEmpty()) {
for (Article article : navigationMenuModule.spotlightSponsored) {
if (article.getContentId().equals(articleId)) {
Article ret = realm.copyFromRealm(article);
realm.close();
return ret;
}
}
}
realm.close();
return null;
}

Theoretically this should work with Realm 3.5.0
public class NavigationMenuModule extends RealmObject implements Parcelable {
#PrimaryKey
public String sectionKey;
public RealmList<ItemModule> modules;
public RealmList<Article> spotlightSponsored;
public RealmList<Article> items;
}
public class Article extends RealmObject {
#PrimaryKey
public String contentId;
public String leadImageURL;
public String summary;
public String headline;
#LinkingObjects("spotlightSponsored")
public final RealmResults<NavigationMenuModule> spotlightSponsoredOf = null;
#LinkingObjects("items")
public final RealmResults<NavigationMenuModule> itemsOf = null;
}
public static Article getArticle(Realm realm, String sectionKey, String articleId) {
return realm.where(Article.class)
.equalTo("contentId", articleId)
.equalTo("spotlightSponsoredOf.sectionKey", sectionKey)
.findFirst();
}

Related

How to create an array list inside a realm object for todo app?

I want to develop todo app with the realm database. I have successfully created a list and displayed in recycler view. but when I try to add task inside the recycler view item. I'm a little bit confused. I don't know how to achieve this.
for example:
this is my POJO class
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ShoppingModel extends RealmObject {
#PrimaryKey
private int id;
private String title;
private String items;
private String color;
private String date;
private String time;
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 getItems() {
return items;
}
public void setItems(String items) {
this.items = items;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
This is my realm helper class
import android.util.Log;
import java.util.List;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
public class RealmHelper {
Realm realm;
public RealmHelper(Realm realm){
this.realm = realm;
}
//save data to realm
public void save(final ShoppingModel shoppingModel){
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
if (realm!=null){
Log.e("Log", "Database was created " );
Number currentID = realm.where(ShoppingModel.class).max("id");
int nextId;
if (currentID == null){
nextId=1;
} else {
nextId = currentID.intValue() + 1;
}
shoppingModel.setId(nextId);
ShoppingModel s = realm.copyToRealm(shoppingModel);
} else {
Log.e("Log", "Database not exits " );
}
}
});
}
public List<ShoppingModel> getAllShoppingList(){
RealmResults<ShoppingModel> shopResult = realm.where(ShoppingModel.class).findAll();
return shopResult;
}
//update data to realm
public void update(final int id, final String title, final String items, final String color, final String date, final String time){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ShoppingModel shoppingModel = realm.where(ShoppingModel.class).equalTo("id",id)
.findFirst();
shoppingModel.setTitle(title);
shoppingModel.setItems(items);
shoppingModel.setTime(time);
shoppingModel.setDate(date);
shoppingModel.setColor(color);
}
}, new Realm.Transaction.OnSuccess(){
#Override
public void onSuccess() {
}
}, new Realm.Transaction.OnError(){
#Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
}
// delete from realm
public void delete(final int id, final String title, final String items, final String color, final String date, final String time){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ShoppingModel shoppingModel = realm.where(ShoppingModel.class).equalTo("id",id)
.findFirst();
shoppingModel.setTitle(title);
shoppingModel.setItems(items);
shoppingModel.setTime(time);
shoppingModel.setDate(date);
shoppingModel.setColor(color);
shoppingModel.deleteFromRealm();
realm.commitTransaction();
}
}, new Realm.Transaction.OnSuccess(){
#Override
public void onSuccess() {
}
}, new Realm.Transaction.OnError(){
#Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
}
}
Here's my output
Now I want to click that item inside that item i want to add task with checkbox
for example like this
Both List and ShoppingModel cannot be stored in Realm directly. You will need to create a model object for ShoppingModel and then use a RealmList object containing your model objects.
public class ShoppingModel extends RealmObject {
public ShoppingModel() { }
#PrimaryKey
private int id;
private String title;
private String items;
private String color;
private String date;
private String time;
RealmList<ShoppingModelDetails> shoppingListDetails = new RealmList<ShoppingModelDetails>();
// getter setters are here.
}
ShoppingModelDetails class is here -
public class ShoppingModelDetails extends RealmObject {
public ShoppingModelDetails() { }
#PrimaryKey
private int id;
private String title;
private String items;
private String color;
private String date;
private String time;
// getter setters are here.
}
//Add shopping model details objects to shoppingListDetails and store it in your ShoppingList object
You will need to manually convert objects of the ShoppingModelDetails class to the ShoppingModel class when you are inserting/retrieving from the database.

Serialise / deserialise model in firestore

I have the following class that I want to store in firestore.
public class User extends Model {
#PropertyName("user_auth_id")
public String authUid;
#PropertyName("first_name")
public String firstName;
#PropertyName("last_name")
public String lastName;
#PropertyName("picture_url")
public String pictureUrl;
#PropertyName("email")
public String email;
#PropertyName("companies")
public ArrayList<UserCompany> companies;
public User() {}
}
public class UserCompany extends Model {
public String name;
public String role;
public String position;
public UserCompany() {
super();
}
public UserCompany(Company company, String role, String position) {
this();
name = company.name;
this.role = role;
this.position = position;
}
public Map<String, Object> toObject() {
Map<String, Object> object = new HashMap<>();
object.put("id", id);
object.put("name", name);
object.put("role", role);
object.put("position", position);
return object;
}
}
#IgnoreExtraProperties
public class Model {
#Exclude
public String id;
public <T extends Model> T withId(#NonNull final String id) {
this.id = id;
return (T) this;
}
}
And I want to use a transaction to update an user entry with it's newly created company list. (appUser instanceOf User)
transaction.update(userRef, "companies", appUser.companies);
If I do so...I get
Invalid data. Unsupported type: ro.exemple.model.UserCompany
How can I serialise an User object so that I can deserialise it as such
User appUser = queryDocumentSnapshots.getDocuments().get(0).toObject(User.class);
Where queryDocumentSnapshots is the result of a query in my firestore db.
I know I can change from ArrayList to HashMap, but I wish to keep the List, and try to serialise and deserialise it, in order to obtain in firestore an array of objects.
if this serialization you must tag your class as Serializable..
public UserCompany extends Model implements Serializable
public class User extends Model implements Serializable
plus tag the class Model as well

How to insert data and retrieve data in nested relationships in Room Database Android

I have entities
#Entity
public class A {
#PrimaryKey(autoGenerate = true)
public long id;
public String bFId;
public List<B> bList;
}
#Entity()
public class B {
#PrimaryKey #NonNull
public String id;
public String oneCId;
public List<C> cList;
}
#Entity
public class C {
#PrimaryKey #NonNull
public String id;
public String value;
}
And I wrote this like a Relation
public class AWithB extends A{
#Relation(parentColumn = "id", entityColumn = "bId")
public List<BWithC> bWithC;
}
public class BWithC {
#Embedded
public B b;
#Relation(entity=C.class,parentColumn="bFId",entityColun="cid")
public List<C> {}
}
Is my relation wrong? And How to insert data And retrieve data this.I must to be used this relation.I cannot use another relation.Please help me.

Unable to find generated Parcelable class

I am trying to use Parceler in my android project.
This is my Song model.
#Parcel(implementations = {SongRealmProxy.class},
value = Parcel.Serialization.BEAN,
analyze = {Song.class})
public class Song extends RealmObject {
#PrimaryKey
public String id;
public String isrc;
public String songName;
public String artistName;
public String album_id;
public String albumArtUrl;
public String genre_id;
public String genreName;
public String releaseYear;
public String price;
public String lyrics;
public String demo;
public int explicit;
}
When I try to warp these song model using bundle like this.
b.putParcelable(DATA_PARAM, Parcels.wrap(song));
I keep having this error.
org.parceler.ParcelerRuntimeException: Unable to find generated Parcelable class for com.devhousemyanmar.juketrill.models.Song, verify that your class is configured properly and that the Parcelable class com.devhousemyanmar.juketrill.models.Song$$Parcelable is generated by Parceler.
Please help me to solve this problem.
Parcelable class should be like this :
package com.yourpackagename;
public class BrushData implements Parcelable {
public static final Creator<BrushData> CREATOR = new Creator<BrushData>() {
#Override
public BrushData createFromParcel(Parcel in) {
return new BrushData(in);
}
#Override
public BrushData[] newArray(int size) {
return new BrushData[size];
}
};
private static final int VERSION = 1;
#SerializedName("icon")
private String icon;
#SerializedName("effects")
private ArrayList<String> effects;
private BrushData(Parcel parcel) {
if (parcel != null) {
readFromParcel(parcel);
}
}
#Override
public int describeContents() {
return 0;
}
private void readFromParcel(Parcel in) {
if (in.readInt() == VERSION) {
icon = in.readString();
}
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(VERSION);
parcel.writeString(icon);
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public ArrayList<String> getEffects() {
return effects;
}
public void setEffects(ArrayList<String> effects) {
this.effects = effects;
}
}

How to delete many to many DB in realm

This is I tried
public class AppInfo extends RealmObject {
public String packageName;
public RealmList<CategoryInfo> categoryList;
}
public class CategoryInfo extends RealmObject {
public String categoryName;
}
This is my DB Table.
I wanna delete categoryName.
AppInfo result = realm.where(AppInfo.class).equalTo("packageName",info.getPackageName()).findFirst();
result.categoryList.remove(category);
but the code can't delete categoryName.
Instead of
result.categoryList.remove(category);
You should do
result.categoryList.where().equalTo("categoryName", category).findAll().deleteAllFromRealm();
With Realm 3.4.0, you can also do
public class AppInfo extends RealmObject {
public String packageName;
public RealmList<CategoryInfo> categoryList;
}
public class CategoryInfo extends RealmObject {
public String categoryName;
#LinkingObjects("categoryList")
public final RealmResults<AppInfo> appInfos = null;
}
and
realm.where(CategoryInfo.class)
.equalTo("appInfos.packageName", packageName)
.equalTo("categoryName", category)
.findAll()
.deleteFromRealm();

Categories

Resources