Where to store files for user in Android? - android

I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?

You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.

This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}

The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.

Related

Xamarin Android Sqlite Db browser

I have my first smartphone since one week and try make a App with Xamarin.
I use SQLite with EntityFrameworkCore to store data.
It is work fine, but to debug easier I want use a SQLite browser.
The database file path is 'data/data/{AppName}/Database.db'.
I debug from a physic device by USB, but when I explore the device with Windows Explorer I cannot find the SQLite DB file. The 'data/data' folder is not available. Then I can not use a SQLite browser to see the data.
In this post, the author use a Android emulator and can see 'data/data' folder :
https://blog.xamarin.com/building-android-apps-with-entity-framework/
But I prefer use a real device.
Have you a solution?
A solution from the MikeT, in development store the db file in available folder like this :
public static string DatabasePath
{
get
{
var dbFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
var fileName = "database.db";
var dbFullPath = Path.Combine(dbFolder, fileName);
return dbFullPath;
}
}
In production, copy the db file to a available folder.
One a real device you would, I believe, need to root the device to directly access the data.
However, what you could do is to copy the database file elsewhere e.g. to external storage. In following is the core process that I use:-
try {
FileInputStream fis = new FileInputStream(dbfile);
OutputStream backup = new FileOutputStream(backupfilename);
//byte[] buffer = new byte[32768];
int length;
while((length = fis.read(buffer)) > 0) {
backup.write(buffer, 0, length);
}
backup.flush();
backup.close();
fis.close();
catch (IOException e) {
e.printStackTrace();
confirmaction = false;
}
I use the following to get the pathname for backupfilename:-
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),subdirectory);
this.directory = dir.getPath();
I then add the actual filename (which is user input).
Note! I do checks to determine that EXTERNAL storage is mounted etc.
To get the database path i use:-
String dbfilename = this.getDatabasePath(
DBConstants.DATABASE_NAME).getPath();
dbfile = new File(dbfilename);
This is of course Java, but I'd assume that it could be converted/adapted to suit. The crux of the answer is to get the database file into a place from which you can access it.
Call the ExtractDb method from your activity
public void ExtractDB()
{
var szSqliteFilename = "databasename.db3";
var szSourcePath = new FileManager().GetLocalFilePath(szSqliteFilename);
var szDatabaseBackupPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/databasename_Backup.db3";
if (File.Exists(szSourcePath))
{
File.Copy(szSourcePath, szDatabaseBackupPath, true);
Toast.MakeText(this, "Copied", ToastLength.Short).Show();
}
}
Get path to the android device storage as shown below
public class FileManager
{
public string GetLocalFilePath(string filename)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
}
you need to add the android.permission.WRITE_EXTERNAL_STORAGE permission in your manifest file.

Creating a file unsing openFileOutput() which is visible to other applications

I'm using the openFileOutput() to create a new txt file. I need the file to be visible from other applications (as well as from a PC when the Android device is connected via USB. Ive tried using .setReadable(true); but this does not seem valid. Please advise how I should declare the file is visible / public.
try {
textIncoming.append("saving");
final String STORETEXT = "test.txt";
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.setReadable(true);
out.write("testing");
out.close();
}
catch (Throwable t) {
textIncoming.append("not saving");
}
Ive changed my program to use getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but for some reason it returns a path /storage/emulated/0/Documents, and I cant even find this folder on the device. Ive looked at the files on the android device using ES file explorer but cant find the folder or file I'm trying to create (Plus I want these in an documents folder on the SD card, so it seems that its not giving me a pointer to the SD card at all, and not creating the folder, and not creating the file. Following is my updated code, please advise
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt-" + n + ".xml";
textIncoming.append(root);
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Save it to sdcard if you want anyone to be able to read it.
This android documentation should tell you what you need to do.
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
openFileOutput() documentation says:
Open a private file
So the file that it creates won't be visible to other apps, unless you copy it to another directory that is visible. In that case, you have to save your data in what's called "external storage" which is shared with other apps. Use the code at this link.

