Android Realm Insert on conflict ignore - android

Does anyone know a way how to solve a problem?
I need to implement data storage with Realm.
I receive from network JSON object convert him to realm object Card and save it. I expand Card object with extra field favorite and change it manually from an application.
Every time when network operation executes insertOrUpdate wipes value, and insert throws an exception 'RealmPrimaryKeyConstraintException' because I have #PrimaryKey definition.
Is there exist in Realm feature how to use an insert with a particular update on Insert with Ignore?

Card card = realm.where(Card.class).equalTo(CardFields.ID, cardId).findFirst(); // https://github.com/cmelchior/realmfieldnameshelper
if(card == null) {
card = realm.createObject(Card.class, cardId);
}
card.setFavorite(true);
Or
Card card = realm.where(Card.class).equalTo(CardFields.ID, cardId).findFirst(); // https://github.com/cmelchior/realmfieldnameshelper
if(card == null) {
card = new Card();
card.setId(cardId);
}
card.setFavorite(true);
realm.insertOrUpdate(card);
Basically, if you don't want to overwrite the object, then you should query it and manipulate it, otherwise create it.

Related

add/overwrite field of type array in Firestore

I want to add a field of type array inside a collection.
if the field doesn't exist create it. if it exists overwrite it with the new array value.
the field should be called macAddress and it's of type array of String
I have tried the following:
val macInput = setting_mac_text.text.toString()
val macArray = macInput.split(",")
val macList = Arrays.asList(macArray)
val data =
hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
//save it in firebase
db.collection(FirebaseConstants.ORGANIZATION)
.document(orgID + ".${FirebaseConstants.USER_MAC_ADDRESS}")
.set(FieldValue.arrayUnion(macList))
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "successfully inserted")
} else {
Log.d(TAG, " failed ${task.exception}")
}
}
also tried to insert the list itself and hash map like this
val data = hashMapOf(Pair(FirebaseConstants.USER_MAC_ADDRESS, macArray))
db.collection(FirebaseConstants.ORGANIZATION)
.document(orgID)
.set(data))
but it keeps giving me java.lang.IllegalArgumentException: Invalid data. Nested arrays are not supported
what am I doing wrong here?
You're doing three things wrong here:
FieldValue.arrayUnion() is only meant to be used as the value of a field to add elements to that field. The way you are using it now in the first sample, it's being taken as the entire contents of the document.
set() with one parameter is only intended to create or overwrite an entire document. It can't be used to update an existing document. You would have to pass in SetOptions to tell it to merge if you want an update. Or, you would simply use update() to modify an existing document.
Your code that deals with macArray and macList isn't working the way you expect. You are creating a list with one element, which is itself an array. The error message is telling you that you can't have nested arrays like this.
I suggest taking a step back and simplifying your code, removing all the moving parts that don't have to do with Firestore. Just hard code values in your Firestore update until the update works the way you want, then add in the code that works with actual values. Get one simple thing to work, then add to it. If you get an error, you will know that the code you just added was incorrect.
To overwrite an array, you would simply call the set method and have the merge option set to true:
try {
const query = await DatabaseService.queryBuilder({
collection: CollectionName,
});
return await query
.doc(insuranceId)
.set(
{ DOCUMENT_PROPERTY_HERE: ARRAY_HERE },
{ merge: true }
);
} catch (exception) {
return Promise.reject(exception);
}

How to make query for table with column contains Pointer value?

