-1

This was something that I expect not to be happening, hence I need help from here.

In my app, I execute() an AsyncTask which might take less than 2-3 seconds. In that AsyncTask I have runOnUiThread() which updates few UI controls value.

This works fine until, if I do a click on Sign out button which does a finish() of Activity.

I get Null pointer exception that findViewById returned null. I can add null check before updating but considering the amount of UI screens and AsyncTasks used I would end up in huge number of checks.

What is best solution to this case? Issue happens only when there is exact coincidence with time difference between AsyncTask completion and call to finish().

harshal
  • 592
  • 6
  • 25
  • if u close the app while the async is running, youll get that. i used a bool to help me with mine. i set it to false on activity creation. i set to true during pre and set it to false AFTER everything in post is done. when i call it. i do if (!running) {new .execute()}else {} seems to fix mine – letsCode Sep 22 '17 at 20:01

1 Answers1

0

Avoid calling runOnUiThread() method for updating progress from your AsyncTask's doInBackground(). You have onProgressUpdate() for this. Here is a basic example on how to call this method inside AsyncTask:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

Remember, inside your AsyncTask, only one method runs on the background thread - doInBackground(), the rest runs on your MainThread.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
  • I am not planning to update progress, once I complete my network interaction in my AsyncTask I am trying to update the UI fields with values. – harshal Sep 22 '17 at 20:30