checking if a directory is created or not, fails? - android

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.

Related

Writing file in Android always fails

I want to write text to file in Android. I tried writing to sdcard and public part of internal storage. I always got FileNotFound exception. I tried to get path by Environment.getExternalStorageDirectory().getAbsolutePath() and by Environment.getExternalStoragePublicDirectory(Enviroment.DIRECTORY_DCIM).getAbsolutePath()(it does not metter the file is not a picture, I suppose) and both returned: "storage/emulated/0" and "storage/emulated/0/DCMI" respectively. I have also tried direct path "/sdcard/MyFile/output.txt" and "mnt/sdcard/MyFile/output.txt". I have checked on most stackoverflow.com answears in such topic but I got only code similar to mine. (like from here)
Example of my code (I tried more variations):
try {
File dir = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyFile");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(("some text").getBytes());
stream.close();
toast = Toast.makeText(context, "Saving file successful.", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
toast = Toast.makeText(context, Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT);
//toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
toast.show();
}
You have to set the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission in your AndroidManifest.xml file.
If you run your app on Android 6.0 or higher you have to request this permission at runtime.
Request App Permissions
I am sorry to all you guys to waste your time. The problem was in permission setting. Here is the answear.

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.

Cannot write file in android internal storage

I am trying to create a text file in android internal storage but I am unable to do that. Can someone please tell me what am I doing wrong?
String append = "some data";
try {
FileOutputStream fileout=openFileOutput("fortify_profile.txt", Context.MODE_PRIVATE);
fileout.write(append.getBytes());
fileout.close();
Toast.makeText(getApplicationContext(), "Profile Created", Toast.LENGTH_LONG);
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not create Profile", Toast.LENGTH_LONG).show();
}
Every where I looked same method has been given to create a file on android internal storage but
mine is not working. Please help
Your code is correct and I hope that is creating file also. But you are not checking it in proper location. Go to data>data>your_package_name>files>fortify_profile.txt and that file should be there.

unusual error in Directory Creation

I have been trying to fix an issue since yesterday but no luck yet. I made a very simple android application to create directory and the application was working fine. The main source code is mentioned here.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//View vi = null;
File extDir= Environment.getExternalStorageDirectory();
File sddir = new File(extDir+"/test10");
if (sddir.mkdirs()) {
Toast toast = Toast.makeText(this,
"Directory successfully created!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else{
Log.e(TAG, "Create dir in sdcard failed");
Toast toast = Toast.makeText(this,
"Directory creation failed!",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
..... followed by remaining code
However, yesterday, when I integrated this code to my own application (a simple videolist that plays videos from the sd-card), the directory function, for whatever reasons, resulted in directory creation failed... I debugged the application but couldn't find exception errors or other errors in it. I don't know what could be wrong.. I am just wondering if there is any method to get the error statement behind directory creation failed. I mean if mkdirs failed, it could generate a small print statement about why it got failed??
any suggestions??
Please try with below function.
File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(),"test10");
if (!cacheDir.exists())
cacheDir.mkdirs();
and declare <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in manifest file.
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

Writing Text File to SD Card fails

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.

Categories

Resources