После загрузки нескольких файлов, получить путь ко всем файлам Android - PullRequest
0 голосов
/ 03 июля 2019

Должно произойти: загрузка и воспроизведение из хранилища

Реализация: загрузка нескольких файлов mp3 во внешнее хранилище, вставка в таблицу данных mp3_file_name и других данных столбца, получение пути к этим загруженным файлам, обновление путейmp3_file_name получено.Все это происходит в Asynctask.

Это происходит: загрузка работает, вставка значений работает. Получение массива путей не работает.Когда я отлаживаю, я получаю все пути, но когда я бегу, получаются только некоторые пути. Я застрял на этом с нескольких дней, любая помощь приветствуется.Спасибо

Когда API позвонил и получил массив songdetails, песни загружаются

 for (final SongDetails song : songDetailsArrayList) {
      beginDownloadingSong(song);
 }

public void beginDownloadingSong(SongDetails song) {
    String pathh = Environment.getExternalStorageDirectory() + "/Allsongs/";
    File directory1 = new File(pathh);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(FinalStrings.SERVER_BASE_URL_AWS + song.getSong_file_name()))              .setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
            .setDestinationUri(Uri.fromFile(new File(directory1 + "/" + song.getTitle() + "_" + song.getId() + ".mp3")))
            .setAllowedOverMetered(true)
            .setAllowedOverRoaming(true);
    DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    downloadID = (downloadManager).enqueue(request);
}

 private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        long id = intent.getLongExtra(DownloadManager.ACTION_DOWNLOAD_COMPLETE, -1);
        success++;
        if (success == 1) {
            new insertSongDatabase().execute();

        }
    }
};


class insertSongDatabase extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... voids) {
        helper.insertSongDetails(songDetailsArrayList);
        // get file path for all songs
        //**************************************************
        downloaded_song = getFilePaths();  // count is not giving properly
        // song path received from getfilepaths are updated to songfilename
        setSongs();
        // then query it and update it in your local db
        helper.updateSongFileName(downloaded_song, songDetailsArrayList);

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        new insertSongDatabase().cancel(true);
   getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
            Intent intent1 = new Intent(LoadingGameActivity.this, GameActivity.class);
            intent1.putParcelableArrayListExtra("song_details", songDetailsArrayList);
            startActivity(intent1);
            finish();
    }
}


 public ArrayList<String> getFilePaths() {
    ArrayList<String> filePaths = new ArrayList<String>();
    String pathh = Environment.getExternalStorageDirectory().toString() + "/Allsongs/";
    File directory = new File(pathh);
    File[] listFiles = directory.listFiles();
    if (listFiles != null) {
        int count = listFiles.length;
        Log.d("count12", String.valueOf(count));
        // get the count of all the files in the folder
        // update onl the ones that are given for particular playlist
        for (int i = 0; i < listFiles.length; i++) {
            String filePath = listFiles[i].getPath();
            Log.d("filepath1", filePath);
            for (SongDetails sdf : songDetailsArrayList
            ) {
                String songmade = pathh + sdf.getTitle() + "_" + sdf.getId() + ".mp3";
                if (songmade.equalsIgnoreCase(filePath)) {
                    if (IsSupportedFile(filePath)) {
                        filePaths.add(filePath);
                    }
                }
            }
        }
    }
    return filePaths;
}


  private void setSongs() {
    try {
        if (downloaded_song != null) {
            for (int i = 0; i <= songDetailsArrayList.size() - 1; i++) { 
   songDetailsArrayList.get(i).setSong_file_name(downloaded_song.get(i));  
            }
        } else {
            Utilities.makeSnackbar(text_playlistName, "FETCHING SONGS FAILED", "red");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
...