I am working on a server-client model using the Nearby Connections API, and I'm trying to transfer a large amount of data between the devices. I've already tried sending the data as bytes, but it didn't work well for large amounts of data. Now, I have an ArrayList containing 5000 records that I want to send as a stream to the nearby device, but I'm facing errors when I try to do this. I'm wondering if there is a way to send the 5000 records in chunks as byte format or if there is a way to send the entire ArrayList as a stream to the nearby device.
Here is the Code snipet to send arrayList:
fun sendDataFromServer(list: ArrayList<PatientEntity>) {
if (isHost) {
val json = gson.toJson(list)
Log.d(TAG, "Json : $json")
val inputStream = ByteArrayInputStream(json.toByteArray())
val payload = Payload.fromStream(inputStream)
getClients().forEach { endpointId ->
connectionsClient.sendPayload(endpointId, payload).addOnSuccessListener {
Log.d(TAG, "Payload sent successfully: $payload")
}.addOnFailureListener { e ->
Log.e(TAG, "Error sending payload: $payload", e)
}
}
}
}
Here is the Code snipet to recieve arrayList:
val inputStream =
payload.asStream()
?.asInputStream() // Get the input stream from the payload
val bufferedReader = BufferedReader(InputStreamReader(inputStream))
val json = StringBuilder()
var line: String?
while (bufferedReader.readLine().also { line = it } != null) {
json.append(line)
}
val type = object : TypeToken<ArrayList<PatientEntity>>() {}.type
val list: ArrayList<PatientEntity> = gson.fromJson(json.toString(), type)
_patientList.value.addAll(list)
If I send less data arrayList so it works fine, but if try to send large arrayList it shows this error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
I would greatly appreciate your help if you know how to solve this issue. If you have a solution, please share it with me. Thank you in advance for your assistance.