Created
February 4, 2019 19:07
-
-
Save yasincidem/e353d3f2a1ce708878c85d6e4e195064 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
import android.os.Bundle | |
import android.os.Handler | |
import android.os.Message | |
import android.view.View | |
import androidx.appcompat.app.AppCompatActivity | |
import kotlinx.android.synthetic.main.activity_main.* | |
import java.io.BufferedReader | |
import java.io.InputStreamReader | |
import java.net.URL | |
class MainActivity : AppCompatActivity() { | |
private val MSG_SHOW_PROGRESS = 1 | |
private val MSG_SHOW_IMAGE = 2 | |
private lateinit var handler: Handler | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
handler = Handler(UIHandler()) | |
Thread(JsonMessageCreator("https://jsonplaceholder.typicode.com/todos/1")).start() | |
} | |
fun getJsonFromServer(url: String): String { | |
val inputStream: BufferedReader | |
val jsonUrl = URL(url) | |
val dc = jsonUrl.openConnection() | |
dc.connectTimeout = 5000 | |
dc.readTimeout = 5000 | |
inputStream = BufferedReader( | |
InputStreamReader( | |
dc.getInputStream() | |
) | |
) | |
var string = "" | |
inputStream.readLines().forEach{ | |
string += it | |
} | |
return string | |
} | |
inner class JsonMessageCreator(val url: String) : Runnable { | |
override fun run() { | |
handler.obtainMessage(MSG_SHOW_PROGRESS).sendToTarget() | |
val data = getJsonFromServer(url) | |
handler.obtainMessage(MSG_SHOW_IMAGE, data).sendToTarget() | |
} | |
} | |
inner class UIHandler: Handler.Callback { | |
override fun handleMessage(msg: Message?): Boolean { | |
when(msg?.what) { | |
MSG_SHOW_PROGRESS -> progress_bar.visibility = View.VISIBLE | |
MSG_SHOW_IMAGE -> { | |
progress_bar.visibility = View.GONE | |
json_textview.text = msg.obj as CharSequence | |
} | |
} | |
return true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment