1

I'm trying to create a folder in android to store files concerning the user of the application.

I created an input output utility class for the use of the application.

For the moment i wrote this:

public void createFolder(){

    String dirPath =  new String();
    dirPath  =  getFilesDir().getAbsolutePath() + File.separator + "MyFolder";
    File folder = new File(dirPath);

    if(!folder.exists()) {
        folder.mkdir();
        Log.i("IO", ""+folder.exists());
    }

}

But when i try and call it from the main activity i get a null pointer exception: "java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference"

I know what is a null object reference but i don't understand which part of my code cause it.

  • Have a look at these: [enter link description here](https://stackoverflow.com/questions/8387252/cant-create-a-folder-in-external-storage-on-android-device) and that [enter link description here](https://stackoverflow.com/questions/17794974/create-folder-in-android). – D. B. Feb 27 '18 at 15:05
  • `NullPointerException` !!! Which context is used by your utility class? If there is no context your code should not compile. From which class is it derived? – greenapps Feb 27 '18 at 16:03
  • `folder.mkdir(); Log.i("IO", ""+folder.exists());`. That is nonsense. You shoul check the return value of mkdirs() before you tell that the folder is created. It might fail! Use mkdirs() instead of mkdir(). – greenapps Feb 27 '18 at 16:08
  • @greenapps i found the error, there was nos context, the code could still compile though. As for that line, i used it to check if the mkdir was created, i shouldn't have used the Log for that i guess. –  Feb 27 '18 at 16:23

1 Answers1

1

You should add permission in manifest.xml

<manifest ...>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  ...
</manifest>

Save Files on Device Storage

nhonnq
  • 184
  • 1
  • 9