[Android] RuntimeException on AsyncTask : NullPointerException on doInBackground
Here’s a memo on how to solve a bug where a RuntimeException occurs during AsyncTask execution in an Android app, causing a crash.
"Thread: AsyncTask #5, Exception: java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.example.myapp.d.c$a.doInBackground(SourceFile:1)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 5 more"
The solution is to properly wrap the part where the NullPointerException occurs in the doInBackground method with a try/catch block, and return null at the end of the method.
Also, in the onPostExecute method, you need to handle the case when the async task fails (when null is passed as an argument).
[References]
・android - AsyncTask doInBackground returning a nullpointerexception only sometimes - Stack Overflow
・Android : Getting RuntimeException on AsyncTask - Stack Overflow
That’s all from the Gemba.