Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a directory on the internal storage upon installation of the Android application?

I want to have a single folder where I will put all the resources I'm going to need and I want it on the internal storage. Since I want this directory to be created only once, I found out that I should create it in the main activity of the application:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    File directory = context.getDir("mydir", Context.MODE_PRIVATE);
    Log.d("directory", directory.getAbsolutePath().toString());
} 

It seems ok as this is what I was able to find on the internet, however I am receiving loads of erros, I can get to the log for the directory path and the application doesn't start. Any idea why?

Also, if I work with internal storage every time when I run my application from Eclipse to my phone, does it automatically deletes the previous one together with its resources or I've to do that manually?

like image 315
Andrey Avatar asked Dec 12 '12 16:12

Andrey


People also ask

How do I create a folder in my internal storage?

With your document open, click File > Save As. Under Save As, select where you want to create your new folder. You might need to click Browse or Computer, and navigate to the location for your new folder. In the Save As dialog box that opens, click New Folder.

What is internal storage directory in Android?

Internal storage directories: These directories include both a dedicated location for storing persistent files, and another location for storing cache data. The system prevents other apps from accessing these locations, and on Android 10 (API level 29) and higher, these locations are encrypted.

Where is the directory on Android?

Head to Settings > Storage > Other and you'll have a full list of all the files and folders on your internal storage.


2 Answers

use getCacheDir(). It returns the absolute path to the application specific cache directory on the filesystem. Then you can create your directory

File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
like image 182
Blackbelt Avatar answered Sep 20 '22 18:09

Blackbelt


IF you would like to store on the external storage SD card instead, you need to have this

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

In your AndroidManifest.xml file

Also this for working with the storage:

File direct = new File(Environment.getExternalStorageDirectory()+"/folder");

if(!direct.exists()) {
     if(direct.mkdir()); //directory is created;
}
like image 37
Andy Davies Avatar answered Sep 20 '22 18:09

Andy Davies