Writing to the internal private storage in Android - android

I am trying to save some data from my app in a simple text file on the internal private storage area (app user preferences). I have read through many questions on here (StackOverflow) and tried the solutions suggested with no success. The simplest solution, it seems, would be the one suggested here: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal but I cannot get this to work on my test device. I have also tried to create the file using the methods available in the java.io.File with the appropriate methods. I have also tried to create the file on the SDCard with the same result, fail. I have tried many solutions listed in other answers, following the code and instructions suggested exactly and find the same result. I am beginning to feel that I am missing some important bit of code, or a setting flag somewhere, I have set the permission in the manifest file:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
To be clear, I am trying to write to the device's internal, private storage. It is a small file containing a name, phone number, and a couple of type int flags. What ever method I use, I either find that the file did not create (or change if I place the file manually on the SDCard), or I get a NullPointerException when I try to reference the file or file location:
private File fILE = new File("Mydata", main.FILENAME);
or
private File fILE = getDir("Mydata", 0);
I am running the code on a HTC Hero, updated with the latest service release from Sprint. Any help would be GREATLY appreciated, Thanks in advance!
-Steve
Update (2/2/11): Using a EVO (API 8) I still get a NullPointerException. The code generating the exception is below, any thoughts on why my app can't access the internal storage? I have this problem on three different physical devices using two API levels (API 7 and 8).
File newfile = new File(this.getFilesDir() + "/data/files/", "sample.txt");
UPDATE 2: 2/4/11 - I have found that I cannot see the file structure on the physical device (data directory) under any circumstance. Any one have any thoughts on this? The device is properly configured and can run app from eclipse or adb.
UPDATE 3: (2/9/11) - I think I may have found what the problem is here, but I am not sure about how to deal with it. I have figured out that the permissions on the /data/ directory on the physical devices are: drwxrwx--x. I am not sure why it is this way, maybe something to with Sprint? I have found this set this way on an HTC Hero, Samsung Epic (Galaxy S), and HTC EVO all on Sprint. The issue appears to be that DDMS and my app do not have r/w access to the directory. I need to figure out 2 things here, why it is like this and how to over come this issue in the wild. Again, any help here would be AWESOME!!
UPDATE 4: I think last February was a total blonde moment for me (see UPDATE 3). The test devices that I have are not ROOTed and hence no access (DUH!). After all the updates that he SGS and the EVO 4G have gone through, the result is still the same. I am still working this problem and will try and get back here with an update soon (hopefully less than a year next time).

Try changing the following line:
File newfile = new File(this.getFilesDir() + "/data/files/", "sample.txt");
to:
File newfile = new File(this.getFilesDir() + "/","sample.txt");

Not a direct answer to your question, but nevertheless: I noticed that you don't want to store tons of data in your file. Would it be a sufficient alternative to use the Shared Preferences instead?
And perhaps even more interesting: does the problem occur even when you write to the Shared Preferences file instead?
http://developer.android.com/guide/topics/data/data-storage.html#pref

A physical device's /data/ directory is only available to the root user. Since the only realistic way to get this access on a physical device is to root the device, DDMS file explorer cannot get into this branch of the directory tree.
As to why the app will not write there, likely the issue is in the fact that I have signed the app with debug keys (not a big *NIX expert, but what appears to be the case here from my personal research).

I was dealing with the same issue. Finally, I found that you really don't have to give all file paths in order to create a new file in internal storage. Just mention the file name and it will be created under your app's package folder at the device. I did exactly mentioned here
And it works perfectly. I would say avoid mentioning Full file path like : /data/... in order to create a file (you need write permissions to create a file in such a manner). Let Android framework do the job for creating a private file for your app.

