Writing Text File to SD Card fails - android

I have a strange problem I've come across. My app can write a simple textfile to the SD Card and sometimes it works for some people but not for others and I have no idea why.
For some people, it force closes if they put some characters like ... in the File and such. I cannot seem to reproduce it as I've had no troubles but this is the code which handles the File writing. Can anyone think of something that may lead to problems or a better to way to do it?
public void generateNoteOnSD(String sFileName, String sBody)
{
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}

You can use this method to check de sdCard state. Change the toast dialog to you language:
** Care with MEDIA_MOUNTED_READ_ONLY. In no need write in the SDCard and i return true **
public static Boolean comprobarSDCard(Context mContext) {
String auxSDCardStatus = Environment.getExternalStorageState();
if (auxSDCardStatus.equals(Environment.MEDIA_MOUNTED))
return true;
else if (auxSDCardStatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
Toast.makeText(
mContext,
"Warning, the SDCard it's only in read mode.\nthis does not result in malfunction"
+ " of the read aplication", Toast.LENGTH_LONG)
.show();
return true;
} else if (auxSDCardStatus.equals(Environment.MEDIA_NOFS)) {
Toast.makeText(
mContext,
"Error, the SDCard can be used, it has not a corret format or "
+ "is not formated.", Toast.LENGTH_LONG)
.show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_REMOVED)) {
Toast.makeText(
mContext,
"Error, the SDCard is not found, to use the reader you need "
+ "insert a SDCard on the device.",
Toast.LENGTH_LONG).show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_SHARED)) {
Toast.makeText(
mContext,
"Error, the SDCard is not mounted beacuse is using "
+ "connected by USB. Plug out and try again.",
Toast.LENGTH_LONG).show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_UNMOUNTABLE)) {
Toast.makeText(
mContext,
"Error, the SDCard cant be mounted.\nThe may be happend when the SDCard is corrupted "
+ "or crashed.", Toast.LENGTH_LONG).show();
return false;
} else if (auxSDCardStatus.equals(Environment.MEDIA_UNMOUNTED)) {
Toast.makeText(
mContext,
"Error, the SDCArd is on the device but is not mounted."
+ "Mount it before use the app.",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}

Are you checking that the external storage is writeable? If not then try using...
Environment.getExternalStorageState()
This will tell you if the SD card is mounted and you can also check if it's writeable. That's all I can think of to suggest at this point.

I just found out that in my case, i was missing adding <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in Manifest file.
Cheers,
wahib

For all fellow newbies out there debugging on an actual device via USB: Don't forget to unplug the USB cable from your dev PC, like I did. When USB is connected the SD card is unavailable. Happy file writing...
This is not correct on all phones/ROM builds. CMod7 and MIUI ROMS both allow you to set whether the SD card is mounted or not when plugged into PC, depending on your settings the above may hold true. Best to check.

I usually use PrintWriter rather than FileWriter. I don't know if it would solve your issue but it's of a higher level so it may take care of more things than a simple FileWriter.

Related

creating folder not visible in file explorer

Hi i am creating folder in external storage.first i need to check that Sd card is present or not.In my mobile i dont have sd card.i am using redmi mobile.Below is my code.I dnt have sd card bt i am getting sd card is mounted.Then i checked my internal storage i cant found the folder what i created.i had tried so many codes,please help me.i also added read and write external permission.
my code is:`
String state;
state=Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
Toast.makeText(this, "Sd card found", Toast.LENGTH_SHORT).show();
File root=Environment.getExternalStorageDirectory();
File dir=new File(root.getAbsolutePath()+"/myappfile");
if(!dir.exists()){
dir.mkdir();
}
}
else {
Toast.makeText(this, "SD card not found", Toast.LENGTH_SHORT).show();
}`
Try this code -
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent)
{
// yes SD-card is present
}
else
{
// Sorry
}
Source - https://stackoverflow.com/a/7429264/1649353
And also check Environment.isExternalStorageRemovable()
Try someting like this
if(Environment.MEDIA_MOUNTED.equals(Environnement.getExternalStorageState()))
{
File f = new File(Environment.getExternalStorageDirectory(), "/myappfile");
if (!f.exists()) {
if.mkdirs();
}
}

writing to a file in android, couldn't locate file

