Search code examples
javaandroidstructurefile-storage

Guidance on Android file storage



I need to write an Android app that would download sounds from the internet for further use.
Where should i store these sounds? Is Sqlite an option? And what's the best way to load and play these files?
Thanks in advance.


Solution

  • I would recommend putting the files on the SD Card, if one exists. One thing to note, though, is that you should never hard code a path to the SD card. You would likely want to do something along the lines of:

    try {
            //Create handle to SD card drectory
            exportDirectory = new File(Environment.getExternalStorageDirectory() + "/MyDir");
    
            //Verify export path exists.  Create otherwise.
            if (exportDirectory.exists() == false) {
                if (exportDirectory.mkdirs() == false) {
    
                    //Directory structure could not be created.
                    //Message the user here
                    return false;
                }
            }
    
            //Create handle to SD card file.
            exportFile = new File(exportDirectory.getAbsolutePath() + "/whatever.mp3");
    
            //Do whatever here
    
    } catch(Exception e) {
            //Exception.  Message user and bail
            return false;
    }
    

    From there it is a simple matter of transferring whatever data you want into the file. An SQLite database would likely be overkill for this app, unless you plan on storing a LOT of extra information. There is also no guarantee, unless you store the files directly into the database as BLOBs, that the user won't mess with the file system between application runs. Though, in the case of MP3s and the like, track / artist type information can be stored directly into the file via ID3 tags instead of using a database.

    As for playing the files back, consult the Android documentation on their audio APIs. There is a ton of great information out there, definitely more than I can repeat here.