Search code examples
androidc++kotlinandroid-ndksharedpreferences

How to read shared preferences from Android NDK C++ code?


I'd like to read shared preferences from C++ code directly. Is that possible?

Any piece of code for that ? Thanks.

Here's what I would transcript to C++ :

val sharedPref = applicationContext.getSharedPreferences("OF_IR", MODE_PRIVATE)
val paramFromPref = sharedPref.getString("parameter", "")
if (paramFromPref != "") {

}

Solution

  • You can call Kotlin function from JNI easily. Here is JNI Docs.

    https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

    You can find method for FindClass, GetMethodId, CallVoidMethod, etc.

    Here is example for read sharedpreferences.

    jclass jcContext = env->FindClass("android/content/Context");
    jclass jcSharedPreferences = env->FindClass("android/content/SharedPreferences");
    
    if(jcContext==nullptr || jcSharedPreferences== nullptr){
        __android_log_print(ANDROID_LOG_DEBUG, "SharedPreferences","Cannot find classes");
    }
    
    jmGetString=env->GetMethodID(jcSharedPreferences,"getString","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
    jmethodID jmGetSharedPreferences=env->GetMethodID(jcContext,"getSharedPreferences","(Ljava/lang/String;I)Landroid/content/SharedPreferences;");
    joSharedPreferences=env->CallObjectMethod(androidContext,jmGetSharedPreferences,env->NewStringUTF(name),MODE_PRIVATE);