Android Cache folder is created as file - android

I am using Disk Cache folder for storing image files. It works perfectly, but after anyone performs Clean Data from his/her device the cache folder turns into a file.
Here is the code for creating cache directory
File myDiskCacheDir=getDiskCacheDir(this,IMAGE_CACHE_DIR);
diskCache=new MyDiskCache(this,myDiskCacheDir);
public static File getDiskCacheDir(Context context, String uniqueName) {
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||(!isExternalStorageRemovable()))
{
cachePath=getExternalCacheDir(context).getPath();
}
else {
cachePath=context.getCacheDir().getPath();
}
new File(cachePath).mkdirs();
return new File(cachePath + File.separator + uniqueName);
}
public static File getExternalCacheDir(Context context) {
if (Utils.hasFroyo()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
File cacheDirFile=new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
cacheDirFile.mkdirs();
return cacheDirFile;
}
I am facing this problem in Android 4.2 and below only.

Use
new File(cachePath + "/").mkdirs();

Related

File.renameTo return false

I want to rename my png file. Image current path like this:
/storage/emulated/0/Android/data/sample.png
I want to save this image under app's file directory. I give write external storage permission on runtime.
File toFileDir = new File(getFilesDir() + "images");
if(toFileDir.exists()) {
File file = new File("/storage/emulated/0/Android/data/sample.png");
File toFile = new File(getFilesDir() + "images/sample-1.png");
file.renameTo(toFile);
}
renameTo returns false. But I couldn't understand the reason.
Internal and external memory is two different file systems. Therefore renameTo() fails.
You will have to copy the file and delete the original
Original answer
You can try the following method:
private void moveFile(File src, File targetDirectory) throws IOException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!src.renameTo(new File(targetDirectory, src.getName()))) {
// If rename fails we must do a true deep copy instead.
Path sourcePath = src.toPath();
Path targetDirPath = targetDirectory.toPath();
try {
Files.move(sourcePath, targetDirPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
throw new IOException("Failed to move " + src + " to " + targetDirectory + " - " + ex.getMessage());
}
}
} else {
if (src.exists()) {
boolean renamed = src.renameTo(targetDirectory);
Log.d("TAG", "renamed: " + renamed);
}
}
}

Including files in building apk application in Unity

