Home » Android » android – While loop not properly working on device, it works well in the emulator-Exceptionshub

android – While loop not properly working on device, it works well in the emulator-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

While loop not properly work in device , it works well in emulator. What will be an issue? Below is my code,

 val query = database?.createAllDocumentsQuery()
    query?.startKey = "refill-device-SERIAL-AB121-0"
    query?.endKey = "refill-device-SERIAL-AB121-7"
    var result: QueryEnumerator? = null
    result = query?.run()
    val it = result
    if (it != null) {
        while (it.hasNext()) {
            val row = it.next()
            if (row.documentId.startsWith("refill-device-SERIAL-")) {
                obj = JSONObject(row.document.properties)
                val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
                arrayList.add(canisters)
            }
        }
        canistersArrayList.postValue(arrayList)
    }
How to&Answers:

You have to use thread or asynctask for long running operations. Sometime this long running operations works fine on emulator but fails on real device. Do you have any logs in logcat if yes please post them as well.

AsyncTask will look like this

class queryTask() : AsyncTask<Void, Void, ArrayList>() {
    override fun doInBackground(vararg params: Void?): String? {
      val query = database?.createAllDocumentsQuery()
    query?.startKey = "refill-device-SERIAL-AB121-0"
    query?.endKey = "refill-device-SERIAL-AB121-7"
    var result: QueryEnumerator? = null
    result = query?.run()
    val it = result
    if (it != null) {
        while (it.hasNext()) {
            val row = it.next()
            if (row.documentId.startsWith("refill-device-SERIAL-")) {
                obj = JSONObject(row.document.properties)
                val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
                arrayList.add(canisters)
            }
        }

        return arrayList
    }   
    }

    override fun onPreExecute() {
        super.onPreExecute()

    }

    override fun onPostExecute(result: ArrayList?) {
        super.onPostExecute(result)
        canistersArrayList.postValue(result)

    }
}

And execute it like

queryTask().execute()