How do i declare an id with primary key auto increment?
package com.ncf.globofly.models
data class Destination(
var id: Int = 0, #PRIMAY KEY Auto Increment
var Sequence: String? = null,
var Description: String? = null,
var Status: String? = null
)
It can be done using annotation first add the dependencies for database and annotation processor after that
data class Destination(
#PrimaryKey(autoGenerate = true)
var id: Int = 0,
var Sequence: String? = null,
var Description: String? = null,
var Status: String? = null
)
Related
#Query("UPDATE RealEstateDatabase SET type = :entryType WHERE id = :id AND type NOT LIKE :entryType")
suspend fun updateRealEstate(entryType: String, id: String)
This code works perfectly to update a row in the table based on a condition I want to do the same thing with several rows each linked to a condition
here is the entity/table in question
#Entity
#Parcelize
data class RealEstateDatabase(
#PrimaryKey
var id: String,
var type: String? = null,
var price: Int? = null,
var area: Int? = null,
var numberRoom: String? = null,
var description: String? = null,
var numberAndStreet: String? = null,
var numberApartment: String? = null,
var city: String? = null,
var region: String? = null,
var postalCode: String? = null,
var country: String? = null,
var status: String? = null,
var dateOfEntry: String? = null,
var dateOfSale: String? = null,
var realEstateAgent: String? = null,
var lat: Double ?=null,
var lng: Double ?=null,
var hospitalsNear : Boolean = false,
var schoolsNear : Boolean = false,
var shopsNear : Boolean = false,
var parksNear : Boolean = false,
#ColumnInfo(name = "listPhotoWithText")
var listPhotoWithText : List<PhotoWithTextFirebase> ?=null,
var count_photo : Int? = listPhotoWithText?.size,
)
I also put the method of my repository , this method has parameters of the same type as my table to modify
override suspend fun updateRealEstate(
id: String,
entryType: String,
entryPrice: String,
entryArea: String,
entryNumberRoom: String,
entryDescription: String,
entryNumberAndStreet: String,
entryNumberApartement: String,
entryCity: String,
entryRegion: String,
entryPostalCode: String,
entryCountry: String,
entryStatus: String,
textDateOfEntry: String,
textDateOfSale: String,
realEstateAgent: String?,
lat: Double?,
lng: Double?,
checkedStateHopital: MutableState<Boolean>,
checkedStateSchool: MutableState<Boolean>,
checkedStateShops: MutableState<Boolean>,
checkedStateParks: MutableState<Boolean>,
listPhotoWithText: List<PhotoWithTextFirebase>?,
itemRealEstate: RealEstateDatabase
): Response<Boolean> {
return try {
Response.Loading
val rEcollection = firebaseFirestore.collection("real_estates")
if(entryType != itemRealEstate.type ){
rEcollection.document(id).update("type",entryType)
}
realEstateDao.updateRealEstate(entryType,id)
Response.Success(true)
}catch (e: Exception) {
Response.Failure(e)
}
}
I repeat that I want to update the rows of the table on the condition that the variable given by the method of my repo is different from the row in question
#Query("UPDATE RealEstateDatabase SET " +
"type = (CASE WHEN type NOT LIKE :entryType THEN (:entryType) ELSE type END) ," +
"price = (CASE WHEN price NOT LIKE :entryPrice THEN (:entryPrice) ELSE price END) WHERE id =:id")
suspend fun updateRealEstate(
entryType: String,
id: String,
entryPrice: Int
)
this solution works but forces me to update the value anyway
What you can do is add a condition in the WHERE clause which will prevent the execution of the UPDATE statement if both columns do not need to be updated:
#Query("UPDATE RealEstateDatabase SET " +
"type = CASE WHEN type NOT LIKE :entryType THEN (:entryType) ELSE type END," +
"price = CASE WHEN price NOT LIKE :entryPrice THEN (:entryPrice) ELSE price END " +
"WHERE id = :id AND (type NOT LIKE :entryType OR price NOT LIKE :entryPrice)")
This question already has answers here:
Drop "is" prefix for Firebase Firestore fields for Boolean Values
(2 answers)
Prevent firebase from taking the method name as variable in Firebase
(2 answers)
Closed 5 months ago.
I have multiple data classes and all upload fine to Firebase Realtime database except for this one key "isCompleted" gets changed to "completed" in the database.
My data class:
data class MaintenanceLog(
val isCompleted: Boolean? = null,
val brand: String? = null,
val clientCode: String? = null,
val dateOfSubmission: Double? = null,
val details: String? = null,
val equipmentID: String? = null,
val id: String? = null,
val model: String? = null,
val name: String? = null,
val photosArray: List<String>? = null,
val refNum: String? = null,
val restaurantID: String? = null,
var hidden: Boolean? = null,
val userSelectedDate: Double? = null,
val wasFutureMaintCreated: Boolean? = null,
val workLogRef: String? = null,
val contractorCode: String? = null,
val isCalendarEvent: Boolean? = null,
val calendarEvent_venueName: String? = null,
val createdBy: String? = null
)
Implementation:
val demoLog = MaintenanceLog(
isCompleted = true,
id = "DemoLog22222",
equipmentID = "demo_equipID_123456",
refNum = "DemoRefNum_123456",
dateOfSubmission = APSDate.getCurrentDatabaseFormattedTime(),
details = "Maintenance Log created from Work Log - Demo Description",
photosArray = null,
workLogRef = "DemoRefNum_123456",
createdBy = "Demo User",
clientCode = "Demo Client",
restaurantID = "Demo Restaurant",
brand = "Demo Brand",
model = "Demo Model",
name = "Demo User",
userSelectedDate = APSDate.dateFromComponents(timeIn_Year, timeIn_Month, timeIn_Day, timeIn_Hour, timeIn_Minute),
wasFutureMaintCreated = false)
dbRef.child(FirebaseLocations.MAINTENANCE_RECORDS.code).child("111_demo_path").setValue(demoLog)
The demo log when setting the value:
And the firebase value:
Why is "isCompleted" getting changed to "completed" when uploaded to the database?
Is it possible to add a new table without specifying every field "manually" like this:
schema.create("LoyaltyActivity")
.addField("id", String::class.java, FieldAttribute.PRIMARY_KEY)
.addField("source", String::class.java)
.addField("date", String::class.java)
.addField("points", String::class.java)
.addField("reference", String::class.java
Realm class looks like this:
open class LoyaltyActivity(
#PrimaryKey var id: String? = null,
var source: String? = null,
var date: String? = null,
var points: String? = null,
var reference: String? = null
) : RealmObject()
On iOS, it is possible with method provided in SDK: migration.create(typeName: String, value: <Any>)
This is my model class
#Parcel
data class ClientModel(
var name: String? = "",
var phone: String? = "",
var princpalAddresse: String? = "",
var homeAddresse: String? = "",
var travailleAddresse: String? = "",
var email: String? = "",
var userToken: String? = "",
var principalAddresseCoords: Pair<Double, Double>? = null,
var homeAddresseCoords: Pair<Double, Double>?= null,
var workAddresseCoords: Pair<Double, Double>? = null,
)
My proGuard file keep the class :
-keep class com.olivier.oplivre.models.ClientModel
But! when I try to get the snapshot with a singleValueEventListener I got exception because of the Pair<Double,Double> variables
val utilisationInfo = snapshot.getValue(ClientModel::class.java) //todo CRASH
Exception :
com.google.firebase.database.DatabaseException: Class kotlin.Pair does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
Database Structure :
I think firebase Realtime database treat your principalAddresseCoords as a list of long so in your ClientModel change the value of principalAddresseCoords to emptyList() and the type List
As #Sami Shorman said , firebase took my Pair instance and transform it but not as list, as Hashmap<,> ! so I changed my class model like that :
var principalAddresseCoords: HashMap<String,Double>? = null,
var homeAddresseCoords: HashMap<String,Double >? = null,
var workAddresseCoords: HashMap<String,Double >? = null,
To put the data as Hashmap I just had to do :
clientModel.workAddresseCoords = HashMap<String,Double>().apply {
put("lat",lat)
put("long",long)
}
I have a scenario. I have created a data class in Kotlin like this:
data class AgentDetails(
val mobileNo: String,
val Name: String,
val Email: String,
val Password: String,
val Occupation: String,
val pincode: String,
val usertype: String,
val profilepic: String,
val AccountStatus: String
)
I want to send different type of objects of this data class to a web service:
1st object example:
val agentDetails = AgentDetails(mobileNo = mobileNumberText.text.toString(),
Name = userNameText.text.toString(),
Email = emailIdText.text.toString(),
Password = HashUtils.sha1(passwordText.text.toString()),
Occupation = item,
pincode = pinCodeText.text.toString(),
usertype = "Agent",
profilepic = "null", AccountStatus = "pending")
In 2nd object I only want to send mobile number. I dont wanna include any other field. Something like this:
val agentDetails = AgentDetails(mobileNo = mobileNumberText.text.toString())
And in 3rd object I only wanna send email id. Instead of creating multiple data classes. Can I use the same data class for multiple implementations?
Personally, I'd define three objects because they represent three different concepts (or projections of a concept). But if you make your properties nullable and provide a default value of null, you can get away with creating them as you want...
data class AgentDetails(
val mobileNo: String? = null,
val name: String? = null,
val email: String? = null,
val password: String? = null,
val occupation: String? = null,
val pincode: String? = null,
val usertype: String? = null,
val profilepic: String? = null,
val accountStatus: String? = null
)
Note: I've changed some of your property names to camelCase, as is the proper convention. And these all work fine:
AgentDetails(mobileNo = mobileNumberText.text.toString())
AgentDetails(email = "foo#example.com")
AgentDetails(name = "Foo", password = "Bar")
All of the other fields not provided will be null, and the types will be nullable, so you'll have to guard against that. Otherwise, I'd define three data classes for this.
Another solution would be to consider a sealed class structure:
sealed class AgentDetails
data class AgentByName(val name: String) : AgentDetails()
data class AgentByEmail(val email: String): AgentDetails()
// etc..
And then use it in a when expression:
fun doSomethingWithAgents(agentDetails: AgentDetails) {
when (agentDetails) {
is AgentByName -> // Do something
is AgentByEmail -> // Do Something
}
}
The easiest way is to make the fields nullable and provide default values:
data class AgentDetails(
val mobileNo: String? = null,
val Name: String? = null,
val Email: String? = null,
val Password: String? = null,
val Occupation: String? = null,
val pincode: String? = null,
val usertype: String? = null,
val profilepic: String? = null,
val AccountStatus: String? = null
)