Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing data on SD Card in Android

Using the data-storage page in the docs, I've tried to store some data to the SD-Card. This is my code:

    // Path to write files to
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                  "/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
    String fname = "mytest.txt";

    // Current state of the external media
    String extState = Environment.getExternalStorageState();

    // External media can be written onto
    if (extState.equals(Environment.MEDIA_MOUNTED))
    {
        try {
            // Make sure the path exists
            boolean exists = (new File(path)).exists();  
            if (!exists){ new File(path).mkdirs(); }  

            // Open output stream
            FileOutputStream fOut = new FileOutputStream(path + fname);

            fOut.write("Test".getBytes());

            // Close output stream
            fOut.flush();
            fOut.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

When I create the new FileOutputStream I get a FileNotFound exception. I have also noticed that "mkdirs()" does not seem to create the directory.

Can anyone tell me what I'm doing wrong?

I'm testing on an AVD with a 2GB sd card and "hw.sdCard: yes", the File Explorer of DDMS in Eclipse tells me that the only directory on the sdcard is "LOST.DIR".

like image 457
BBoom Avatar asked May 24 '10 09:05

BBoom


People also ask

Can I move Android Data to SD card?

You can move or copy files to an SD card on your device. Files by Google works on Android version 5.0 and up. If you don't have the app, you can download it from the Play Store.

Can we store data in SD card?

If your Android device doesn't have enough internal memory to store all the apps you need, you can use the SD card as internal storage for your Android phone. A feature called Adoptable Storage allows the Android OS to format an external storage media as permanent internal storage.

Is it better to store on SD card or internal storage?

External memory is useful to extend your phone memory. However, for the better performance of your mobile device, it is better that you start off with device of larger internal storage.


2 Answers

Have you given your application permission to write to the SD Card?

You do this by adding the following to your AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
like image 152
Dave Webb Avatar answered Oct 21 '22 03:10

Dave Webb


Before reading or writing to SD card, don't forget to check the SD card is mounted or not?

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
like image 40
Shahul3D Avatar answered Oct 21 '22 05:10

Shahul3D