1

I have written a simple code

if (context != null) 
    {
        File mydir = context.getDir("abc",0);
    }

As per my understanding, i can pass any random string as the first parameter. This will be name of the directory created. Also this code is already inside null check, so context cannot be null.

but this is giving NullPointerException

11-10 09:43:44.839: E/AndroidRuntime(11441): FATAL EXCEPTION: DOWNLOAD_THREAD
11-10 09:43:44.839: E/AndroidRuntime(11441): Process: com.samsung.samsunggearapps, PID: 11441
11-10 09:43:44.839: E/AndroidRuntime(11441): java.lang.NullPointerException
11-10 09:43:44.839: E/AndroidRuntime(11441):    at android.content.ContextWrapper.getDir(ContextWrapper.java:257)

EDIT: I tried using getApplicationContext(); . Even that is null.

11-10 11:31:17.919: E/AndroidRuntime(21038): java.lang.NullPointerException
11-10 11:31:17.919: E/AndroidRuntime(21038):    at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:114)
kenju
  • 5,866
  • 1
  • 41
  • 41
user4057066
  • 295
  • 3
  • 14

2 Answers2

1

I think you cant do that. You must specify where (1st param) and how (2nd param):

File mydir = context.getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);
Blaze Tama
  • 10,828
  • 13
  • 69
  • 129
  • the second parameter can be 0. Even if i give Context.MODE_PRIVATE, i get the same error. – user4057066 Nov 10 '14 at 04:32
  • @user4057066 Yes, what really annoying me is the 1st param..why you do that? – Blaze Tama Nov 10 '14 at 04:33
  • even if I change my code to if (context != null) { File mydir = context.getDir(Environment.DIRECTORY_PICTURES,Context.MODE_PRIVATE);}, i get the same error. It is not going in else also. which means context is not null. – user4057066 Nov 10 '14 at 04:37
  • @user4057066 Now...that is strange. I never got that problem, take a look here : http://stackoverflow.com/questions/8673567/why-do-i-get-a-nullpointerexception-on-getdir – Blaze Tama Nov 10 '14 at 04:49
0

getDir() enables you to create any file or directory in the internal memory, which is also accessible by other applications depending on the mode you create.

File dir = ctx.getDir("abc", Context.MODE_PRIVATE);
Thirumoorthy
  • 589
  • 2
  • 11
  • Can you explain why this is the right thing to do? Code dumping without any explanation is usually discouraged here on StackOverflow. – rayryeng Nov 10 '14 at 05:19