Search code examples
androidc++android-ndkjava-native-interface

DCIM directory path on Android - Return Value


I have requirement of getting DCIM directory path from Native code. I am using the following code snippet:

jclass envClass = env->FindClass("android/os/Environment");
char charParam[] = "Environment.DIRECTORY_DCIM";
jstring jstrParam = env->NewStringUTF(charParam);
jmethodID getExtStorageDirectoryMethod = env->GetStaticMethodID(envClass, "getExternalStoragePublicDirectory",  "(Ljava/lang/String;)Ljava/io/File;");
jobject extStorageFile = env->CallStaticObjectMethod(envClass, getExtStorageDirectoryMethod, jstrParam);
jclass fileClass = env->FindClass("java/io/File");
jmethodID getPathMethod = env->GetMethodID(fileClass, "getPath", "()Ljava/lang/String;");
jstring extStoragePath = (jstring)env->CallObjectMethod(extStorageFile, getPathMethod);
const char* extStoragePathString = env->GetStringUTFChars(extStoragePath,NULL);

//use extStoragePathString
LOGI("DCIM_PATH ==================================== %s", extStoragePathString);

But result is always [PATH_TO_SD_CARD]/Environment.DIRECTORY_DCIM. I checked this is couple of devices as well as on Emulator. I created DCIM directory on emulator. Path to SD Card is correct.

As a solution, I can always go ahead and search for DCIM directory on SD Card. Because anyway under DCIM, I have to search where are pics. But still, Why aren't I getting the path to DCIM?


Solution

  • Environment.DIRECTORY_DCIM is the qualified Java name of the static String defined in the Environment class for the DCIM folder. However, it's isn't the actual value of the String, which is just "DCIM":

    public static String DIRECTORY_DCIM = "DCIM";
    

    You need to pass the String value, not the Java name of the variable, so you can change your code like this:

    char charParam[] = "DCIM";
    

    Passing this value as a parameter is equivalent to calling:

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
    

    in Java, given that Environment.DIRECTORY_DCIM is defined as "DCIM".

    However, if you do not want to use a hard-coded value, you can look up the static field from the Environment class, like this:

    jfieldID fieldId = env->GetStaticFieldID(envClass, "DIRECTORY_DCIM", "Ljava/lang/String;");
    jstring jstrParam = (jstring)env->GetStaticObjectField(envClass, fieldId);