4

I'm having a problem getting files from my Android application's cache folder. This is what I'm trying to to but doesn't work:



    File cacheDir = getApplicationContext().getCacheDir();
    myFile = File.createTempFile("filename", ".mp3", cacheDir);

    ...
    // Here I have to code to initialize the file
    ...

    Log.i(LOG_TAG, "file.length = "+myFile.length());  // This logs correct info

    ...

    //File file = new File(myFile.getPath());
    //Log.i(LOG_TAG, "file.length() = "+file.length());  // This logs 0
    //Log.i(LOG_TAG, "file.name = "+file.getName());     // This is correct

    String fileURI = myFile.getPath();
    mediaPlayer.setDataSource(fileURI);
    mediaPlayer.prepare();             // This crashes


As you can see it seems the file doesn't contain anything. However I've tried to swap the two first lines with this piece of code and then it works.

    myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYFOLDER/filename.mp3");

I haven't found any way to set my mediaPlayer without the URI and when I try to get the file from the URI it seems to be a problem.

Do you have solution to how I can get the file from the cache directory?

Gjerdingen
  • 61
  • 1
  • 6

1 Answers1

-1

Ok, I managed to find a solution to this myself. First, I was able to "add content" to the file by changing createTempFile with this:

myFile = new File(getFilesDir(), "filename.mp3");

Unfortunately, seems you can't read files from this directory. You can read more about this here.

Therefore I found this post and I managed to solve it. Here is my final code:



     myFile = new File(getFilesDir(), "filename.mp3");

     ...

     Button playBtn = (Button) findViewById(R.id.button_play);
     playBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             play(myFile);
         }
     });

                    ...

        public void play(File f) {
            try {
                FileInputStream fis = new FileInputStream(f);
                mediaPlayer.setDataSource(fis.getFD());
                mediaPlayer.prepare();
                mediaPlayer.start();
                     ...


If you can't pass the file, then I can't help you. But please post solution when you find one.

Community
  • 1
  • 1
Gjerdingen
  • 61
  • 1
  • 6