Error while deleting a file from SD card - android

when i am deleting the file the code is running and showing me the toast of deleted file also but not deleting it from SD card.
code is below :
delete_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
fn = baseAppDir.getPath()+ File.separator + folderName + File.separator
+ folderName + "_" + Integer.toString(imgNo) + ".jpg";
FileName = folderName + "_" + Integer.toString(imgNo)
+ ".jpg";
if (FileName!=null)
{
deleteFile(FileName);
Toast.makeText(ImageCaptureActivity.this, "Deleted",
Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} else {
Toast.makeText(ImageCaptureActivity.this, "Not Deleted",
Toast.LENGTH_LONG).show();
}
}});

Have a look on following : Delete a file
Your can do like as below :
try {
deleteFile(FileName);
Toast.makeText(ImageCaptureActivity.this, "Deleted", Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}

Try this may be its help full too..
File dir = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
Log.e(TAG, " get path ..**... " + dir.getPath());
Log.e(TAG, " get Directory ..**... " + dir.isDirectory());
Log.e(TAG, " get Name ..**... " + dir.getName());
Log.e(TAG, " get strign ..**... " + dir.list());
if (dir.isDirectory()) {
String[] children = dir.list();
Log.e(TAG, " children .... ... " + children.length);
for (int i = 0; i < children.length; i++) {
Log.e(TAG, "Delete old Image ...");
new File(dir, children[i]).delete();
}
}
this is code for delete multiple image from SD card.

replace
if (FileName!=null) {
deleteFile(FileName);
Toast.makeText(ImageCaptureActivity.this, "Deleted",
Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} else {
Toast.makeText(ImageCaptureActivity.this, "Not Deleted",
Toast.LENGTH_LONG).show();
}
with
File file = new File(FileName);
if (file.delete()){
Toast.makeText(ImageCaptureActivity.this, "Deleted",
Toast.LENGTH_LONG).show();
image1.setVisibility(View.GONE);
} else {
Toast.makeText(ImageCaptureActivity.this, "Not Deleted",
Toast.LENGTH_LONG).show();
}

Related

Android : Not able to create directory in external sdcard in lollipop lenovo

I am tring to create directory in External sdcard, I tested my code in MI (Android M), Samsung and in lenovo (Android L). Below code works fine in all devices except in lollipop.
private void crateDirectory() {
Log.d(TAG, "inside crateDirectory() ");
try {
String extPath = "";
String base = "/storage/sdcard1/"; //lenovo
// String base="/storage/9F44-E930/"; // for xiaomi
File baseFile = new File(base);
Log.d(TAG, "baseFile.exists() >>" + baseFile.exists()); // resulting TRUE
String path = "Android/data/package name/files/";
extPath = base + path;
Log.d(TAG, "exPath >>" + extPath);
File myFile = new File(Environment.DIRECTORY_DOWNLOADS + "/MY Download");
Log.d(TAG, "myFile >>" + myFile.getAbsolutePath());
File outputFile = new File(extPath, "" + myFile.getAbsolutePath());
if (!outputFile.exists()) {
Log.d(TAG, "Creating outputFile ....");
outputFile.mkdirs();
}
Log.d(TAG, "outputFile.exists() >>" + outputFile.exists() + "\n outputFile >>" + outputFile.getAbsolutePath());
} catch (Exception e) {
Log.d(TAG, "Exception >>" + Log.getStackTraceString(e));
}
Log.d(TAG, "end of crateDirectory() ");
}

Reading files from encrypted OBB file

I created an encrypted OBB file from the JOBB tool and I am trying to access the files inside of it, there are some images "image1.jpg, image2.jpg" etc. So far I am able to successfully mount it with:
public void mountExpansion() {
final StorageManager storageManager = (StorageManager) this.getSystemService(Context.STORAGE_SERVICE);
String packageName = "com.nick.app";
String filePath = Environment.getExternalStorageDirectory()
+ "/Android/obb/" + packageName + "/" + "main."
+ getString(R.string.apk_expansion_version) + "." + packageName + ".obb";
final File mainFile = new File(filePath);
if (mainFile.exists()) {
Log.d("STORAGE", "FILE: " + filePath + " Exists");
} else {
Log.d("STORAGE", "FILE: " + filePath + " DOESNT EXIST");
}
String key = "123456";
if (!storageManager.isObbMounted(mainFile.getAbsolutePath())) {
if (mainFile.exists()) {
if(storageManager.mountObb(mainFile.getAbsolutePath(), key,
new OnObbStateChangeListener() {
#Override
public void onObbStateChange(String path, int state) {
super.onObbStateChange(path, state);
Log.d("PATH = ",path);
Log.d("STATE = ", state+"");
expansionFilePath = storageManager.getMountedObbPath(path);
if (state == OnObbStateChangeListener.MOUNTED) {
expansionFilePath = storageManager
.getMountedObbPath(path);
Log.d("STORAGE","-->MOUNTED");
Log.d("NICK","length()"+mainFile.length());
Log.d("NICK","getAbsolutePath()"+mainFile.getAbsolutePath());
Log.d("NICK","isDirectory()"+mainFile.isDirectory());
}
else {
Log.d("##", "Path: " + path + "; state: " + state);
}
}
}))
{
Log.d("STORAGE_MNT","SUCCESSFULLY QUEUED");
}
else
{
Log.d("STORAGE_MNT","FAILED");
}
} else {
Log.d("STORAGE", "Patch file not found");
}
}
}
And in my log I see the state "1" returned from OnObbStateChangeListener indicating the encrypted OBB file is successfully mounted. However at this point I am at a loss for how I can access the files inside of it and make use of them. For example load them into an ImageView etc. Any suggestions for what I am missing here?
storageManager.mountObb(main.getPath(), null, new OnObbStateChangeListener() {
#Override
public void onObbStateChange(String path, int state) {
super.onObbStateChange(path, state);
if (state == MOUNTED) {
Toast.makeText(MainActivity.this, "obb mounted", Toast.LENGTH_LONG).show();
File file = new File(storageManager.getMountedObbPath(path));
} else
Toast.makeText(MainActivity.this, "mount fail :" + path, Toast.LENGTH_LONG).show();
}
});
The file object is directory to all your files in obb.
To access those you may call listFiles() on it.

Failed in creating a directory

I'm having problems with regards to creating a directory from an external storage, here is the method that I'm using.
public String createDir(String npath,String ndir,String file)
{
String[] paths = new String[] { npath, npath + ndir };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return "ERROR: Creation of directory " + path + " on sdcard failed";
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(npath + ndir + file)).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(ndir + file);
OutputStream out = new FileOutputStream(npath + ndir + file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copied " + file);
return "Copied " + file;
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + file + e.toString());
return "Unable to copy " + file + e.toString();
}
}
else
return "Error!";
}
But I always get "ERROR: Creation of directory " + path + " on sdcard failed". Not to mention this is already installed in an android device. I tried looking for the directory of my application, but it is nowhere to be found, that supposedly, should be creating its folder automatically after the installation of my APK. Anyone who can resolve this?

