In my app After user clicks on a button ,the download manager starts to download a file from internet and saving it to the internal sd card using this code:
void startDownload()
{
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
download_req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(PersianReshape.reshape("Downloading"))
.setDescription(PersianReshape.reshape("currently downloading the file..."))
.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() , packageId + ".sqlite");
download_ID = mgr.enqueue(download_req);
}
After it is downloaded, I plan to check its existance everytime app runs with this code:
String DatabaseAddress =
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/ee.sqlite";
File file = new File(DatabaseAddress);
Log.d("PATH File: ", DatabaseAddress);
if (file.exists()){
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
Now when I run this code it returns "not found" message whereas the file is already there (I checked its existance using a file manager).
the device I test on is nexus 7 and path used in saving the download file is: /storage/emulated/0/ee.sqlite
ee.sqlite is the filename of downloaded file.
/storage/emulated/0/ is the default path returned by app
Permissions added to manifest for this code are:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Q: Why does file.exists() returns false when there is a file?
UPDATE:
WHEN I USE HARDCODE
File temp = new File("/sdcard/storage/emulated/0/", "ee.sqlite");
it works but when I use Environment.getExternalStorageDirectory().getPath() it doesn't.
Just initialize the File like this:
Updated:
This is just because of the separator missing there:
public static File getExternalStorageDirectory() {
return EXTERNAL_STORAGE_DIRECTORY;
}
and EXTERNAL_STORAGE_DIRECTORY is:
private static final File EXTERNAL_STORAGE_DIRECTORY
= getDirectory("EXTERNAL_STORAGE", "/sdcard");
static File getDirectory(String variableName, String defaultPath) {
String path = System.getenv(variableName);
return path == null ? new File(defaultPath) : new File(path);
}
String baseDir = EXTERNAL_STORAGE_DIRECTORY ;
String fileName = "ee.sqlite";
// Not sure if the / is on the path or not
File file = new File(baseDir + File.separator + fileName);
if (file.exists()) {
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
2nd Possibilites: As you are running it in emulator you have to make sure you have external storage enabled Like this:
In Eclipse, go to Window > Android SDK and AVD Manager. Select the appropriate AVD and then click Edit.
Make sure you have SD card support enabled. If you do not, click the "New" button and select the "SD Card Support" option.
Finally got it to work by changing the File object.
The solution is to change the File object to the following:
File file = new File(Environment.getExternalStorageDirectory().getPath() + dirName + File.separator , fileName);
where dirName is:
String dirName = Environment.getExternalStorageDirectory().getAbsolutePath();
and fileName is:
String fileName = "ee.sqlite";
so I could easily check whether file exist or not using my criteria function.
if (file.exists()){
Toast.makeText(getApplicationContext(), "found", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "not found", Toast.LENGTH_SHORT).show();
}
I like to thank #andru for helping me.
Related
I am trying to delete a file, but the file is not being deleted and my application is not throwing any errors. Below is my code:
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + "howmany.txt");
Uri uri = Uri.fromFile(file);
Boolean k = new File(uri.getPath()).delete();
if(k){
Toast.makeText(getApplicationContext(), "DELETED", Toast.LENGTH_SHORT).show();
}
I put this code right after checking for permissions, and from my understanding, .delete() returns true if the action is completed, so if it is I want to display a toast but the toast is never displayed. The strangest thing is that I am not getting any errors, but it just isn't working.
You don't need to create a Uri of the file object and then create a file object from that Uri. Just delete the file object and get the boolean result from that. You also don't need to create the k boolean. You can just test the delete itself:
final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + '/' + "howmany.txt");
if (file.delete())
Toast.makeText(getApplicationContext(), "DELETED", Toast.LENGTH_SHORT).show();
I wrote a small Android App to record audio and save this on the disk of the smartphone. Now I've got the problem that it's saved on the wrong location with the wrong name and I can't see why. (I'm relative new to Android programming)
public void startRecording(View view) {
File folder = new File(Environment.getExternalStorageDirectory() + "/" + R.string.app_name);
file_name = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + R.string.app_name;
if(!folder.exists()) {
boolean created = folder.mkdirs();
if(!created) { Log.i(LOG_TAG, "Could not create folder/s."); return; }
}
if(editText.getText() != null)
file_name += editText.getText() + ".3gp";
else
file_name += Calendar.getInstance().getTime() + ".3gp";
outputFile = new File(file_name);
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(file_name);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC);
Toast.makeText(CaptureActivity.this, R.string.toast_recording_start, Toast.LENGTH_SHORT).show();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
Toast.makeText(CaptureActivity.this, R.string.toast_recording_failed, Toast.LENGTH_LONG).show();
mediaRecorder = null;
}
}
The file should be saved in a folder called TrueCapture and the file itself should be called ggj.3gp .
But the file is saved on the internal storage under the name 2131099680ggj.3gp .
The next problem there is, I can only find the file with the explorer app from my smartphone. The PC can't find the file and no other app.
Some Details:
Android 6
File Name is wrong (2131099680ggj.3gp instead of ggj.3gp)
File is saved in internal storage in no specific folder instead of the external storage (SD card is in the smartphone) in a new folder called "TrueCapture"
No other app seems to know about this file except for the explorer app of the smartphone
R.string.app_name is the ID assigned to your resource in the R class, an int.
To get your String resource, you might wanna use the getString() method of Context.
Something like this should work:
String ext = ".3gp";
File folder = new File(Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_name));
if(!folder.exists()) {
folder.mkdirs();
}
file_name = folder.getAbsolutePath() + "/";
if(editText.getText().length() > 0) {
file_name += editText.getText().toString() + ext;
} else {
file_name += Calendar.getInstance().getTimeInMillis() + ext;
}
File outputFile = new File(file_name);
// ...
You also need to add the WRITE_EXTERNAL_STORAGE permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String dir = getFilesDir().getAbsolutePath();
File myFile = new File(dir+"/file.apk");
if (myFile.exists())
{
textView.setText("File exists.");
}
else
{
textView.setText("File does not exist.");
}
myFile.exists() is false. I do not know why. The file exists and it is located in the directory.
When I solve the problem, I'll try this:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(Uri.fromFile(myFile));
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Can somebody help? Why it does not see the file?
UPDATE:
It's really strange. If I use code:
if (myFile.exists())
{
textView.setText("it exists");
}
else
{
textView.setText(myFile.getAbsolutePath());
}
, it goes to 'else' and shows the path to the file which 'does not exist'.
Thanks to greenapps:
"Please click in Astro app left to the word Primary on the up arrow to see the real path. /Primary/ does not exist on an Android device. It's an Astro invention. And Astro shows external memory with Primary. And take a better file explorer like ES File Explorer to inform you about real paths"
I used direct path I found using Astro (modified string dir to '/sdcard/data/data/...").
Try using this code:
String dir = getFilesDir().getAbsolutePath();
boolean fileExists = (new File(dir + "/file.apk")).isFile();
if (fileExists)
{
// your file exists
}
else
{
// your file does not exist
}
If you construct the file with the 2-arg constructor, you can avoid adding a system-dependent path separator character. Like this:
File myFile = new File(dir, "file.apk");
I'm trying to create a folder that contains a subfolder inside. I wrote this code
File myFolder = new File(Environment.getExternalStorageDirectory().getPath().toString()
+ File.separator+"Folder/SubFolder"+File.separator);
myFolder.mkdirs();
Log.d("test", "creating the folders");
if (myFolder.exists()) {
Log.d("test", "folder created");
} else {
Log.d("test", "there is an error");
}
In my logcat I see the folder created and there is an error.
Obviously, I've added the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission. Where is the problem?
try removing the File.separator from the file path
File myFolder = new File(Environment.getExternalStorageDirectory().getPath().toString()+File.separator+"Folder/SubFolder");
then check if the path exists, if not create the folders.
if(!myFolder.exists())
myFolder.mkdirs();
use below code.
File myFolder = new File(Environment.getExternalStorageDirectory().getPath().toString()
+ File.separator + "Folder/SubFolder")
I am trying to check if a file exits on android sd card...so i do:
File f=new File(sdpath + "/" + DATABASE_NAME); //
if(!f.exits()) {
...create new file..
}
else {
...do something...
}
Every time this actually creates the directory or file on the sd card.
I know it doesnt exist, and when the new File is executed it is created and it shouldnt ?
I read all across google that new File doesnt create an actual file on the file system , but in my case it does...
Any alternatives to checking if a File/directory exits without using new File..
Edit 1: Well I'd just like to add (after 4 years :)) that this problem occurred only on two devices at the time i was writing the post and never again, one of them was HTC Desire C with android 4.0 and the other was some Huawei with android 2.x, cant remember anymore.
For some strange reason it turned out that new File created a directory every time...
instead of checking if (!f.exists()), I changed it to checking if (!f.isFile())
In that case i create a new file and it works good, the next time i run it the file is already on the sd card...
The way that worked was nearly like yours:
File f = new File(Environment.getExternalStorageDirectory(), "a directory");
if(!f.exists){
// do something
}
and to check whether a file exists or not is almost the same way:
File f = new File(Environment.getExternalStorageDirectory() + "/a directory/" + "a file");
if(!f.exists){
// do something
}
I hope it can help you out, because it didn't create a file or directory in my app. It just checked the path.
this may helps you, try like
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"myDirectory" //folder name
+File.separator
+"myFile.example"); //file name
if(file.exists()){
Toast.makeText(MainActivity.this, "Not Create ", 12).show();
}else{
file.mkdirs();
Toast.makeText(MainActivity.this, "Create ", 12).show();
}
}
Try this
File[] files = filedir.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
Toast.makeText(this, "directory", Toast.LENGTH_LONG).show();
} else {
if (file2.getName().equals(DATABASE_NAME)) {
Toast.makeText(this, "File found",Toast.LENGTH_LONG).show();
}
else{Toast.makeText(this, "File not found",Toast.LENGTH_LONG).show();
}
}
}