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?