0

I understood that getDir will create a directory if it doesnt exist yet. But I'm crashing on:

File dir= getDir(file,Context.MODE_PRIVATE);

file is of type String. logcat shows:

12-29 21:56:09.456: ERROR/AndroidRuntime(631): java.lang.NullPointerException
12-29 21:56:09.456: ERROR/AndroidRuntime(631):     at android.content.ContextWrapper.getDir(ContextWrapper.java:198)

Here's the code:

public class ReportHome extends Application{
public ReportHome(String message, String file){
    …some code…
    inf(tosend,file);
}
public void inf(String c, String file){
    File dir= getDir(file,Context.MODE_PRIVATE);

btw: what is the trick to format more than one line of logcat correctly?

michaelsmith
  • 1,011
  • 1
  • 16
  • 35

3 Answers3

4

Are you sure that the file argument isn't null?

If it's not, then the other possibility is that you're not running this in a sane environment.

Looking at the source code for getDir(), the only other possibility is that mBase (a private variable that holds the current Context) is null. I'm not quite sure how that would happen without seeing the rest of your code.

Trevor Johns
  • 15,682
  • 3
  • 55
  • 54
  • I expanded the answer a bit then. Is there some reason there wouldn't be a valid Context based on where this is? (Is this inside of an Activity, or somewhere else?) – Trevor Johns Dec 29 '11 at 21:42
1

Do not implement a constructor on any component, including Application. Move this logic to onCreate(), after you have called super.onCreate().

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

The getDir() method in itself isn't very interesting, as it just delegates the call to its underlying Context object (as with about every call to the ContextWrapper).

@Override
public File getDir(String name, int mode) {
    return mBase.getDir(name, mode);
}

It's important to know where you're calling the method from. mBase is set when the constructor of ContextWrapper is called or with attachBaseContext(). If you're certain that file isn't null, it appears as if neither of the the former to paths have been taken. Can you verify that the context you're working on isn't actually null by printing/debugging the returned result for getBaseContext()?

MH.
  • 45,303
  • 10
  • 103
  • 116
  • it's the context. I added Context to the constructor and use it for doing getDir and things are working fine now. Thank you! – michaelsmith Dec 29 '11 at 21:57
  • You're welcome. I noticed only after posting that Trevor editted his original answer to basically include what I was saying, sorry 'bout that. – MH. Dec 29 '11 at 22:01