I have object called Reservation which contains column with name "object_entity" and inside is ParseObject from table Entity. I want to query only those Reservation which contains certain Entity.
val q = ParseQuery.getQuery<ParseObject>("Reservation")
if (!isOnline(c)){
q.ignoreACLs()
q.fromLocalDatastore()
}
q.whereEqualTo("object_entity", ticket.getParseObject("object_entity")?.objectId)
q.findInBackground { itemList, err ->
itemList //empty size 0
err //null
}
This is working as intended if you are online. But if you are offline it will return empty list. I've checked local datastore and all expected objects are there. But if I remove q.whereEqualTo it will return list of all Reservations without any problem (but I need specific ones).
ticket.getParseObject("object_entity")?.objectId is not null. It always contains objectId - checked in debugger
If I remove q.whereEqualTo I check all returned Reservation objects if they contains Entity.
This is inside findInBackground:
itemList.forEach { reservation ->
val entityObj = reservation.getParseObject("object_entity")
if (entityObj == null) createLog("FoundObj", "null") else
createLog("FoundObj", entityObj.objectId.toString())
}
Ive tried to add inside q.whereEqualTo specific Entity objectId. And it returned empty list. But if I removed q.whereEqualTo that specific object with specific objectId I wanted to get was returned in list.

Realm databease in android return null when i use "findFirst()"

i have one screen that save some data after the user choose one area i save it to the realm after that direct i go to another screen and try to find this saved model
carriageRealm.where(CountryRealm.class).findFirst()
but it retruns empty and crashes in some devices?
Realm carriageRealm = Realm.getDefaultInstance();
carriageRealm.beginTransaction();
carriageRealm.delete(CurrentAreaRealm.class);
CurrentAreaRealm currentArea = new CurrentAreaRealm();
currentArea.setAddress_name(area.getAddress_name());
currentArea.setArea_id(area.getArea_id());
currentArea.setLatitude(area.getLatitude());
currentArea.setLongitude(area.getLongitude());
carriageRealm.copyToRealm(currentArea);
carriageRealm.commitTransaction();
carriageRealm.close();

Create or update record in ActiveAndroid ORM

I'm using active android as orm in my android project.
after I get a json response from server, I wanna create a field if that item does not exist, or update it if that item already exists.
Record existence is determined via a field named slug.
How can I achieve this via ActiveAndroid? since I don't see how to achieve in the wiki.
Assume your class name is YOUR_CLASS which has a slug field. Then do the following with ActiveAndroid:
YOUR_CLASS item = new Select()
.from(YOUR_CLASS.class)
.where(slug = ?,_slug_value_)
.executeSingle();
if(item == null) {
item = new YOUR_CLASS();
item.slug = _slug_value_;
}
//change what you want then save the item.
item._field_to_change_ = _new_value_;
item.save();

pass an array objects in Corona with class

I'm creating an app with Corona structured in Class and I have a problem when I want pass an array objects for create an object.
I have this:
main.lua
local SurpriseBoxClass = require("SurpriseBox")
local BoxClass = require("Box")
local box1 = BoxClass.new('palo', 'images/chestClose.gif', 'OPEN')
local box2 = BoxClass.new('moneda', 'images/chestClose.gif', 'OPEN')
boxes = { box1, box2 }
local game = SurpriseBoxClass.new(boxes)
SurpriseBox.lua
local SurpriseBox = {}
local SurpriseBox_mt = { __index = SurpriseBox }
function SurpriseBox.new(boxesAux)
local object = {
boxes = boxesAux
}
return setmetatable( object, SurpriseBox_mt )
end
The problem is when I want to print the content of array in a method of SurpriseBox, and the program said me that the array is nil if for example I do this:
print(boxes[0])
What can I do?
Thanks!
Lua tables are 1-based.
Try print(boxes[1], boxes[2]).
It will print the table id. If you need to print the contents of the table, you must iterate over its fields, or use a custom printer that does it for you (see "Print a table recursively").
Look at the function SupriseBox.new(boxesAux) (where I gather you desire to do the printing):
In object, you are associating the key "boxes" with the table boxesAux. This to access the contents of boxesAux via object you must go through the following process:
object["boxes"] or object.boxes will get you to boxesAux, to go into that you need the superscripting i.e [1]
print(object["boxes"][1]) --etc..
print(object.boxes[1]) --etc..
Note that, this will now give you box1. If you want to print a meaningful display of it's content (that is if the class isn't overloaded) you should use a pretty printing library.

Categories

Resources