so i have this code below in my MainActivity, after I call this method, it pop up Toast "file saved" but i could not locate this file to be sure it saves what i wanted to, anyone?
private void saveToFile(String data){
try {
outFile = new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath()+"/batteryLogFile.txt", true);
PrintWriter out = new PrintWriter(outFile);
out.println(data);
out.close();
//output = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/batteryLogFile.txt");
//output.write(data.getBytes());
//output.close();
Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
}catch(FileNotFoundException e){
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(java.io.IOException e){
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I've finally found the file, issue was about that I was debugging this app on my real device and while it was debugging, somehow app hasn't been saving my file. When I disconnect my device from computer and re-run application again, everything was good and file was located on my SD card.

Android FileWriter not working on Sony Ericsson Arc but works on another phone

The issue I am having could be a hardware-related. In any case I'm stumped.
I have written some code (that I took and modified from: Writing Text File to SD Card fails) I've put the code below. It works fine on my Sony Ericcson X8. However, on the Sony Ericsson Arc, I can't find the file when I look for it on the phone! I went line by line through the code and there are no failures. It's as if it's on the phone and I'm just blind. I can even see in the debugger that the value of gpxfile is:
/mnt/sdcard/MyCompany/MyLog
But when I use windows explorer to look for the file, I certainly don't see the directory MyCompany. Is there some setting on the phone that (silently) prevents writing to the SD Card?
Here is the code:
public static boolean generateNoteOnSD(String sFileName, String sBody) {
try {
String auxSDCardStatus = Environment.getExternalStorageState() ;
if (!auxSDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
Log.i(TAG, "generateNoteOnSD auxSDCardSTatus: " + auxSDCardStatus);
}
if (auxSDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
File root = new File(Environment.getExternalStorageDirectory(), "Dexcom");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile, true);
String currentTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
writer.append(currentTimeString + ", " + sBody +System.getProperty("line.separator") );
//writer.newLine();
writer.flush();
writer.close();
Log.d(TAG,"generateNoteOnSD: Saved to file: " + sBody);
return true;
} else {
return false;
}
} catch(IOException e) {
e.printStackTrace();
return false;
//importError = e.getMessage();
//iError();
}
}
In my case the problem was that I had the Xperia ARC attached to the laptop with a USB cable. Apparently, things don't work quite right if you do that. No problem with the X8, so I'm guessing that it's phone specific. Computer may be putting lock on the file thus preventing Android from updating file. Not sure why I don't get an error though.
Bottom line for future readers: Try disconnecting phone from computer.

checking if a directory is created or not, fails?

I'm trying to create a directory, and i'm checking whether it is created successfully or not but displaying a text on the screen, but nothing to be displayed.
Java code:
public void createDirectory() {
try {
String strDirectory = "test";
boolean success = ( new File(strDirectory)).mkdir();
if (success) {
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created", Toast.LENGTH_SHORT);
} else {
Toast.makeText(getApplicationContext(), "error occured", Toast.LENGTH_SHORT);
}
} catch (Exception e) {
Log.e("Error", "Error creating directory");
}
}
put .show() end of Both Toast....
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created",
Toast.LENGTH_SHORT).show();
Did you add uses-permission write external storage to your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I actually don't know where it's trying to create the directory since you are not qualifying the entire path. what are you trying to do?
If you are trying to create it on the SD card, do this,
File f = new File(Environment.getExternalStorageDirectory(), "myfile.txt");
http://developer.android.com/reference/android/os/Environment.html
Note that this file will be readable by all apps.
If you are trying to create a file that's private to the app, do this,
OutputStream os = context.openFileOutput("myfile.txt");
http://developer.android.com/reference/android/content/Context.html
Note that this method is reserved for small files as it uses the internal storage which is limited on many devices.
Finally, always print the stack trace,
Log.e("mytag", "some message", e);
9 times out of ten, this will point you directly to the problem.

android: writing to sdcard fails - why?

i have a problem with my code that is supposed to write some data string to my sdcard. i use a class to do this:
public class CVS {
private String path;
private String filename;
private File dir;
private File file;
private FileWriter fw;
public CVS() {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/traffic/";
filename = "data.cvs";
file = new File(path, filename);
createDir();
}
private void createDir() {
dir = new File(path);
if(!dir.exists()) {
if(file.mkdirs() == false) {
Log.d(Config.LOGTAG, "UHOH!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
else Log.d(Config.LOGTAG, "dir exists");
}
public void writeToFile(String data) {
try {
fw = new FileWriter(file);
fw.append(data); Log.d(Config.LOGTAG, "data saved to file...");
}
catch(Exception e) {
Log.d(Config.LOGTAG, "file: " + e.getMessage());
}
}
}
this results ALWAYS in an exeption being caught in writeToFile(), saying "permission denied". actually, i set permissions to WRITE_EXTERNAL_STORAGE in the manifest. so - what am i doing wrong!?
additional info: real device with sd card mounted. no emulator. android 2.2. if i create the dir myself, the problem wont go away :(
Either:
Your manifest is wrong, or
Your external storage is mounted on your development machine, or
Your manual concatenation of your directory is wrong
Your code is ok but still you can add a check for whether sdcard is inserted or not, if you run this code and sdcard is not inserted then it will throw an exception, good practice is that you should always catch the exeptions.
you can check sdcard by following code...
if (android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_MOUNTED))
{
//code or logic if sd card is inserted....
}
else
{
Log.e("Exception","SD Card not found!");
}
All of the answers are needed, but if it's a Samsung device, then you need to append "/external_sd/" to the path - because they decided they needed to dork with our minds and break the API:
"http://developer.samsung.com/forum/board/thread/view.do?boardName=GeneralB&messageId=162934&messageNumber=1381&startId=zzzzz~&searchType=TITLE&searchText=sdcard

Categories

Resources