The internal storage area is sort of private to the application so the user must have root access(rooted device) to create and load the files. If you have rooted device this is how to write a file to the internal storage:
// Create a file in the Internal Storage
String fileName = "MyFile";
String content = "hello world";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_APPEND);
outputStream.write(content.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
This should instantly create a file called MyFile with the content hello world. The internal storage directory is usually found in a special location specified by our app’s package name. In my case it is /data/data/[package name] and the files created are stored in a directory called files in that directory.

As #bianca says, you're better not using a file path. But instead, use only the filename to create a File. Something like this:
public static void saveTextToFile(Context context, String filename, String content) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And to get the file, you can use:
File file = new File(context.getFilesDir(), filename);
Read more: Saving Files.

Related

How to access to internal storage in Android

I want to store .docx files generated and modified through an Android app into the internal storage of android phones (all the same model of phone if that helps). I've got the loading of the template (located into the app) and the modifying of the fields working, but I'm blocked on how to save the files.
I am using docx4j which has a method for saving :
private void writeDocxToStream(WordprocessingMLPackage template,
String target) throws IOException, Docx4JException {
File f = new File(target);
template.save(f);
}
I have tried other more "manual" ways, but I always have the same problem :
what should be the input for the target directory?
It seems easy to do it for external storage, but concerning internal storage it's something else.
When I simply try to output a String in a test.txt then get the String in it back, with the classical BufferedReader, InputStreamReader, FileInputStream way of doing, I can't get this information whatsoever.
Information on this topic is super scattered, I've passed the afternoon reading about thousands of ways to achieve storage, but none corresponds to my problem.
I have set <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in my Manifest just to be sure but it doesn't change anything.
Moreover, and maybe it has to do with the issue, I can't access files (from device or from computer) on my testing device (a Samsung Galaxy 5S which can run the app), I seem to have quite all folders but not any files in them, apart from a few xml and txt files... (However, I still get nothing when doing the : write in EditText - store in File - save File in .txt - retrieve String - view String in textView).
This is super important as I have to retrieve the .docx files for further use, after them being created.
Thank you for your answers and let me know if I can provide any more information, I know my problem is quite unclear.
It seems easy to do it for external storage, but concerning internal storage it's something else.
To write to external storage, you use the two-parameter File constructor, where you provide a File object pointing to some root location on external storage, such as:
new File(getExternalFilesDir(null), target);
To write to internal storage, you use the two-parameter File constructor, where you provide a File object pointing to some root location on internal storage, such as:
new File(getFilesDir(), target);
You don't have to hold the permission android.permission.WRITE_EXTERNAL_STORAGE if you write your file to the app's private internal storage.
In your code, with the call
context.getDir("testfile", Context.MODE_WORLD_READABLE)).getPath().toString()+"/test.docx";
the file will write to the path
/data/data/com.yourpackage.name/app_testfile/test.docx
If the write operate successfully, you can read and retrieve the content of the file by using the path above.

Download file to phone with and without sdcard

I am novice programming android. I want to write a simple application that gets updated. For this I use a simple function that can download a file and show the current progress in a ProgressDialog and I store the file in the phone´s Sdcard like this:
output = new FileOutputStream("/sdcard/file_name.extension");
It would be some problem with the phones that not have SdCard? How can I solve it to work in any phone? Thank you.
There is an internal storage in Android devices, so you can utilize that.
I think, the default path to a private storage is "/data/data/package_name/files/file_name.extension".
Try this code:
FileOutputStream fOut = openFileOutput("file name here", MODE_WORLD_READABLE);
String str = "data";
fOut.write(str.getBytes());
fOut.close();
For further information, look this resources:
Section "Save a File on Internal Storage" of the official Android documentation;
http://www.tutorialspoint.com/android/android_internal_storage.htm
It's not only dealing with the problem phones without SDCard MMC, you'll find phones running without AOSP distribution. In fact, I saw some non-official Android mods (a lot of Chinese phones sold over the world) and you get no guarantee to find /sdcard filesystem in all of them.
If you got root permissions (rooted phone) you can program your app to read fstab and find out which storage filesystem is mounted at.
So, without knowing what Android distribution will run your app, I can tell you I found /data directory at all distros I saw.
Hope it helps.
Regards

Android: save file to downloads that can be viewed later