How to find external storage directory

static final String FILE_LOG = "log.txt";
private void SaveLogToExternalStorage()
{
String s = tv_log.getText().toString();
File file;
FileOutputStream fos = null;
try
{
file = new File(getExternalFilesDir(null), FILE_LOG);
fos = new FileOutputStream(file);
}
catch(FileNotFoundException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
try
{
fos.write(s.getBytes());
fos.close();
}
catch(IOException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
String savedFile = Environment.getExternalStorageDirectory() + "/" + FILE_LOG;
Toast.makeText(this, "Log is saved to " + savedFile, Toast.LENGTH_SHORT).show();
}
This function prints Log is saved to mnt/sdcard/log.txt Actually the file is saved to mnt/sdcard/Android/data/package.name/files/log.txt How can I find this directory programmatically to show correct message?
Solved by using file.getAbsolutePath()
Just change following line.
String savedFile1 = Environment.getExternalStorageDirectory() + getFileStreamPath(FILE_LOG).toString();
Toast.makeText(this, "Log is saved to " + savedFile1, Toast.LENGTH_LONG).show();
Log.d("File", savedFile1);
This will gives output like: /mnt/sdcard/data/data/com.android.experimentalproject/files/log.txt
And as per Alex Farber..
String savedFile = file.getAbsolutePath().toString();
Toast.makeText(this, "Log is saved to " + savedFile, Toast.LENGTH_SHORT).show();
Log.e("PATH", savedFile1);
Output: /mnt/sdcard/Android/data/com.android.experimentalproject/files/log.txt
He is spot on...
Hope this will help you.
Thanks..

Create log file on SendSms and Receive SMS

I am working on an Android version 2.3.3 application which depends on SMS for SMS dealing. I have written two classes SendSMS and ReceiveSMS. I want to create a log file which logs each SMS that it is sent or received. For creating log file I have written code but does not work.
Following is my code,
public void WriteOnLog()
{
File exportDir = Environment.getExternalStorageDirectory();
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" msg";
}
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
txt = dt + " |" +" Send " + "| " + phoneNumber + " | " + message.toUpperCase();
out.write(txt + "\n");
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
I have used the OutputStreamWriter (instead of FileWriter) Approach. I have it working in my dev environment and tested on device (android 2.3.6). try this out:
try {
File directory;
if(isSDCard){
directory = new File(Environment.getExternalStorageDirectory().toString()+"/"+folderNameOrPath+"/");
}
else{
directory = new File(folderNameOrPath);
}
boolean fileReturnVal = directory.mkdirs();
if(fileReturnVal){
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder Created successfully");
}
else{
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder either already exists or creation failed");
}
File file = new File(directory, fileNameWithExtention);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//Write the string to the file
osw.write(text);
osw.flush();
osw.close();
//file saved
Toast.makeText(context, "Text saved in SD Card", Toast.LENGTH_SHORT).show();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: File Not Found ERROR: " + e.toString());
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: IOException ERROR: " + e.toString());
return false;
} catch (Exception e) {
Log.e("Storage", "Write in SD Card: ERROR: " + e.toString());
return false;
}
you can set append mode for you task. The variables isSDCard, folderName, fileNameWithExtn. etc. are method level variables. I am passing those as parameters.

Categories

Resources