Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. class ExecutionThread(private val mCustomCallback: CustomCallback) : Thread() {
  2.  
  3. override fun run() {
  4. mCustomCallback.showProgressBar()
  5. val inputStream = BufferedInputStream(URL(JSON_URL).openStream())
  6. val url = URL(JSON_URL)
  7. val connection = url.openConnection()
  8. connection.connect()
  9. inputStream.bufferedReader().use { File(FILE_PATH).writeText(it.readLine()) }
  10. val text = File(FILE_PATH).readText()
  11. val flightResponse = parseJson(text)
  12. val flights = flightResponse?.flights
  13. mCustomCallback.setFlights(flights)
  14. mCustomCallback.hideProgressBar()
  15. }
  16.  
  17. private fun parseJson(text: String): FlightResponse? {
  18. var flightResponse: FlightResponse? = null
  19. try {
  20. val list = ArrayList<Flight>()
  21. val jsonArray = JSONArray(text)
  22. (0 until jsonArray.length())
  23. .map { jsonArray.getJSONObject(it) }
  24. .forEach {
  25. list.add(Flight(it.optInt("flight_number"),
  26. Rocket(it.optJSONObject("rocket").optString("rocket_id"),
  27. it.optJSONObject("rocket").optString("rocket_name")),
  28. it.optString("launch_date_unix"),
  29. Links(it.optJSONObject("links").optString("mission_patch"),
  30. it.optJSONObject("links").optString("article_link"),
  31. it.optJSONObject("links").optString("video_link")),
  32. it.optString("details")))
  33. }
  34. flightResponse = FlightResponse(list)
  35. } catch (ex: JSONException) {
  36. ex.printStackTrace()
  37. }
  38. return flightResponse
  39. }
  40.  
  41. companion object {
  42. val JSON_URL = "https://api.spacexdata.com/v2/launches?launch_year=2017"
  43. val FILE_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path + "/temp.json"
  44. }
  45.  
  46. interface CustomCallback {
  47.  
  48. fun setFlights(flights: List<Flight>?)
  49.  
  50. fun showProgressBar()
  51.  
  52. fun hideProgressBar()
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement