Context - unable to create external files directory

1.4k Views Asked by At

I have a very strange problem with my app that appears when you start app on the Nexus 4.

I have following code in Application class:

public class MyApp extends Application {

@Override
public void onCreate() {
    super.onCreate();
    File dir = this.getExternalFilesDir(null);
    if (dir == null) {
        Log.e("App", "Problem with my dir!");
    }
}

In LogCat I saw message:

12-11 14:09:05.402 11739-11739/com.company.app W/ContextImpl: Unable to create external files directory
12-11 14:09:05.402 11739-11739/com.company.app E/App: Problem with my dir!

I already have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in my AndroidManifest.xml.

Also, this problem appears only when I re-install my application and don't reboot my device. If I reboot my Nexus, problem disappear.

What can be wrong in this simple code snippet?..

Thank you in advance for your reply.

2

There are 2 best solutions below

0
Pavel Strelchenko On BEST ANSWER

I've finally found cause of this strange behaviour.

In my application, after some initialization in Application class, I've started logging process like this:

String[] cmd = new String[] {
    "logcat", "-f", myFileNameFromExternalDir, "-v", "time"
};
Runtime.getRuntime().exec(cmd);

And I didn't destroy this process anywhere. That's why after re-intalling my app, Android unable to create external files dir or cache dir.

Summary:

  1. If you started some process, don't forget to destroy it, e.g:

    Process process = Runtime.getRuntime().exec(cmd); ... process.destroy();

  2. To check, if there are some unusual processes running on your device, you can use adb shell. For example:

In Windows cmd

adb shell

In Android shell

ps - it will list all processes on your device.

If you found something interesting, you can check, does this process belong to your application with lsof command:

lsof -p process_name | grep app_package

1
Dhaval Parmar On

you have to do this way

File dir = new File (this.getExternalFilesDir(null) + "/NewDirectory");  
if(!dir.exists()){
  f.mkdirs();// if there is no directory then create new
}

when use getExternalFilesDir() no need to add permission. its only needed when use getExternalStorageDirectory()