Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Failed to ensure directory

I have been using "Environment.getExternalStorage()" to store and manage files. And there is no warning message from logcat with that method and works greatly fine.

But, My project needs to use method "Context.getExternalFilesDir(String type)" and there is a warning message

ContextImpl:Failed to ensure directory: /storage/external_SD/Android/data/(package name)/files

Fortunately that File object works fine(reading or write or making folder works, too).

But I want to know how to resolve that warning message. Do I miss something?

like image 778
iroiroys Avatar asked Oct 27 '15 08:10

iroiroys


2 Answers

You should know how the warning message comes up.

The getExternalFilesDir(String type) will call getExternalFilesDirs(String type) (notice the 's' at the final of the second method name).

The getExternalFilesDirs(String type) will find all dirs of the type, and calls ensureDirsExistOrFilter() at the end to ensure the directories exist.

If the dir can't be reached, it will print a warning!

Log.w(TAG, "Failed to ensure directory: " + dir);
dir = null;

So, if your device has two sdcard paths, it will produce two dirs. If one is not available, the warning will come up.

The conclusion is the warning does not need to be fixed.

like image 99
Hongji Song Avatar answered Oct 31 '22 21:10

Hongji Song


If you have code that is iterating files, calling this API many times, this warning can cause log pollution. To solve this (since the warning is actually benign) you can create a wrapper class that stores the result of calling getExternalFilesDir / getExternalCacheDir and subsequently returns the stored value instead of calling the API. In this way, at least you will only ever see this message once.

like image 23
Mr. Bungle Avatar answered Oct 31 '22 20:10

Mr. Bungle