Skip to content
This repository was archived by the owner on Nov 24, 2020. It is now read-only.

Commit 6bed62e

Browse files
answer api calls on main thread - kt android
1 parent b9d6d9f commit 6bed62e

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

src/target/kt_android.cr

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ import android.annotation.SuppressLint
3737
import android.content.Context
3838
import android.graphics.Point
3939
import android.os.Handler
40-
import android.os.HandlerThread
4140
import android.provider.Settings
4241
import android.util.Log
4342
import com.google.gson.Gson
@@ -46,6 +45,7 @@ import java.io.IOException
4645
import java.io.Serializable
4746
import org.json.JSONArray
4847
import com.google.gson.reflect.TypeToken
48+
import android.os.Looper
4949
5050
@SuppressLint("SimpleDateFormat")
5151
object API {
@@ -270,19 +270,26 @@ END
270270
client.newCall(request).enqueue(object: Callback {
271271
override fun onFailure(call: Call?, e: IOException?) {
272272
e?.printStackTrace()
273-
callback(Error(ErrorType.Fatal, e?.message ?: "Chamada falhou sem mensagem de erro!"), null)
273+
Handler(Looper.mainLooper).post {
274+
callback(Error(ErrorType.Fatal, e?.message ?: "Chamada falhou sem mensagem de erro!"), null)
275+
}
274276
}
275277
276278
override fun onResponse(call: Call?, response: Response?) {
277279
if (response == null || response.code() == 502) {
278-
callback(Error(ErrorType.Fatal, "Erro Fatal (502) - Tente novamente"), null)
280+
Handler(Looper.mainLooper).post {
281+
callback(Error(ErrorType.Fatal, "Erro Fatal (502) - Tente novamente"), null)
282+
}
283+
return
279284
}
280285
281286
var responseBody = try {
282287
val stringBody = response?.body()?.string()
283288
JSONObject(stringBody)
284289
} catch (e: Exception) {
285-
callback(Error(ErrorType.Fatal, "502 - Tente novamente"), null)
290+
Handler(Looper.mainLooper).post {
291+
callback(Error(ErrorType.Fatal, "502 - Tente novamente"), null)
292+
}
286293
null
287294
return
288295
}
@@ -295,15 +302,21 @@ END
295302
//TODO Fetch correct error type
296303
val error = Error(ErrorType.valueOf(jsonError.getString("type")), jsonError.getString("message"))
297304
Log.e("API Error", jsonError.getString("type") + " - " + error.message);
298-
callback(error, null)
305+
Handler(Looper.mainLooper).post {
306+
callback(error, null)
307+
}
299308
} else {
300-
callback(null, responseBody)
309+
Handler(Looper.mainLooper).post {
310+
callback(null, responseBody)
311+
}
301312
}
302313
}
303314
})
304315
} catch (e: JSONException) {
305316
e.printStackTrace()
306-
callback(Error(ErrorType.Fatal, e.message ?: "Erro ao parsear json"), null)
317+
Handler(Looper.mainLooper).post {
318+
callback(Error(ErrorType.Fatal, e.message ?: "Erro ao parsear json"), null)
319+
}
307320
}
308321
}
309322
}

0 commit comments

Comments
 (0)