Issue
When my database is running, everything is okey. But when is not running my mobile app always crash.
Error message:
Caused by: java.net.ConnectException: Failed to connect to /httpURL.
How to fix problem?
here is my code:
AsyncTaskHandleJson().execute(url)
inner class AsyncTaskHandleJson : AsyncTask<String, String, String>() {
override fun doInBackground(vararg url: String?): String {
var text: String
var connection = URL(url[0]).openConnection() as HttpURLConnection
try {
connection.connect()
text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
} finally {
connection.disconnect()
}
return text
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
handleJson(result)
}
}
Solution
Since there is no catch
block in your code, you are not catching any exceptions currently.
If you would like to handle the ConnectException
, then you simply have to catch it:
override fun doInBackground(vararg url: String?): String {
var text = ""
var connection: HttpURLConnection? = null
try {
connection = URL(url[0]).openConnection() as HttpURLConnection
connection.connect()
text = connection.inputStream.use {
it.reader().use { reader ->
reader.readText()
}
}
} catch (ce: ConnectException) {
// ConnectionException occurred, do whatever you'd like
ce.printStackTrace()
} catch (e: Exception) {
// some other Exception occurred
e.printStackTrace()
} finally {
connection?.disconnect()
}
return text
}
Check out the Exceptions reference.
Answered By - earthw0rmjim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.