Search code examples
androidkotlinandroid-asynctask

Kotlin's URL.readText() crashes when I turn my phone's internet off


I am doing an HTTP GET request using Kotlin's URL.readText() in an AsyncTask. I'm not making the common mistake of networking in the UI thread, yet my app still experiences crashes.

If I start my app with internet off or turn internet off during operation, it crashes the next time I indirectly trigger a GET request with user input. What is a good way to do a "safe" GET request that just returns an empty String for example instead of crashing?

I separated each call into its own line to make sure it was readText() causing the crash, and not for example the GoogleMap I also use. I also checked the URL object and it is not null. The app does not request any permissions.


Task:

class MyTask(map : GoogleMap, url : String) : AsyncTask<Void, Void, String>() {
    val mMap = map;
    val mURL = url;

    override fun doInBackground(vararg params: Void?): String {
        return URL(mURL).readText()
    }

    ... (more code) ...
}

UI Thread:

MyTask(mMap, url).execute()

Log:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1

Solution

  • @CommonsWare's suggestion of catching an Exception works for me, I thought the "fatal" meant it cannot be caught.

    override fun doInBackground(vararg params: Void?): String {
        return try {
            URL(mURL).readText()
        } catch (ex : Exception) {
            "null"
        }
    }
    

    Even shorter:

    override fun doInBackground(vararg params: Void?): String =
        try { URL(mURL).readText() } catch (ex : Exception) { "null" }