Android - problem with file-writing - android

I have some problems when writing an xml file onto my android device (GalaxyTab 10.1V). The code for writing the xml works fine. I can see the written file at the DDMS perspective in Eclipse and can save the file to any location on my computer. But when I open the same directory as opened in Eclipse with the windows explorer, it seems that the file does not exist! The file is still visible at the DDMS perspective, but windows explorer does not want (or can´t?) show me this file. After rebooting the tablet, the file is also shown at the windows explorer.
I have tried several things for solving this problem...
writing a .txt file --> same result
tried getExternalFilesDir() (as recommended since API Level 8) and getExternalStoragePublicDirectory() instead of getExternalStorageDirectory() --> same result
writing at USB-Debug mode, writing at "normal" USB mode, writing without USB connection --> same result
of course I have set the permission to read and write on the device at the manifest file
android.permission.WRITE_EXTERNAL_STORAGE
android.permission.READ_EXTERNAL_STORAGE
"show hidden files" is activated at the windows folder options
this is how my code looks like...
public boolean write(Result result) {
Serializer serial = new Persister();
File file = new File(Environment.getExternalStorageDirectory()
+ "/Test/result.xml");
try {
serial.write(result, file);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
I use the SimpleXML library for reading and writing my xml files but as mentioned before, the same problem occurs when writing a normal .txt file
Does anyone have an idea what the reason for this behaviour could be?

Related

Access an app's "private storage" folder (Internal Storage)

MinSDK=24, Target/Compile=27, Java 8
I'm creating a file inside my app's InternalStorage folder with this code:
File f = new File(context.getFilesDir(),"settings.txt");
if(!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
According to getContext().getFilesDir().getPath(); the folder is data/user/0/com.xxx.xxx/files (I'm aware this can change through updates,...) and if I run above code on Android Studio's simulator, the new "settings.txt" file can be accessed through Android Studio's "Device File Explorer".
This doesn't work on an actual phone though (Galaxy S7 with 7.0) because the user folder doesn't exist according to the "Device File Explorer".
I know that an app's InternalStorage can't be accessed by other apps, so Android's default File Manager probably won't display it but is there a way to access the folder via e.g. Win 10's explorer on an actual Android phone without rooting it? If so, how?

Exception in saving file on Android Marshmallow

Earlier, I was using KitKat on my rooted device, I was able to create temporary files easily. But now I have installed Marshmallow on my Nexus 5, the same code is giving me an exception.
The relevant code is:
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS);
// File repertoireStockage = Environment.getExternalStorageDirectory();
try {
file1 = File.createTempFile("RecordAudio",".mp4", storageDir);
}
catch (IOException e) {
Log.e("RecordAudio", "I/O Problem");
e.printStackTrace();
return;
}
Yes, I do have permissions outside the application tag in Manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Earlier, I used the commented line to get storage directory but now, both are not working. Any kind of help would be appreciated.
I have tried saving file after removing data cable, I still get the same exception.
The OS brings a number of new features and it also has a built-in file manager, which may go unnoticed by many users.
Many third-party file managers allow users to rename files, create new folders, cut files and more. However, Android 6.0 Marshmallow's on-board file manager does not allow such actions.
Be aware that the file paths they return will dynamically change when
the app is moved between internal and external storage devices. When
building file paths, it is strongly recommended that you always call
these APIs dynamically. Don’t use hardcoded file paths or persist
fully-qualified file paths that were built previously.
Link For reference
1) http://developer.android.com/about/versions/marshmallow/android-6.0.html
2) http://www.techtimes.com/articles/94044/20151012/android-6-0-marshmallow-has-a-built-in-file-manager-heres-how-to-access-it.htm

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!

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.

Writing to the internal private storage in 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.

Categories

Resources