Caching files using getCacheDir() - android

I wanted to download images that are downloaded from Dropbox and cache them for further use:
String cachePath = mContext.getCacheDir().getAbsolutePath() + entry.fileName();
File cacheFile = new File(cachePath);
//cacheFile.exists() returns true after 1st call
if(!cacheFile.exists()){
//If cache doesn't exist, download the file
mFos = new FileOutputStream(cachePath);
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_320x240,
ThumbFormat.JPEG, null);
}
mDrawable = Drawable.createFromPath(cachePath);
mImageView.setImageDrawable(mDrawable);
The mDrawable is null if the code doesn't enter the if block.
If I comment the if condition it works fine. But downloads the images every time.
Edit:
The above code is from how to test for a file in cache

Try this hope helps you
String path = context.getFilesDir().getAbsolutePath() + File.separator + entry.fileName();
File file = new File(path);
if (file.exists()) {
// File exists
} else {
// File does not exist
}

Related

Not Able to access expansion file content

I am using this code, but I am not able to access the expansion file content, i want to show gif image from expansion file, how can i do?
String packageName = getPackageName();
File root = Environment.getExternalStorageDirectory();
File expPath = new File(root.toString() + "/Android/obb/" + packageName);
try {
if (expPath.exists()) {
String strMainPath = expPath
+ File.separator
+ "main."
+ getPackageManager().getPackageInfo(
getPackageName(), 0).versionCode + "."
+ packageName + ".obb";
File f = new File(strMainPath);
if (f.exists()) {
Log.e("Path ", "=====>Exists");
} else {
Log.e("Path ", "=====> Not Exists");
}
ZipResourceFile zip = new ZipResourceFile(strMainPath);
InputStream iStream = zip.getInputStream("stage1_popup.gif");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeStream(iStream, null, option);
Glide.with(SampleDownloaderActivity.this).load(bitmap).into(image);
}
} catch (Exception e) {
}
http://prntscr.com/kp25qz
The Play APK expansions files library is completely open source, and you can see the sourcecode for ZipResourceFile here.
It looks like stage1_popup.gif is not in your obb file. To investigate it, why not use adb pull to get the file off your device and see what it actually contains. Or download the source code and attach to your IDE so you can step into the getInputStream() call and see where it is going wrong.
As mentioned in this answer, ZipResourceFile isn't able to deal with too much little files and neither is ZipFile. So try to divide your files in more directories.
Also, it's quite possible that there isn't any file with the name, stage1_popup.gif.
Alternatively, you can get all Entries via zipResourceFile.getAllEntries() and findout if the file exists.

Check If File Exists Before downloading the file

