java.lang.NullPointerException при загрузке большого файла - PullRequest
0 голосов
/ 02 ноября 2018

Я использую Firebase Cloud Messaging для отправки файлов с веб-сайта на устройство Android. Обратите внимание, что я нажимаю, когда мое приложение близко / в фоновом режиме / выход. Я использую сервис для получения уведомления. Файл успешно загружен с помощью Asynctask:

private static class DownloadFileTask extends AsyncTask<String, String, String> {
    String notiType = null;

    String dlink = null;
    String fileName = null;

    private WeakReference<MyFirebaseMessagingService> activityReference;


    DownloadFileTask(MyFirebaseMessagingService context) {
        activityReference = new WeakReference<>(context);
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG, "DownloadFile");
    }

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

        int count;
        String filePath = null;
        notiType = payload[0];
        dlink = payload[1];
        fileName = payload[2];

        try {
            URL url = new URL(dlink);
            URLConnection conection = url.openConnection();
            conection.connect();
            int lenghtOfFile = conection.getContentLength();
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            OutputStream output = null;

            switch (notiType) {
                case Notification_001:
                    filePath = activityReference.get().getFileDir("/DownloadedFiles", fileName);
                    break;

                case Notification_002:
                    filePath = activityReference.get().getFileDir("/DownloadedAPK", fileName);
                    break;

                   default:

                    break;
            }

            if (filePath != null) {
                File myFile = new File(filePath);
                if (myFile.exists()) {
                    myFile.delete();
                    Log.d(TAG, "file exist. delete it first");
                }
            }

            output = new FileOutputStream(filePath);
            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) {
            Log.e(TAG, "exception", e);
        }

        return filePath;
    }

    protected void onProgressUpdate(String... progress) {
    }

    @Override
    protected void onPostExecute(String file_url) {
        if (file_url == null) {
            Log.d(TAG, "DownloadFile Error");
            activityReference.get().setToast("ERROR downloading file.. URL is invalid.");
        } else {
            Log.d(TAG, "DownloadFile Finish");
            File file = new File(file_url);
            if (file.exists() && file.length() > 0) {


                switch (notiType) {

                    case Notification_001:

                            if (activityReference.get().isAppInForeground) {


                            }           

                            Log.d(TAG, "Task finish");                         
                        break;
                    case Notification_002:
                       break;
                    default:
                        break;

                }

        } else{

            activityReference.get().setToast("File downloaded but file has 0 size.");
        }
    }
}

}

Однако я сталкиваюсь с проблемой в методе PostExecute, когда я не могу вызвать нативный метод, например activityReference.get().isAppInForeground. У меня есть следующее исключение

java.lang.NullPointerException
    at xk.service.MyFirebaseMessagingService$DownloadFileTask.onPostExecute(MyFirebaseMessagingService.java:342)
    at xk.service.MyFirebaseMessagingService$DownloadFileTask.onPostExecute(MyFirebaseMessagingService.java:228)
    at android.os.AsyncTask.finish(AsyncTask.java:632)
    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

Исключение часто возникает, когда размер файла, например, 17 КБ, но небольшого размера, например 10 КБ, не вызывает проблем в методе invoke.

Спасибо ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...