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.
Related
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);
}
I have ArrayList and i want to get him some specific object values and insert them to another ArrayList, but I can't get the specific values
val listA = ArrayList<User>()
this list contains some users with their id,name, and email so i need to get all user's whose names are john and id,email will be any value
You could use the filter function i.e
listA.filter { it.name == "john" }
or use groupBy with forEach i.e
listA.groupBy{ it.name }.forEach{name, list ->
//name: the key for each list according to their names
//list: a grouped list according to the names
}
I am learning to fetching data from sqlite using anko. I can print the data successfully (if the record exist) but my application always crash when the data doesn't exist.
the error says:
parseSingle accepts only cursors with a single entry
I know exactly the meaning of error, I just dont know how to solve it.
here is the code for query:
fun getUserByUid(uid: Int): UserModel
{
val data = context.database.use {
val db = context.database.readableDatabase
val columns = UserModel.COLUMN_ID + "," + UserModel.COLUMN_NAME + "," + UserModel.COLUMN_API_KEY
val query = db.select(UserModel.TABLE_NAME, columns)
.whereArgs("(uid = {userId})",
"userId" to uid)
query.exec {
val rowParser = classParser<UserModel>()
parseSingle(rowParser) // this line that trigger error exception
}
}
return data
}
I tried to find count function in query or rowParser variable to check if the record exist or not but could not find it.
From the wiki page.
https://github.com/Kotlin/anko/wiki/Anko-SQLite#parsing-query-results
Parsing query results
So we have some Cursor, and how can we parse it into regular classes? Anko provides functions parseSingle, parseOpt and parseList to do it much more easily.
Method Description
parseSingle(rowParser): T Parse exactly one row
parseOpt(rowParser): T? Parse zero or one row
parseList(rowParser): List Parse zero or more rows
Note that parseSingle() and parseOpt() will throw an exception if the received Cursor contains more than one row.
I have the following denormalized data structure:
A Contact can associate with multiple Records. A Record can have multiple associated Contacts (many<->many relationship). To keep track of their relationship, an int value to indicates the contact's role in a particular record, and store the role value in two separate references
Contact
- Contact1:data
- Contact2:data
- Contact3:data
Record
- Record1:data
- Record2:data
Record_Role_Ref
- Record1
-- Contact1: roleA
-- Contact2: roleA
-- Contact3: roleD
- Record2
-- Contact1: roleB
Contact_Role_Ref
- Contact1
-- Record1: roleA
-- Record2: roleB
I'm using FirebaseIndexRecyclerAdapter is to show a list of associated Contacts to a particular Record id. So for the key reference I would use Record_Role_Ref/record_id, and for the data reference I would use Contact, like so:
// Setup the reference to the all the associated contact list in record_role_ref, using the record id as key
Query mRecordRoleRef = firebaseDatabase.getReference().child(DB_RECORD_ROLE_REF).child(mRecordId);
// Reference the Contact data ref
Query mContactRef = firebaseDatabase.getReference().child(DB_CONTACT);
FirebaseIndexRecyclerAdapter mContactAdapter = new FirebaseIndexRecyclerAdapter<Contact, ContactViewHolder>(Contact.class,
R.layout.item_contact,
ContactViewHolder.class,
mRecordRoleRef, // The Firebase database location containing the keys associated contacts to this record
mContactRef)// The Firebase database location to watch for data changes. Each key key found at keyRef's location represents a list item in the RecyclerView.
Limitation(s): I don't want to store the role value in each contact and record object because each time a role is changed, both the contact and record's entire object would have fetched and updated. Users want to delete, modify, move both contact and records, and change roles.
Problem(s):
The contact's role value is stored as value of the key in the mRecordRoleRef. Is it possible/how to get the value from the key reference in on-go with FirebaseIndexRecyclerAdapter? What is the good/best practice in this kind of situation?
Thanks In Advance :)
As of now, I just form another data read request inside the populateViewHolder callback method. Since the data read request is itself also async, I'm not yet sure if this would work for a large list and when the view recycles. The viewHolder returned by the populateViewHolder is set to final.
Query mRecordContactRoleRef = firebaseDatabase.getReference().child(DB_RECORD_CONTACT_ROLE_REF).child(mRecordId).child(mContact.getContactId());
mRecordContactRoleRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Getting the role int base on record type
Long roleNum = (Long) dataSnapshot.getValue();
viewHolder.setContactRoleTv("hi, the role is " + roleNum);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I'm writing a Xamarin Android app which is using Parse.com as the backend. I'm running a query against a Parse Class called Beacons, of which one of the columns is a Pointer to another class called BeaconCat.
I'm therefore using two queries as shown below, but when it returns the data, it lists ALL of the categories within the BeaconCat class, not just the one which matches the initial query.
I'm expecting just one category, not all 13 of them. Any idea why?
// First query on class 1.
var innerQuery = ParseObject.GetQuery("Beacons");
innerQuery.WhereEqualTo("minor", minor);
// Query on class 2 which passes in first query.
var newQuery = ParseObject.GetQuery("BeaconCat");
newQuery.WhereMatchesQuery("Category", innerQuery);
IEnumerable<ParseObject> Myresults = await newQuery.FindAsync();
foreach (var result in Myresults)
{
var category = result.Get<string>("Category");
Console.WriteLine ("Category " + category);
}