Skip to main content

Sample

Because the Sync SDK maintains the latest data with background synchronization services and binding communication, it is processed with the same file on the device. If the developer knows the database and document names, data can be shared quickly and easily across multiple applications and Android components.

When the Profile database contains data like the following, you can modify and synchronize data using SyncDatabase and SyncDocument.

Profile database
{
"id": "john@example.com",
"name": "John",
"age": 30,
"isMale": true,
"contact": {
"phone": "+82-10-1234-5678",
"github": "https://github.com/john",
"linkedin": "https://www.linkedin.com/in/john",
"address": {
"street": "123 Main St",
"city": "Seoul",
"country": "South Korea"
}
},
"skills": [
{
"name": "Java",
"proficiency": "Expert"
},
{
"name": "Kotlin",
"proficiency": "Advanced"
}
]
}

Define a data class to receive Profile data.

data class Profile(
val id: String,
val name: String,
val age: Int,
val isMale: Boolean,
val contact: Contact,
val skills: List<Skill>
)

data class Contact(
val phone: String,
val github: String,
val linkedin: String,
val address: Address
)

data class Address(
val street: String,
val city: String,
val country: String
)

data class Skill(
val name: String,
val proficiency: String,
)

After initializing SyncDatabase, use SyncDocument to read and write data and receive real-time updates for changed data.

lifecycleScope.launch {
val configsProvider = SyncConfigsProvider.createFromConfigFile(applicationContext).getOrThrow()

SyncDatabase.initialize(application, configsProvider) {
if (it.isReady()) {
// handle success
syncDatabase = SyncDatabase.getInstance("Profile")!!
} else {
// handle failure
val connectionState = it["Profile"]
Log.d("Sync SDK", connectionState?.reason ?: "unknown reason")
}
}
}

val document = syncDatabase.document("john@example.com")
document.addDocumentEventListener(object : DocumentListener {
override fun onDocumentChanged(document: SyncDocument,fromRemote: Boolean) {
// handle changes
val profile: Profile? = document.value()
val jsonString: String? = document.jsonString
}

override fun onDocumentError(document: SyncDocument, e: SyncError) {
// handle error
}
})

document.child("contact").setKeyValue("+82-10-8765-4321", "phone")
val phone = document.child("contact").child("phone").value<String>()
/*
"phone": +82-10-8765-4321"
*/

val addrDocument = document.paths("contact", "address")
addrDocument.setKeyValue("742 Evergreen Terrace", "street")
val street = addrDocument.child("street").value<String>()
/*
"street": "742 Evergreen Terrace"
*/

val android = Skill(name = "Android", proficiency = "Expert")
document.child("skills").insertToArray(0, android)
/*
"skills": [
{
"name": "Android",
"proficiency": "Expert"
},
{
"name": "Java",
"proficiency": "Expert"
},
{
"name": "Kotlin",
"proficiency": "Advanced",
}
]
*/