'"E/Perf: getFolderSize() : Exception_1 = java.lang.NullPointerException: Attempt to get length of null array" error

I am trying to create an app which downloads and plays music. For stopping users from copying the music files, I want to encrypt the file as soon as it is downloaded. I am struggling with the code for days, but cannot find out what is causing the errors. Here is the relevant code -

private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {
        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        if (downloadID == id) {
            Toast.makeText(DownloadActivity.this, "Download completed", Toast.LENGTH_SHORT).show();

            Context appContext = getApplicationContext();
            MasterKey mainKey = new MasterKey.Builder(appContext)
                    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
                    .build();

            String fileToWrite = songName + ".mp3";
            EncryptedFile encryptedFile = new EncryptedFile.Builder(context,
                    new File(getExternalFilesDir(null), fileToWrite),
                    mainKey,
                    EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
            ).build();

            byte[] fileContent = convert(getExternalFilesDir(null).getAbsolutePath() + "/" + songName + ".mp3");
            OutputStream outputStream = encryptedFile.openFileOutput();
            outputStream.write(fileContent);
            outputStream.flush();
            outputStream.close();
        }
    }

    public byte[] convert(String path) throws IOException {

        FileInputStream fis = new FileInputStream(path);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];

        for (int readNum; (readNum = fis.read(b)) != -1;) {
            bos.write(b, 0, readNum);
        }

        byte[] bytes = bos.toByteArray();

        return bytes;
    }
};

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(onDownloadComplete);
}

I also wrap the necessary lines with try-catch. Removed it here for simplifying the code.

Also, I will be very grateful if I could get advice on what is the best way to play encrypted audio files, while keeping them safe. Is creating temporary file for playing a good option?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source