android-where to store lots of images and how to move them while installing

I'm writing an android app that contains about 500 images .
there are somethings that make me worry, I don't want to use internet.
1-the application size will be very big , is there anyway to moving images to sd card while installing? some devices may don't have this amount of space on the phone .
2-should I make 3 images for hdpi , ldpi and mdpi ?
You can put you image in asset folder. If you want to transfer image from assets to SD Card then you can't do like this.
But you can do by one way. You put your image on server and at 1st time when you will open app you can download it and save it in SD Card and then access from there.
Yes, it will be big. No, you can't remove them from your package.
No, you can make only hdpi images. Android will scale them automatically (which may slow down a bit the app).
Suggestion - use internet. Since the user has internet to download your app, he can wait to download the resources on first start. Also it give you the ability to add/remove files via online configuration. Just imagine if you have to add 1 image and upload new version - this means that the user will have to download the same huge package again.
I had a similar requirement - include a bunch of images in the app, but in my case, the image had to be accessible by any user or app, not just the app that unpacked them. I stored them in the res/raw folder and copied them to user space on start up:
private void loadCopyResources() {
// copy resources to space any activity can use
String sourceName;
String resourceName;
String fileName;
int resource;
String typeName = sourceSink.Types.photo.toString();
for (sourceSink.Sources source: sourceSink.Sources.values() ){
for (int i = 0; i< photoFileCount; i++) {
sourceName = source.toString();
resourceName = sourceName + "_" + typeName + (i+1); // i.e. dropbox_photo2
fileName = resourceName + ".jpg"; // files requires extension
resource = getResources().getIdentifier(resourceName, "raw", "com.example.myapp");
createExternalStoragePublicFile(typeName,fileName, resource); // copy it over
}
}
}
void createExternalStoragePublicFile(String fType, String fname, int res ) {
// Create a path where we will place our picture in the user's
// public pictures directory. Note that you should be careful about
// what you place here, since the user often manages these files. For
// pictures and other media owned by the application, consider
// Context.getExternalMediaDir().
File path = null;
if (((fType.equals(sourceSink.Types.photo.toString())) || (fType.equals(sourceSink.Types.file.toString())) ) ){
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
}
if (fType.equals(sourceSink.Types.music.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MUSIC);
}
if (fType.equals(sourceSink.Types.video.toString())) {
path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
}
File file = new File(path, "/" + fname);
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(res);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
scanMedia(file);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
sourceSink, which I didn't include, is just a list of file names and file types I needed copied.

Android: Possible to write into /etc folder?

I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.

Android How to use and create temporary folder

I develop an app which collects some data from internet. Then save it to a temporary folder. To build this app I need to create and access a folder ( just for the purpose of app, not for the user). How can I do it?
this code is to create folder:
File direct = new File(Environment.getExternalStorageDirectory() + "/New Folder");
if(!direct.exists())
{
(direct.mkdir()) //directory is created;
}
try it may help you
File mFile;
onCreate()
mFile= new File(Environment.getExternalStorageDirectory()+"/temp/";
mFile.mkdir();
onDestroy();
mFile.delete();
try out this...
private void makeFolder(){
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + getString(R.string.folder_name));
boolean mainfolderexist = root.exists();
if (!mainfolderexist) {
try {
if (Environment.getExternalStorageDirectory().canWrite()) {
root.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
All The best
You should really check this other SO answer: https://stackoverflow.com/a/6485850/65716
Aside from the fact that you have to completely manage your use of the space, etc, caching on external storage requires more permission for your app.
See http://developer.android.com/reference/android/content/Context.html#getCacheDir()
"Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage."
For app use only, I would recommend to use Context.getDir() for retrieving the directory if the files is used by our app only and don`t want to be visible to users by file browsers.
// No need to check if exist, created automatically.
File tempRoot = context.getDir("temp", Context.MODE_PRIVATE);
// do something

Categories

Resources