pass an array objects in Corona with class - android

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.

Related

How to save a list of objects with Proto DataStore

If I have the following class, how can I save a list of it with Proto DataStore?
data class Tag(
val id: int,
val name: String
)
All guides that I saw were teaching how to save only a single object. Is it possible to have a list of it?
You should consider storing list of content in Room, Even proto-datastore isnt a proper solution to store complex stuff,
If you still want then, I will suggest you to restrict the data stored to 10-15 items
to the code --->
Create your proto file, repeated is used to create list type for Java
message Student {
string id = 1;
string name = 2;
}
message ClassRoom {
string teacher = 1;
repeated Student students = 2; // repeated => list
}
Inside your proto-store,
dataStore.updateData { store ->
store.toBuilder()
.clearStudents() // clear previous list
.setAllStudents(students)// add the new list
.build()
}
if you want example checkout my sample app, read the data/domain layer
https://github.com/ch8n/Jetpack-compose-thatsMine

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

Unable to fetch the list column of AWS DynamoDB in Android Kotlin

I am developing an Android application using Kotlin and AWS DynamoDB. I am new to both technologies. What I am doing now is I am trying to scan data from a table of DynamoDB. I know how to scan it. But the problem is that one of the column has List data type.
I have a table called item with the following columns.
Note in particular the Images field.
In Kotlin Android, I scan the table like this.
val dynamoDBClient = AmazonDynamoDBClient(AWSMobileClient.getInstance().credentialsProvider)
val fetchedItems: ArrayList<Any> = ArrayList();
val scanRequest = ScanRequest().withTableName(MainApplication.DB_TABLE_ITEMS);
scanRequest.exclusiveStartKey = lastEvaluatedKey
val scanResult = dynamoDBClient.scan(scanRequest)
scanResult.items.forEach { item ->
Log.i("ITEM_NAME", item.get("Name")?.s)
val viewItem = ItemDO()
viewItem.id = item.get("Id")?.s
viewItem.description = item.get("Description")?.s
viewItem.name = item.get("Name")?.s
viewItem.userId = item.get("UserId")?.s
viewItem.images = item.get("Images")?.ns
fetchedItems.add(viewItem)
Log.i("IMAGES_COUNT", item.get("Images")?.ns?.size.toString())
}
But this
item.get("Images")?.ns
always return null even if the data exists in the column as in the screenshot below.
Why my code is not fetching the list data type but others?
The code looks good and should be returning data for all the attributes irrespective of their type. I have equivalent piece of code in java that works as expected. Can you try inspecting the value returned by item.get("Images") before making the null-safe call. Type of the value returned by item.get("Images") is AttributeValue and so there is a possibility that the value gets lost in the course of implicit type conversion.

How to access Firebase Database node using contains() method?

I am working on an app using Firebase Database. In my Firebase Database I have a node like xxxxxx_yyyyyy, where xxxxxx represents first user ID and yyyyyy represents second user ID. Now I want to retrieve only nodes which contains xxxxxx_ from my database. I don't know how to do this. Because all I know is Firebase gives only equalsTo() method.
There is no query like contain(). I recommend to change node structure (locating yyyyy under xxxxx).
There Is no Query Like Contains in Fire base.!
if you dnt want to change structure of your node you can Store Data in list and then simply use list.contains() you will get your desired Result.!
HtBVbQP0qMSrCStroYsIiMSuhMC3 //node userID
Name:XXXXXXX
You can get this Data by using orderbychild(XXXXXX);
There is no contain() method, however, you can solve this problem in two ways:
Using the split() method from String class.
Using Regex Pattern
Here is the code:
String firebaseField = "xxxxxx_yyyyyy";
String[] data = firebaseField.split("_");
System.out.print("Using split method: ");
for(String part : data) {
if (part.equals("xxxxxx")) {
System.out.print(part + " ");
//Add your logic
}
}
Or
System.out.print("\nUsing Regex Pattern: ");
Pattern datePattern = Pattern.compile("_");
data = datePattern.split(firebaseField);
for(String part : data) {
if (part.equals("xxxxxx")) {
System.out.print(part + " ");
//Add your logic
}
}
Hope it helps.

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();

Categories

Resources