I have an app that needs to collect a bunch of data while connected to a stream. I need to save this data to a file that I can later pull off my device and analyze using a standard computer.
My code currently looks like:
private void saveData(byte[] data){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, "_Ascent_Test.txt");
try {
FileOutputStream stream = new FileOutputStream(file, true);
stream.write(data);
stream.close();
Log.i("saveData", "Data Saved");
} catch (IOException e) {
Log.e("SAVE DATA", "Could not write file " + e.getMessage());
}
}
It's correctly hitting the "Data Saved" log without any errors yet I cannot find the file anywhere in the devices internal storage when I browse it from my computer.
What am I missing?
Thanks.
Edit: I'm needed to run this on a Nexus 7
Files are not visible unless you make them explicitly available. See my blog post about the MediaScanner to read more about this.
It's the developer's job to take care of this and to make sure that all files, the user might want to access, are made available to the MediaScanner.
I wanted to do a very similar thing. Here's how I got it to work using your code EXACTLY.
After running my code to make the file(/storage/emulated/0/Download/_Ascent_Test.txt):
I downloaded the ES File Explorer.
In the "Fast Access" menu towards the bottom I turned "Show hidden files" ON.
Then, also in the "Fast Access" menu, go to local -> / Device.
Now you will be able to navigate to the /storage folder and all the way down to _Ascent_test.txt
From there you can open it and email it yourself.
Hope this helped!
So this seems to be a known issue with Nexus 4 and 7. I still don't have a workaround, but for now, using Astro File Manager to email myself will solve the immediate issue at hand.
Saving files on external storage on Nexus 7 and retrieving from PC
Nexus 4 not showing files via MTP
Always fun to waste several hours on something like this. Gah!

cant find files written to device

I am using
outStream = ctext.openFileOutput("demo.jpg",0);
outStream.write(data);
outStream.close();
If I use the emulator the file is written to the data hieracrchy on the simulated sdcard.
When I run on my Samsung 15500 I cant find where the data has been written to. If I click on MyFiles I can see the directories under Android with a data subdir but no sign of the file.
Am I missing something either in the method of writing the file or the way to find it on the device.
You should be able to find it via Context.getFileList();. The docs to Context.openFileOutput() say
Open a private file associated with this Context's application package for writing
So I guess there is no "guarantee" that you can have arbitrary access to it via file paths or urls or such.

where is /data/data/?

Beginner android question. Ok, I've successfully written files. E.g.
// get the file name
String filename = getResources().getString(R.string.filename);
FileOutputStream toWriteTo;
try {
toWriteTo = openFileOutput(filename, MODE_WORLD_READABLE);
// get the string to write
String toWrite = getResources().getString(R.string.contentstowrite);
toWriteTo.write(toWrite.getBytes());
toWriteTo.close();
...
}
catch (Exception ex) {
Toast.makeText(HelloFilesAppActivity.this, "fail!", Toast.LENGTH_SHORT).show();
}
}});
And I've proved that it is there by reading it and displaying contents, even using getFilesDir() and displaying all of the files in the folder.
Everything I read says that the files are in /data/data//files/
But I cannot find them. (I'm on Windows XP). My install didn't use default locations because my C:\ is pretty full. I looked in C:\Documents and Settings\Mike\.android\avd and in the project folder and in the place I installed the SDK: D:\Program Files\Android\android-sdk-windows. So where is /data/data/ ?
I read that I can use ADB to push and pull files back and forth, but I'm using Eclipse ADT and I'd prefer to use something other than command line. The book I'm using seems to imply that you can use Eclipse but then proceeds to give the command-line commands.
I found info about the Project Explorer in the DDMS, but I don't see the files I have written.
I've been working under the assumption that I might want to create a text file using some other means in Windows that I would read with my App. So if the answer is "why do you want to do this?", that's what I'm after. Eventually a DB probably too (that's in the next chapter :-) ).
Do I have to use the ADB command line?
thanks
Mike
http://developer.android.com/guide/topics/data/data-storage.html
The method your using to get the directory you read/write to:
openFileOutput()
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
You'll want to save the files your working with to the SD card.
Try this:
getExternalStoragePublicDirectory Example
It's on your phone. Your phone has its own file system. If you are using an emulator, then it's on the emulated file system, which is completely separate from yours. Your only way to access the phone's (or emulator's) file system is via ADB (unless we're talking about the SD card, which however does NOT host /data/data).
Side note - if your phone is not rooted, you won't have access to a lot of stuff on /data/data. I suppose that you are using an emulator, which is "rooted" in the sense that you have full access to its filesystem.

Categories

Resources