I am trying to fetch data from server and sync it on the background of app. I did it using AsyncTask in an Intent Service class, but now I want to make network call using Retrofit. So, I fetched data from server using retrofit but while I am saving them on the local database the main thread freezes, only after completion of the process I can do something on the Main thread. Why is this happening?
I tried both synchronus and Asynchronus request of retrofit but the problem remains. This is what I have tried so far..
//calling company api in synchronus way
try {
val responseCompany = apiService.company(page, headers, bodyModel).execute()
Log.e("onResponse", "Company Response Code: ${responseCompany.code()}")
Log.e("onResponse", "Company Response Body: ${Gson().toJson(responseCompany.body())}")
if (responseCompany.isSuccessful) {
val response = responseCompany.body()
//delete company data
if (response?.delete?.data?.size!! > 0) {
for (i in response.delete.data.indices) {
val delete = response.delete.data[i]
Log.e(tag, "Delete Company data $i: ${delete.company_id}")
dbAdapter.open()
dbAdapter.Delete_COMPANY_NAME(delete.company_id)
dbAdapter.close()
}
}
//insert company data
if (response.insert.data.isNotEmpty()) {
for (i in response.insert.data.indices) {
val insert = response.insert.data[i]
Log.e(tag, "Insert company data $i: ${insert.company_id}")
dbAdapter.open()
dbAdapter.Insert_COMPANY_NAME(insert.company_id.toString(), insert.company_name)
dbAdapter.close()
}
}
//update company data
if (response.update.data.isNotEmpty()) {
for (i in response.update.data.indices) {
val update = response.update.data[i]
Log.e(tag, "Update Company data $i: ${update.company_id}")
dbAdapter.open()
dbAdapter.Update_COMPANY_NAME(update.company_id.toString(), update.company_name)
dbAdapter.close()
}
}
val totalPage = largest(response.delete.meta.pagination.total_pages, response.insert.meta.pagination.total_pages, response.update.meta.pagination.total_pages)
if (page < totalPage) {
prefManager.pageNumber = page + 1
bodyModel.date = lastAdUpdate2
bodyModel.limit = 500
companyData(bodyModel)
} else {
prefManager.T_COMPANY_NAME = currentTime
prefManager.PAGE_NUMBER = 1
prefManager.TOTAL_PAGE = 1
prefManager.pageNumber = 1
prefManager.FIRST = "1"
pagenumber = prefManager.PAGE_NUMBER
Handler().postDelayed({
bodyModel.limit = 100
bodyModel.date = lastAdUpdate3
generics(bodyModel)
}, 1000)
}
} else {
prefManager.dbUpdateStatus = false
Log.i("dataNotInsert", "data Not Insert")
}
} catch (e: Exception) {
Log.e("Exception", "Company: ${e.localizedMessage}")
e.printStackTrace()
}
N.B: I made network call (Retrofit request) in an Intent Service class..
Any Kind of help is highly appreciated. Thank you
This problem was actually solved by replacing Intent Service with Work Manager. And Using Kotlin Coroutine
And if you want to persist with Intent Service rather than using WorkManager. Just wrapping your network call with AsyncTask will solve the problem