How to add files and folders to the apk file when building it in unity.
What I need is to have some files and a folder to be present in the parent directory of the application ( android/data/com.company.product/files) after installing it on Android.
This is my code for copying files from streaming assets into android persist path:
using System.IO;
using UnityEngine;
public static class FileManager
{
public static string RereadFile(string fileName)
{ //copies and unpacks file from apk to persistentDataPath where it can be accessed
string destinationPath = Path.Combine(Application.persistentDataPath, fileName);
#if UNITY_EDITOR
string sourcePath = Path.Combine(Application.streamingAssetsPath, fileName);
#else
string sourcePath = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
#endif
//UnityEngine.Debug.Log(string.Format("{0}-{1}-{2}-{3}", sourcePath, File.GetLastWriteTimeUtc(sourcePath), File.GetLastWriteTimeUtc(destinationPath)));
//copy whatsoever
//if DB does not exist in persistent data folder (folder "Documents" on iOS) or source DB is newer then copy it
//if (!File.Exists(destinationPath) || (File.GetLastWriteTimeUtc(sourcePath) > File.GetLastWriteTimeUtc(destinationPath)))
{
if (sourcePath.Contains("://"))
{
// Android
WWW www = new WWW(sourcePath);
while (!www.isDone) {; } // Wait for download to complete - not pretty at all but easy hack for now
if (string.IsNullOrEmpty(www.error))
{
File.WriteAllBytes(destinationPath, www.bytes);
}
else
{
Debug.Log("ERROR: the file DB named " + fileName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
else
{
// Mac, Windows, Iphone
//validate the existens of the DB in the original folder (folder "streamingAssets")
if (File.Exists(sourcePath))
{
//copy file - alle systems except Android
File.Copy(sourcePath, destinationPath, true);
}
else
{
Debug.Log("ERROR: the file DB named " + fileName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
}
StreamReader reader = new StreamReader(destinationPath);
var jsonString = reader.ReadToEnd();
reader.Close();
return jsonString;
}
}
I hope it helps.

Android incompeted download file

I try to download audio from a URL. I use following sample download manager code from Github https://github.com/folee/Download_Mgr
My problem is If i cancel download, Incomplete mp3 file still there in SDcard. How can i remove Incomplete mp3 files?
#Override
public void onClick(View v) {
Intent downloadIntent = new Intent(DownloadValues.Actions.DOWNLOAD_SERVICE_ACTION);
switch (v.getId()) {
case R.id.btn_continue:
// mDownloadManager.continueTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.CONTINUE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
mViewHolder.continueButton.setVisibility(View.GONE);
mViewHolder.pauseButton.setVisibility(View.VISIBLE);
break;
case R.id.btn_pause:
// mDownloadManager.pauseTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.PAUSE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
mViewHolder.continueButton.setVisibility(View.VISIBLE);
mViewHolder.pauseButton.setVisibility(View.GONE);
break;
case R.id.btn_delete:
// mDownloadManager.deleteTask(mPosition);
downloadIntent.putExtra(DownloadValues.TYPE, DownloadValues.Types.DELETE);
downloadIntent.putExtra(DownloadValues.URL, url);
mContext.startService(downloadIntent);
removeItem(url);
break;
}
}
my file bath :
public class ConfigUtils {
public static void InitPath(Context ctx) {
File temFile = Environment.getExternalStorageDirectory();
if (temFile != null && temFile.canWrite() && Util.getAvailableExternalMemorySize() > 0) {
IMG_PATH = Environment.getExternalStorageDirectory().getPath() + "/DL_Mgr/Image/";
FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/DL_Mgr/Downloads/";
}
else {
IMG_PATH = ctx.getFilesDir() + "/Image/";
FILE_PATH = ctx.getFilesDir() + File.separator;
}
new File(IMG_PATH).mkdirs();
new File(FILE_PATH).mkdirs();
Log.i(TAG, "IMG_PATH-->" + IMG_PATH + "\n FILEPATH-->" + FILE_PATH);
}
}
I use this code for delete temp files but not work
case R.id.btn_delete:
File tempFile = new File(ConfigUtils.FILE_PATH + "filename".toString());
if(tempFile.exists()) {
tempFile.delete();
}
But it not work
EDIT:
WORKING CODE: (If download mp3 temp file remane like : "sample.mp3.download"
so ichanged code like this it work fine
File tempFile = new File(ConfigUtils.FILE_PATH + filename +".download".toString());
if(tempFile.exists()) {
tempFile.delete();
}
Before downloading starts. You must know where you are saving the file. So probably a absolute path or Uri pointing to a file in sdcard
that you are giving to Download manager to store your file at.
Incase of cancel. create a file object from that uri or absolute path and call delete on file object if exists.
Something like this
File tempFile = new File(uri.toString());
if(tempFile.exists()) {
tempFile.delete();
}
This should be simple. Google it out

Where is my Excel file on Android saved?

I have this code which makes new Excel file.
The file is blank, it only creates a sheet.
Code goes like this
public void onClick(View v) {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Havaji");
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("Hi there");
try{
FileOutputStream output = new FileOutputStream("Test2.xls");
workbook.write(output);
output.close();
}
...
Where is that file saved ?
How to manage to save a file on the location on the mobile device that i want?
How to create a directory where all the files are gonna be stored?
Here are a few methods you'll find useful for your purposes:
Creates all the directories along the path provided:
public static boolean createPath(String path) {
File pathFile = new File(path);
if (!pathFile.exists()) {
boolean result = pathFile.mkdirs();
if (!result) {
Log.e(TAG, "Unable to create directory path: " +
path);
return false;
}
}
if (!pathFile.isDirectory()) {
return false;
}
return true;
}
Returns the root of the external storage directory:
public static String extDirectory() {
File file = Environment.getExternalStorageDirectory();
return file.getAbsolutePath();
}
Returns the path to the root of an application's external storage directory:
public static String externalMyAppDataRoot(Context context) {
return externalAppDataRoot() + File.separatorChar
+ context.getPackageName() + File.separatorChar + "data";
}
Returns the path to the root of the Android application data directory:
public static String externalAppDataRoot() {
return extDirectory() + File.separatorChar + "Android/data";
}
I'm guessing that is being stored in /data/app//files/Test2.xls, though i'm not completely sure
I would try to pass in an absolute file path. If you want the file to be in the sdcard, i would use the Context.getExternalFilesDir to get the root path of the sdcard.

file.mkdirs() not working

i want to write to a file in the sdcard of my phone.i used the below code to do this.
private CSVWriter _writer;
private File _directory;
public String _fileTestResult;
private String PATH_FILE_EXPORT = "/applications/foru/unittestframework/";
public ExportData(){
_writer=null;
_directory = new File(Environment.getExternalStorageDirectory () +PATH_FILE_EXPORT);
if(!_directory.exists())
_directory.mkdirs();
}
public void exportResult(String testcaseNum,String testcase,String status){
try {
if(_directory.exists()){
//do something
}
but mkdirs() is not working.so i could not excecute following code in the if condition.please help me.
note:i have given the permission in manifest file.
EDIT:
i am using this file write option for storing the result of automation testing using robotium.i have created a normal project and tried to create directory in sdcard.but the same code when i am using in this testproject it is not working.why like that?dont unit testing framework support this?
have you add the correct permission in your manifest ?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit : ok, i just read your note for permission.
If it's help you this is my sdcard cache code :
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
String evtDir = "";
if(evt > 0){
evtDir = File.separator + evt;
}
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Android"
+ File.separator
+ "data"
+ File.separator
+ Application.getApplicationPackageName()
+ File.separator + "cache"
+ evtDir);
}else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
Try below code
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
imagefolder = new File(root,
mycontext.getString(R.string.app_name));
imagefolder.mkdirs();
}
} catch (Exception e) {
Log.e("DEBUG", "Could not write file " + e.getMessage());
}
Try with:
if(!_directory.exists())
_directory.mkdir();
Also check this - Creating a directory in /sdcard fails

Categories

Resources