Search code examples
javaandroidapikotlingeturl

Attempt to invoke virtual method 'java.lang.String at.huber.youtubeExtractor.YtFile.getUrl()' on a null object reference


In the first install application in my physic device. I am able to download some videos to storage but when I do the same with some more videos it cannot. Then Android Studio IDE announce to me error in line init String downloadURL like title of this question. This is my code:

String youtubeLink = ("https://www.youtube.com/watch?v=" + videoYT.getId().getVideoId());
                    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(context) {
                        @Override
                        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
                            if (ytFiles != null) {
                                int itag = 22;
                                String downloadURL = ytFiles.get(itag).getUrl();// line where Android Studio IDE gives an error
                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadURL));
                                String title = URLUtil.guessFileName(downloadURL,null,null);
                                request.setTitle(title);
                                request.setDescription("Downloading file...");
                                String cookie = CookieManager.getInstance().getCookie(downloadURL);
                                request.addRequestHeader("cookie",cookie);
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,title);
                                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);
                                Toast.makeText(context, "Bắt đầu tải xuống...", Toast.LENGTH_SHORT).show();
                            }
                        }
                    };
                    ytEx.execute(youtubeLink);

Solution

  • The problem is here ytFiles.get(itag).

    In the source code of SparseArray: get() will return null

         /**
          * Gets the Object mapped from the specified key, or <code>null</code>
          * if no such mapping has been made.
          */
         public E get(int key) {
             return get(key, null);
         }
    

    If you use kotlin to implement, you need to modify it to:

    val downloadURL = ytFiles.get(itag)?.getUrl() ?: ""
    

    To achieve this with Java, you need to perform a null operation on the ytFiles.get(itag) object.