Android file-creation fails - java

I use the following code to create a folder "mymir" and a file ".nomedia" (in the mymir-folder) on the sdcard of an android unit. However, somehow it fails with the exception that the folder the ".nomedia"-file is to be placed in dosn't exist. Here's the code:
private String EnsureRootDir() throws IOException
{
File sdcard = Environment.getExternalStorageDirectory();
File mymirFolder = new File(sdcard.getAbsolutePath() + "/mymir/");
if(!mymirFolder.exists())
{
File noMedia = new File(mymirFolder.getAbsolutePath() + "/.nomedia");
noMedia.mkdirs();
noMedia.createNewFile();
}
return mymirFolder.getAbsolutePath();
}

I SD really there?
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) == true
If targeting 1.6+, have you declared
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
?
The exact Exception could help.

Related

need help saving image files

I am trying to save signature pad image to file but my app doesn't seem to be creating the directory in storage/emulated/0
this is what I am using to create the folder...
String DIRECTORY = Environment.getExternalStorageDirectory().getPath() + "/Signature/";
String pic_name = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
String StoredPath = DIRECTORY + pic_name + ".png";
and this is what I am using to create the directory
file = new File(DIRECTORY);
if (!file.exists()) {
file.mkdir();
}
and finally, this is where the file is saved...
public void save(View v, String StoredPath) {
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if (bitmap == null) {
bitmap = Bitmap.createBitmap(canvasLL.getWidth(), canvasLL.getHeight(), Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(bitmap);
try {
// Output the file
FileOutputStream mFileOutStream = new FileOutputStream(StoredPath);
v.draw(canvas);
// Convert the output file to Image such as .png
bitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
Log.v("log_tag", e.toString());
}
}
Please note that this is not my own code...
(Basically a copy and paste from)
http://demonuts.com/android-capture-signature-using-canvas/
The pad works fine, I can write on it, but it won't save :(
When I send it to a Toast I can return the full directory and file name of Storage/emulated/0/Signature/20191101_a time stamp.png but it wont save on device.
Any ideas??
Declare the permissions in AndroidManifest.xml file, To grant external storage read write permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
For Android OS version > 6.0, you require run time permissions as well.
// Check whether this app has write external storage permission or not.
int permission = ContextCompat.checkSelfPermission(ExternalStorageActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
// If do not grant write external storage permission.
if(permission!= PackageManager.PERMISSION_GRANTED)
{
// Request user to grant write external storage permission.
ActivityCompat.requestPermissions(ExternalStorageActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE_PERMISSION);
}
Thank you all for the help... my problem was creating a drive to save to. I found my answer at https://www.quora.com/How-do-I-create-a-folder-in-internal-and-external-storage-programmatically-in-an-Android-app
I should be able to create and save the file now thanks

Android Studio Folder doesn´t get created

I'm trying to create a folder on my device and the result isn't as expected.
I do have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in AndroidManifest.xml.
My code:
public void saveOnDevice(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello");
boolean x = true;
if (!myDir.exists()) {
x = myDir.mkdirs();
}
if(x) {
System.out.println("Folder created " + root);
}
else{
System.out.println("Folder not created" + root);
}
}
Result:
Folder not created /storage/emulated/0
Expected:
Folder created /storage/emulated/0
I tried this on my Samsung Galaxy S8. I don't have a SD-Card inserted. I don't have the path /storage/emulated/0 on my device. Why isn't it working and how can I fix this problem?
You do have that folder /storage/emulated/0 on your device. You probably just can't see it due to the layer of abstraction when using Samsungs file browser.
You can verify that by using a more advanced file browser such as FX File Explorer (https://play.google.com/store/apps/details?id=nextapp.fx) and start looking up that path from "System /".
That root string won't help you.
Instead you want to do something like this:
// create folder "myDir" in internal storage as sub directory of /storage/emulated/0
File myDir = new File(Environment.getExternalStorageDirectory(), "myDir");
// create file
File myFile = new File(myDir, "song.mp3");
// get file stream
FileOutputStream fileStream = new FileOutputStream(myFile);
Then you can simply write your songs content to fileStream.
It's a bit confusing that Environment.getExternalStorageDirectory() actually gives you the internal storage location, but it is external to your apps directory which is something like Android/your.apps.packagename/.

How to check whether a file exists in (Internal/External storage) by using file name?

I have been working on a project where I will get a filename from API and have to check whether the file is present in the device and play it.
I am getting Screenshot.jpg as filename from API and under the same name a file is present in my storage.
But when I used the piece of code, I have been returned false. I have checked with other codes also.
public boolean isFilePresent(String fileName) {
String path = this.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
where am I going wrong? Any help would be greatly appreciated!
Probably, what you do wrong is using this.getFilesDir().
Instead, use Environment.getExternalStorageDirectory().toString() for example, it's all dependant on where your file is.
Like I said before, debug it yourself, print (or present a toast) with the 'expected' file path, then verify it doesn't exist
Try something like that :
public boolean isFilePresent(Context context, String fileName) {
File dirFiles = context.getFilesDir();
File[] filesArray = dirFiles.listFiles();
for (File file : filesArray) {
if (file.getName().equals(fileName)) {
return true;
}
}
return false;
}
Use Environment.getExternalStorageDirectory() this is how you get the files directory
then you will add your files path after it, so you should do something like this
if(!new File(Environment.getExternalStorageDirectory().toString()+"/myFolder/"+"myFile").exist())
{
// file is not exist
}
remember to check the runtime permission because it's a special permission

How to write file to sd-card? (Android) No errors, but nothing written

I'm new to developing android apps. And already overchallenged with my first project. My app should be able to save a list of EditText fields to a text file by clicking a "save"-Button.
But I got no success to write a file to my SD-card.
My code:
(function in MainActivity.java called by the button)
public void saveData(View view){
try{
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/myapp/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "datei.txt");
FileOutputStream os = new FileOutputStream(file);
String data = "some string";
os.write(data.getBytes());
os.flush();
os.close();
}
catch (IOException e){
Log.e("com.sarbot.FitLogAlpha", "Cant find Data.");
}
}
With Google I found another way:
public void saveData3(View view){
FileWriter fWriter;
File sdCardFile = new File(Environment.getExternalStorageDirectory() + "/datafile.txt");
Log.d("TAG", sdCardFile.getPath()); //<-- check the log to make sure the path is correct.
try{
fWriter = new FileWriter(sdCardFile, true);
fWriter.write("CONTENT CONTENT UND SO");
fWriter.flush();
fWriter.close();
}catch(Exception e){
e.printStackTrace();
}
}
In my manifest.xml I set the permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
And the function from developer guide returns me True -> SD-card is writable.
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
In the res/layout/activity_main.xml are some TextViews and EditText and a save button with android:onClick="saveData" argument. The function is called. The SD-card is writable. And no IO errors. But after pressing the button (without error) there is still no new file on my SD-card. I already tried to create the file manually and just append but nothing changed. I tried some other function with BufferedWriter too .. but no success.
I'm running my Sony Xperia E with USB-Debug mode. Unmount and mounted the SD-card on my PC but cant find the file. Maybe it is only visible for the phone? It doesn't exist? I don't know what to do because I get no errors. I need the content of this file on my computer for calculations.
:EDIT:
The problem was not in the code.. just in the place I looked up. The externalStorage -> sdCard seems to be the internal and the removable sdcard is the -> ext_card.
After this line,
File file = new File(dir, "datei.txt");
Add this code
if ( !file.exists() )
{
file.createNewFile(); // This line will create new blank line.
}
os.flush() is missing in your code. Add this snippet before os.close()

file.mkdirs() isn't working

Here's the code:
String folderPath = Environment.getExternalStorageDirectory() + "/AllAroundMe/Images";
File file = new File(folderPath);
if(!file.exists())
{
if(file.mkdirs());
Log.d("MyTag","Created folders succefully");
}
if(file.exists())
{
Log.d("MyTag", "folders exists: " + file.getAbsolutePath());
}
The second if never happens, and it should, because I make these dirs. What is wrong with my code?
BTW, everytime I run this program, it always goes in the first condition.
I think you should remove that semi-colon after that inner if: -
if(file.mkdirs()) {
Log.d("MyTag","Created folders succefully");
}
P.S: - That is why you should always use curly braces, even if you have only single statement if, so that you don't do such kind of mistakes.
Make sure that you have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in your android.manifest file.
Also, it would be better to construct your file object like this:
String folderPath = "AllAroundMe/Images";
File file = new File(Environment.getExternalStorageDirectory(), folderPath);

Categories

Resources