I have an android app that I have just changed from using:
String path = Environment.getExternalStorageDirectory();
to:
String path = context.getExternalFilesDir(null);
Both of these memory locations are "external" ( I am testing on phones both with and without SD card slots).
My previous version worked perfectly with no errors, the new code occassionally throws a null pointer exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getExternalFilesDir(java.lang.String)' on a null object reference
The fact that it only does this periodically sujects that sometimes the external portion of the built in memory is not mounted, but the previous version was using the same memory?
Really not sure what could cause this issue, any help appreciated.
Some code:
public class UploadGPSAlarmReceiver extends BroadcastReceiver {
private static final String TAG = "MicRecordUploadAlarm";
TransferUtility mTransferUtility;
Encryption mEncryption;
Context mContext;
String encryptedPath;
static String folder = "/GPS/";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: ");
mContext = context;
mEncryption = new Encryption();
mTransferUtility = Util.getTransferUtility(mContext);
Calendar c = Calendar.getInstance();
//System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
String formattedDate = df.format(c.getTime());
String path = mContext.getExternalFilesDir(null) + "/videoDIARY/Location/";
File directory = new File(path);
if(!directory.exists()){
directory.mkdirs();
}
}
The BroadcastReceiver is called from my Main activity, in a method which is called during onCreate:
Intent intent = new Intent(this, UploadGPSAlarmReceiver.class);
Because this only happens periodically, and from the helpful comments below ( thanks everyone! ), I am deducing that what is happening is my app is launched, everything runs smoothly, my app moves into the background a day or so later, and when the BroadcastReceiver is fired the Main Activity that the context is passed from is no longer instantiated and the app crashes because context is null.
I can think of a few ways of dealing with this, but would be interested in peoples opinions for the best way of doing it? I could make Main Activity a static instance? I could get Application context instead of using Activity context?