I am creating an app which uses sensor data and does experiments on it. I want to create a folder each time app is used and store all the data in a file in folder. How to create a new folder each time the app is used?
3 Answers
you will get all your answers on this previous post:
How to create directory automatically on SD card
the key to achieve it is the method:
mkdirs();
and don't forget to give your device the necessary permission within the Android.xml!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Write this when your main activity starts:
UUID uuid = UUID.randomUUID();
String randomUUIDString = uuid.toString();
String folderPath = "/sdcard/"+randomUUIDString;
File dataDirectory = new File(folderPath);
dataDirectory.mkdirs();
This will create a folder on your sdcard named "Data".
If you use higher level then API 4(1.6) then don't forget to add to the AndroidManifest.xml this line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

- 820
- 1
- 8
- 14
-
I want a new folder to be created each time the app is used. With what you said above creates only one folder, I want to create a new folder each time. How to do it? – Manasa Reddy Jul 17 '13 at 08:18
-
Then I would say, try to use UUID as folder name. It's a random generated ID which represents a 128-bit value. It has a very little chance that 2 UUID is the same :) One sec and I update my code. – Slenkra Jul 17 '13 at 08:29
Try SharedPreferences for creating the unique folders every time.
Maintain a Counter & increment it on every time in onCreate method. For the creation of the directories (in Sdcard) you can use the logic from the above answers.
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(context);
/* Get the value of the Counter */
counter = app_preferences.getInt("counter", 0);
/* Increment the counter and store it in the Shared Preferences */
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("sessionInitiatorCounter", ++counter);
editor.commit();
Please keep in mind that data stored using SharedPreferences will be cleared on clearing the App data (from the Settings).
If you don't want that then you can try creating the directory name based on the system time in millseconds.

- 1