I am using download manager to download the file. The code for downloading the file is as follow.
private String DownloadData(Uri uri, View v, String textview) {
long downloadReference;
// Create request for android download manager
dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle(textview);
//Setting description of request
request.setDescription("Android Data download using DownloadManager.");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");
//Enqueue download and save into referenceId
downloadReference = dm.enqueue(request);
return null
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));
File file = new File(path);
if(file.exists()){
Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
} else if (!file.exists()) {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
String filepath = DownloadData(uri,view,filename);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to isFile:
File file = new File(path);
if (file.isFile()) {
Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

How to track the path of the file On some other Application

I have an requirement on my app that is , i have to track the file path and second i have to track the time of the file if that file is opened in some other application . I had researched everything but still not figuring out how to start . I know it's challenging and brain stroke implementation , but i need proper idea to move ahead .
I have achieved to create a file (file is of any kind .pdf/.docs etc)inside a folder . Now what i need if any one open the file in any other app then i have to first get the path of the file and secondly i have to track the time at what time the file is opened and closed . Here is the way i created the folder and dumped the file inside it . Now i have to read the file path and file opened in other app .
#Override
protected File doInBackground(FileMetadata... params) {
FileMetadata metadata = params[0];
//pathOfFileToSaved --> eg flight/ticket/vilash.pdf , flight/other/suman.docs
String folder_name = pathOfFileToSaved;
// File f = new File(Environment.getExternalStorageDirectory(), folder_main);
try {
File path = new File(Environment.getExternalStorageDirectory() + "/" + folder_name);
Log.e("pathoffile",""+path);
File file = new File(path, metadata.getName());
// Make sure the Downloads directory exists.
if (!path.exists()) {
if (!path.mkdirs()) {
mException = new RuntimeException("Unable to create directory: " + path);
}
} else if (!path.isDirectory()) {
mException = new IllegalStateException("Download path is not a directory: " + path);
return null;
}
// Download the file.
try (OutputStream outputStream = new FileOutputStream(file)) {
mDbxClient.files().download(metadata.getPathLower(), metadata.getRev())
.download(outputStream);
}
// Tell android about the file
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
mContext.sendBroadcast(intent);
return file;
} catch (DbxException | IOException e) {
mException = e;
}
return null;
}

how to create a folder in android External Storage Directory?

I cannot create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
System.out.println("Path : " +Path );
File FPath = new File(Path);
if (!FPath.exists()) {
if (!FPath.mkdir()) {
System.out.println("***Problem creating Image folder " +Path );
}
}
Do it like this :
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
If you wanna create another folder into that :
File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}
The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail. Also, mkdir and mkdirs returns true only if the directory was created. If the directory already exists they return false
getexternalstoragedirectory() is already deprecated. I got the solution it might be helpful for you. (it's a June 2021 solution)
Corresponding To incliding Api 30, Android 11 :
Now, use this commonDocumentDirPath for saving files.
Step: 1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step: 2
public static File commonDocumentDirPath(String FolderName){
File dir = null ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
}
return dir ;
}
The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:
Context.getExternalFilesDir().
Example:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
file.delete();
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
return file.exists();
}
I can create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String folder_main = "Images";
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
if (!outerFolder.exists()) {
inerDire.createNewFile();
}
outerFolder.mkdirs(); // This will create a Folder
inerDire.createNewFile(); // This will create File (For E.g .jpg
file)
we can Create Folder or Directory on External storage as :
String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
File f=new File(myfolder);
if(!f.exists())
if(!f.mkdir()){
Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}
and if we want to create Directory or folder on Internal Memory then we will do :
File folder = getFilesDir();
File f= new File(folder, "doc_download");
f.mkdir();
But make Sure you have given Write External Storage Permission.
And Remember that if you have no external drive then it choose by default to internal parent directory.
I'm Sure it will work .....enjoy code
If you are trying to create a folder inside your app directory in your storage.
Step 1 : Add Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2 : Add the following
private String createFolder(Context context, String folderName) {
//getting app directory
final File externalFileDir = context.getExternalFilesDir(null);
//creating new folder instance
File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);
if(!createdDir.exists()){
//making new directory if it doesn't exist already
createdDir.mkdir();
}
return finalDir.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt";
}
This is raw but should be enough to get you going
// create folder external located in Data/comexampl your app file
File folder = getExternalFilesDir("yourfolder");
//create folder Internal
File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");
if (!file.exists()) {
file.mkdirs();
Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();
}
Try adding
FPath.mkdirs();
(See http://developer.android.com/reference/java/io/File.html)
and then just save the file as needed to that path, Android OS will create all the directories needed.
You don't need to do the exists checks, just set that flag and save.
(Also see : How to create directory automatically on SD card
I found some another thing too :
I had the same problem recently, and i tryed abow solutions and they did not work...
i did this to solve my problem :
I added this permission to my project manifests file :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
(plus READ and WRITE permissions) and my app just worked correctly.
try {
String filename = "SampleFile.txt";
String filepath = "MyFileStorage";
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}

Delete file from internal storage

I'm trying to delete images stored in internal storage. I've come up with this so far:
File dir = getFilesDir();
File file = new File(dir, id+".jpg");
boolean deleted = file.delete();
And this is from another question, which was answered with:
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
My example always returns false. I can see the file fx 2930.jpg in DDMS in eclipse.
The getFilesDir() somehow didn't work.
Using a method, which returns the entire path and filename gave the desired result. Here is the code:
File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();
Have you tried Context.deleteFile() ?
Java
File file = new File(photoPath);
file.delete();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
new String[]{file.getName()},null);
Kotlin
val file = File(photoPath)
file.delete()
MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
arrayOf(file.getName()), null)
String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete();
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);
The code File dir = getFilesDir(); doesn't work because this is a request for a File object.
You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.
You can also use: file.getCanonicalFile().delete();
File file = new File(getFilePath(imageUri.getValue()));
boolean b = file.delete();
is not working in my case.
boolean b = file.delete(); // returns false
boolean b = file.getAbsolutePath.delete(); // returns false
always returns false.
The issue has been resolved by using the code below:
ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);
Have you tried getFilesDir().getAbsolutePath()?
Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.
> 2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created
2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it
solution1:
Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri
here I initialize Content resolver
and delete it with a passed parameter of that URI
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
solution2(my first solution-from head in this time I do know that ): content resolver exists...
String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);
File file = new File (path);
if (file != null) {
file.delete ();
}

Categories

Resources