[FIXED] ANativeWindow_fromSurface(env,surface) always returns null

Issue

I’m trying to pass surface from a fragment to my native code.

But ANativeWindow is always null when I create using ANativeWindow_fromSurface(env,surface);

I’m using kotlin and not java.

I call native function from onViewCreated() function from my fragment :

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    

    surfaceView  = view.findViewById(R.id.surfaceView)
    surface = surfaceView.holder.surface

    myClass = MyClass()
    myClass.myFunction(surface)
 
}

My class:

class MyClass{

init {
    System.loadLibrary("nativeLib")
}

external fun myFunction(surface: Surface): Int

}

This is my native.cpp :

extern "C"
JNIEXPORT jint JNICALL
Java_com_my_app_MyClass_myFunction(JNIEnv *env,jobject obj,jobject surface){


nativeWindow = ANativeWindow_fromSurface(env,surface);

if(nativeWindow == nullptr){
    ALOG("nativeWindow is null");
    return -1;
}

}

When I install my app, it shows that nativeWindow is null.
Why is it null?
Could anyone suggest me a solution for this ?

Solution

Finally found the solution !!

I moved myClass.myFunction() call to SurfaceHolder.Callback{} .

Now it looks like this :

override fun surfaceCreated(p0: SurfaceHolder) {

    object : Thread(){
        override fun run() {
            myClass.myFunction(surface)
        }
    }.start()

}

Answered By – Binish Mathew

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published