Search code examples
androidasynchronouskotlinandroid-asynctasklogcat

Android AsyncTask Doesn't Run


i have an AsyncTask class in Kotlin and it doesn't start running when it's called. The AsyncTask is supposed to download JSON data from a specific URL. The doInBackground method is never started and nothing happens.

onCreate()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // TODO Remove After
//        loadData()
    getDataFromUrl()

    // Set adapter
    adapter = CardAdapter(listOfCard, this)
    lvCards.adapter = adapter
}

My getDataFromUrl(), where the AsyncTask is called:

private fun getDataFromUrl() {
    val url = "https://pay-app-api.herokuapp.com/card/user/1"
    mAsyncTask().execute(url)
}

AsyncTask Inner class:

inner class mAsyncTask: AsyncTask<String, String, String>() {

    override fun onPreExecute() {
        Log.d(TAG, "Pre Execute")
        super.onPreExecute()
    }

    override fun doInBackground(vararg params: String?): String? {
        try {
            // Connect to URL
            val url = URL(params[0])
            val urlConnect = url.openConnection() as HttpURLConnection
//                urlConnect.connectTimeout = 5000

            // Read Data from URL
            val mInputString = 
            convertStreamToString(urlConnect.inputStream)

            publishProgress(mInputString)

        } catch (ex: Exception) {}

        return ""
    }

    override fun onProgressUpdate(vararg values: String?) {

        try {
            val json = JSONObject(values[0])
            tvJsonTest.text = "Downloaded"
            Log.d(TAG, json.toString())
            System.out.print("Downloading...")
        } catch (ex: Exception) {}

//            super.onProgressUpdate(*values)
    }
}

And LogCat logs:

09-03 22:44:44.337 2647-2647/? E/Zygote: v2
09-03 22:44:44.337 2647-2647/? I/libpersona: KNOX_SDCARD checking this for 
10228
KNOX_SDCARD not a persona
09-03 22:44:44.342 2647-2647/? E/Zygote: accessInfo : 0
09-03 22:44:44.344 2647-2647/? W/SELinux: SELinux         
selinux_android_compute_policy_index : Policy Index[2],  Con:u:r:zygote:s0     
RAM:SEPF_SECMOBILE_7.1.1_0003, [-1 -1 -1 -1 0 1]
09-03 22:44:44.347 2647-2647/? I/SELinux: SELinux: seapp_context_lookup: 
seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.makro123.payapp 
09-03 22:44:44.354 2647-2647/? I/art: Late-enabling -Xcheck:jni
09-03 22:44:44.717 2647-2647/com.example.makro123.payapp W/System: 
ClassLoader referenced unknown path: 
/data/app/com.example.makro123.payapp-1/lib/arm
09-03 22:44:44.751 2647-2647/com.example.makro123.payapp I/InstantRun: 
starting instant run server: is main process
09-03 22:44:44.885 2647-2647/com.example.makro123.payapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
09-03 22:44:45.045 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.047 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.052 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.064 2647-2647/com.example.makro123.payapp D/MainActivity: Pre Execute
09-03 22:44:45.100 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: ThreadedRenderer.create() translucent=false
09-03 22:44:45.105 2647-2647/com.example.makro123.payapp D/InputTransport: Input channel constructed: fd=74
09-03 22:44:45.107 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: setView = DecorView@ec37ba4[MainActivity] touchMode=true
09-03 22:44:45.110 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: dispatchAttachedToWindow
09-03 22:44:45.149 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][720,1280] result=0x27 surface={isValid=true -1863970816} surfaceGenerationChanged=true
    mHardwareRenderer.initialize() mSurface={isValid=true -1863970816} hwInitialized=true
09-03 22:44:45.151 2647-2686/com.example.makro123.payapp I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8916_32_LA.BR.1.2.9_RB1__release_AU (I750f7f2fa6)
    OpenGL ES Shader Compiler Version: XE031.09.00.03
    Build Date: 02/18/17 Sat
    Local Branch: 
    Remote Branch: quic/LA.BR.1.2.9_rb1.12
    Local Patches: NONE
    Reconstruct Branch: NOTHING
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp I/OpenGLRenderer: Initialized EGL, version 1.4
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp D/OpenGLRenderer: Swap behavior 1
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp W/Adreno-EGL: <qeglDrvAPI_eglCreateContext:2475>: EGL_BAD_ATTRIBUTE
09-03 22:44:45.155 2647-2686/com.example.makro123.payapp I/OpenGLRenderer: KHR Debugger is Disabled - EGL_BAD_ATTRIBUTE
09-03 22:44:45.159 2647-2647/com.example.makro123.payapp D/AbsListView:  in onLayout changed 
09-03 22:44:45.208 2647-2647/com.example.makro123.payapp W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
09-03 22:44:45.227 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.233 2647-2647/com.example.makro123.payapp D/TextView: setTypeface with style : 0
09-03 22:44:45.257 2647-2647/com.example.makro123.payapp D/ViewRootImpl@39afa37[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
    MSG_WINDOW_FOCUS_CHANGED 1
    mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true -1863970816}
09-03 22:44:45.259 2647-2647/com.example.makro123.payapp V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@7159272 nm : com.example.makro123.payapp ic=null
09-03 22:44:45.259 2647-2647/com.example.makro123.payapp I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
09-03 22:44:45.270 2647-2681/com.example.makro123.payapp D/InputTransport: Input channel constructed: fd=78
09-03 22:44:45.282 2647-2647/com.example.makro123.payapp V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@cfa46c3 nm : com.example.makro123.payapp ic=null

Solution

  • This line in your doInBackground stops all execution and throws a RuntimeException:

    Toast.makeText(applicationContext, "Async Task", Toast.LENGTH_SHORT).show()
    

    The reason is that this line needs to be run on the main thread (UI) and if not it just mysteriously stops all further execution and crashes - silently!

    The reason why it's crashing silently is because you've "eaten" the exception in the end of doInBackground.

    If you hadn't "eaten" the exception you'd get an exception saying something like this:

    Caused by: java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
    

    If you want to call some code, that needs to be run on the UI thread, you should call it in onProgressUpdate - this is also stated in the documentation of AsyncTask.

    onPreExecute and onPostExecute will also be called on the UI thread hence it's safe to change things in the UI or present a Toast there.