shadyinside
shadyinside

Reputation: 630

Creating internal app directory

I am trying to create a app specific directory (Internal) to store some images.I have tried many SO answers, but still nothing works. I've tried this from here.

File mydir = getApplicationContext.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;

But still this directory is not created - Android/data/com.packagename/....

But when I run this-

File mediaDir = new File("/sdcard/Android/data/com.packagename");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

This though creates the directory in the internal storage but is this the right way to do it ?

Upvotes: 1

Views: 2843

Answers (2)

Pararth
Pararth

Reputation: 8134

Internal Storage:
To find locations on internal storage for your app, use getFilesDir(), called on any Context (such as your Activity, to get a File object.

There's getDir,
http://developer.android.com/reference/android/content/Context.html#getDir(java.lang.String,int)

Please have a look at:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

For your purpose, instead of what you did with the path of sdCard, you can use

getExternalFilesDir

http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

It returns the path to files folder inside Android/data/data/your_package/ on your SD card. It is used to store any required files for your app (e.g. images downloaded from web or cache files). Once the app is uninstalled, any data stored in this folder is gone too.
Also, Starting in KITKAT, no permissions are required to read or write to the returned path; it's always accessible to the calling app. This only applies to paths generated for package name of the calling application. To access paths belonging to other packages, WRITE_EXTERNAL_STORAGE and/or READ_EXTERNAL_STORAGE are required.

Can check more:
http://www.mysamplecode.com/2012/06/android-internal-external-storage.html

http://www.vogella.com/code/ApiDemos/src/com/example/android/apis/content/ExternalStorage.html

For API 8 and above that would work fine.

In case you want to a similar implementation for API 7 and below also,

getExternalStorageDirectory()

It returns the root path to your SD card (e.g mnt/sdcard/). If you save data on this path and uninstall the app, that data won't be lost.

Upvotes: 0

marcone
marcone

Reputation: 329

getApplicationContext().getDir() will not create a folder named Android/data/com.packagename/. If you log/print the path for the returned File you will see it is "/data/data/<packagename>/app_mydir/". This is the way it should be for internal storage.

If you want to create a directory on the sd card (usually referred to as external storage, even when the /sdcard path resides in internal flash storage) then use Context.getExternalFilesDir(). This will create a folder like "/sdcard/Android/data/<packagename>/files/"

Upvotes: 3

Related Questions