Last active
April 30, 2019 23:45
-
-
Save ismailgungor/9eedf3923070dc27c5b7894c33627e0d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GetUsersAsyncTask : AsyncTask<Void, Void, ArrayList<User>?>() { | |
override fun doInBackground(vararg params: Void?): ArrayList<User>? { | |
var urlConnection: HttpURLConnection? = null | |
var reader: BufferedReader? = null | |
val userList = ArrayList<User>() | |
try { | |
val url = URL("http://5cb8aeae1551570014da41eb.mockapi.io/api/users") | |
urlConnection = url.openConnection() as HttpURLConnection? | |
urlConnection?.requestMethod = "GET" | |
urlConnection?.connect() | |
val inputStream = urlConnection?.inputStream ?: return null | |
reader = BufferedReader(InputStreamReader(inputStream)) | |
val response = reader.readLine() | |
response?.let { | |
val jsonArray = JSONArray(it) | |
if (jsonArray.length() != 0) { | |
for (index in 0 until jsonArray.length()) { | |
val jsonObject = jsonArray.getJSONObject(index) | |
jsonObject?.let { | |
val createdAt = jsonObject.getString("createdAt") | |
val isPro = jsonObject.getBoolean("is_pro") | |
val name = jsonObject.getString("name") | |
val id = jsonObject.getString("id") | |
val avatar = jsonObject.getString("avatar") | |
val job = jsonObject.getString("job") | |
val username = jsonObject.getString("username") | |
val user = User(createdAt, isPro, name, id, avatar, job, username) | |
userList.add(user) | |
} | |
} | |
} | |
} | |
} catch (e: Exception) { | |
e.printStackTrace() | |
}finally { | |
urlConnection?.disconnect() | |
reader?.close() | |
} | |
return userList | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment