AsyncTask Android generating NullPointerException

0

I have this static class in an Activity where its function and download a file and save it on the user's device. I tested it on a real device in Android version 7.1.1 and 4.1.2 and it worked correctly. However, by launching the application I have received error reports from Android versions 7.1, 6.0 and 7.0 referring to the NullPointerException of the InBackground process in the line referring to catch (Exception e) p>

Class Code

private static class DownloadFileFromURL extends AsyncTask<String, String, String> {

    private WeakReference<DownloadActivity> activityReference;

    DownloadFileFromURL(DownloadActivity context) {
        activityReference = new WeakReference<>(context);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        DownloadActivity activity = activityReference.get();
        activity.txt_status_progress.setText(String.format(activity.getString(R.string.txt_baixando_dados),String.valueOf(0)));
    }

    @Override
    protected String doInBackground(String... f_url) {

        DownloadActivity activity = activityReference.get();

        int count;

        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            int lenghtOfFile = conection.getContentLength();

            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            FileOutputStream output = activity.openFileOutput(FOLDER + File.pathSeparator + FILE_SQL, Context.MODE_PRIVATE);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();

        } catch (Exception e) {
            progressBar.setVisibility(View.GONE);
            txt_status_progress.setText(R.string.txt_erro_config);
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        DownloadActivity activity = activityReference.get();
        activity.txt_status_progress.setText(String.format(activity.getString(R.string.txt_baixando_dados),progress[0]));
    }

    @Override
    protected void onPostExecute(String file_url) {
        DownloadActivity activity = activityReference.get();
        new DownloadActivity.insertFromFile(activity).execute();
    }
}

What might be causing this error?

    
asked by anonymous 04.05.2018 / 23:16

1 answer

1

Probably the activity, in which the download is occurring, is being destroyed by the system but the task continues to run. And anywhere you access the variable activity (or any variable belonging to the destroyed activity) will generate a nullpointer, since that reference no longer exists.

AsyncTasks do not follow the same life cycle as the Activity in which you started it. So it's entirely possible that AsyncTask keeps running while activity no longer exists. What may be causing the problem you are having. As much as you have passed the activity reference in the AsyncTask constructor, Android may have killed it, so the reference you are currently holding in AsyncTask is invalid and any attribute or method access will generate nullpointer.

Since you have not given information that it is possible to change the orientation of the phone to horizontal and if there is a possibility to go to the next activity during the download, I will assume that both are true.

There are a few ways to test this hypothesis.

  • The simplest is to just start downloading and closing the app (kill the process) and see what happens.
  • You can also start downloading and switch the orientation of the phone horizontally if possible.
  • Another is to go in the developer settings and select the "do not keep activities" option. Start the download and open a new activity.
  • Probably scenarios 1 and 2 will actually show the cause of the bug.

    And one possible solution would be for you to use Fragments to not only download but for any use of threads that access class variables.

    Fragments has a method called setRetainInstance , which serves to maintain the current fragment instance when it occurs a configuration change in the activity in which the fragment is committed.

    Another solution would be to kill (call the cancel method) AsyncTask in% of its Activty%.

        
    07.05.2018 / 03:17