Android: save file to downloads that can be viewed later - android

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!

Related

Unity: Accessing .txt files located on Android device connected to PC

I was wondering if anyone could possibly help me or give some advice on how to access a text file that has been saved onto an Android phone which is connected to a PC using Unity? Basically I am trying to track a player's heart rate using an Android Wear watch (Huawei Watch 2) and then send that data over to my phone (Huawei P10) which is connected to my PC, where it can hopefully be read by Unity. So far I have been able to collect the heart rate data and send it over to my phone where it is saved into a text file in the external storage (in this case storage/emulated/0). My next step is to read the text file in Unity but I am unsure which is the correct way to do this and searching online has not provided any solid leads and I was hoping someone may be able to point me in the right direction. Apologies if this question is a bit vague and thank you in advance.
First i would get the path of that text file in my logcat
Log.e("PathOfFile",""+filePath);
after i get the path of the file i would go to device monitor in Android Studio, and with my phone connected to pc i will go to storage/emulated/0
Important Note: storage/emulated/0 is located into internal memory, so you are not able to see this text from your phone (if no root was made) , but you can see this file in debug mode from Android Studio
after that you can navigate to your text file
The reason that the file is stored at internal memory might be because you are creating it into internal memory like this
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
to save it in external storage you should do this
public File getPublicAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
check the official doc for more info here: https://developer.android.com/training/data-storage/files.html#java
happy coding

how to create a folder in sdcard programmatically that can be shown directly in windows and in the phone

I created an android application in which it creates a folder that stores data, but I want it to be shown right away in windows when the usb is connected. right now, it can only be seen after i restarted the mobile device or mount and unmounted the sdcard. or is there even a way to mount and unmount the device programmatically?
someone recommends me this snippet
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
but i can't seem to understand how to apply this code or if this is even applicable with my concern.
You need to launch a scan on the new files so that they can be seen from outside. See this answer
// initiate media scan and put the new things into the path array to
// make the scanner aware of the location and the files you want to see
MediaScannerConnection.scanFile(this, new String[] {path.toString()}, null, null);
PS: This question is a bit old but it is the first one I found when I got stuck... So, probably worth answering for the next ones !

Android - problem with file-writing

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?

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