Java lang unsatisfiedlinkerror как исправить андроид

I am new in ndk development in android.I have gone through the file system of ndk android. Here, explaining what i have done. 1) i have created a folder named "jni" then create 2 file named Android...

I am new in ndk development in android.I have gone through the file system of ndk android.
Here, explaining what i have done.
1) i have created a folder named «jni» then create 2 file named Android.mk and ndkfoo.c.

In Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_MODULE    := ndkfoo
LOCAL_SRC_FILES := ndkfoo.c

include $(BUILD_SHARED_LIBRARY)

and in ndkfoo.c

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

then i have created NdkFooActivity class, in which i have written

// load the library - name matches jni/Android.mk
 static {
  System.loadLibrary("ndkfoo");
 }

But now when i build from cygwin in xp it creates .so file successfully then i run as android application. It gives me java.lang.UnsatisfiedLinkError in LOGCAT.

So, Please let me know where i am wrong.

Thanks in Advance,

Juan Cortés's user avatar

Juan Cortés

20.3k8 gold badges67 silver badges91 bronze badges

asked Jul 16, 2010 at 6:32

Indrajit Kumar's user avatar

Indrajit KumarIndrajit Kumar

4011 gold badge5 silver badges13 bronze badges

3

I think you forgot to change the package name.

Java_com_mindtherobot_samples_ndkfoo

It should be your package what you have specified creating project.

answered Mar 9, 2011 at 8:33

StarDust's user avatar

Also(just ran into this issue), please note that System.loadLibrary() will always throw an exception if you are testing on the Intel Atom x86 emulator. It works just fine on regular Android emulators and debugging on a physical device.

answered Dec 13, 2012 at 23:47

Daniel Rodriguez's user avatar

5

Although this has not been the OP’s problem, I had the same java.lang.UnsatisfiedLinkError because of missing

static {
    System.loadLibrary("mylibraryname");
}

answered Jan 20, 2012 at 6:53

18446744073709551615's user avatar

1

There’s a good chance the signature is wrong, as others have mentioned.

If you run the javah utility, you can find the exact signature. From the bin folder in your project, where the .apk is and the root of the Java class hierarchy is generated, run:

javah -o jni_sig.h com.mindtherobot.whatever.your.package.is.NdkFooActivity

…and, if you got the package name and class name correct, it will write out a header (called jni_sig.h) with the correct function signature(s) for any native functions. Copy that to your header and .c file, adding parameters as needed, and it should work correctly.

answered Sep 25, 2010 at 6:23

SomeCallMeTim's user avatar

SomeCallMeTimSomeCallMeTim

4,3742 gold badges27 silver badges27 bronze badges

1

Maybe not relevant anymore but as far as I know you also need to add the «lib» prefix to your native library name. In your case you need to change the Android.mk to
«LOCAL_MODULE := libndkfoo» and keep «System.loadLibrary(«ndkfoo»);» as it is. Check the ndk sample code.

answered Dec 11, 2012 at 20:41

Elis Popescu's user avatar

0

I’m pretty sure that should be:

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

Which SDK are you targeting and which version of the NDK do you have? Does the error you’re getting say that it couldn’t load the library at all or that there was an unimplemented method? Either way make sure you don’t have android:hasCode=»false» set on the application tag in your manifest.

You can also open up the APK file after a build using winrar or something similar to make sure that the libndkfoo.so file is actually being included with the package.

Either way if you aren’t declaring the native function in NdkFooActivity you will get that error, i.e.

public static native String invokeNativeFunction();

answered Jan 13, 2012 at 14:39

Justin Buser's user avatar

Justin BuserJustin Buser

2,80525 silver badges32 bronze badges

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

the problem is that you compile for a target processor and execute in other. if you compile in ARM(armeabi) then execute in armeabi based emulator.
create a file called application.mk in same folder as Android.mk and put inside it one of this:

  1. APP_ABI := x86
  2. APP_ABI := armeabi
  3. APP_ABI := mips
  4. APP_ABI := armeabi x86 mips //to compile in all target and you will get 3 *.so files

then compile->run.
it should work.

answered Aug 11, 2013 at 21:03

SRedouane's user avatar

SRedouaneSRedouane

4985 silver badges10 bronze badges

0

Create a file Application.mk in jni folder.Copy following line and paste it to Application.mk and save.Now build the project with your cgywin and run again

APP_ABI := armeabi armeabi-v7a

answered Nov 25, 2012 at 8:41

Sajal Saha's user avatar

Sajal SahaSajal Saha

1692 silver badges12 bronze badges

The method name Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

may be not same as that of your package name or class name.
To make this naming of method exactly same you must use javah.

This will make a header file which will be having the same method name that is required.To make this header file go to the classes folder in the bin of your project(make sure you have created the java file with static method and build it properly) by this command in your terminal

~/workspace/Android_Example2/bin/classes$

In this directory write the following command

sudo javah -jni com.NDK.android_example2.MainActivity

Change the package name and class name according to your project.This will create a com_NDK_android_example2_MainActivity.h in your classes folder.

Simply move this file into your jni folder. In this file, there will be static methods that you have created in the MainActivity.java file but they are just declared not implemented that you will implement in your C file.

NOTE: While Coping the method check that the method parameters are need to be declared, so make them declare in your C file.

Hope this help.

answered Jun 11, 2013 at 5:58

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Replace this

Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

With

Java_your_packege_name_your_Activity_Name_invokeNativeFunction

Example if your package is com.pack and Activity Name name is MainActivity then

Java_com_pack1_MainActivity_invokeNativeFunction 

Don’t forget to add reference in Activity.

// load the library — name matches jni/Android.mk

static {
        System.loadLibrary("ndkfoo");
      }

 public native String invokeNativeFunction();

Repeat all these step it should work :)

answered Jul 28, 2013 at 10:01

Vinayak's user avatar

VinayakVinayak

5,9661 gold badge31 silver badges30 bronze badges

I also had a java.lang.UnsatisfiedLinkError error. I verified everything mention in above answers but was still getting the error. I eventually discovered that the JNI method names cannot have underscores.

Example:
Java_com_example_app_NativeLib_print_out_stuff <- generates java.lang.UnsatisfiedLinkError: print_out_stuff

Rename the print_out_stuff function to something without underscores:
Java_com_example_app_NativeLib_printOutStuff <- works

answered Mar 29, 2013 at 4:07

Awesomeness's user avatar

AwesomenessAwesomeness

6528 silver badges14 bronze badges

here’s a tutorial how to use native code: here

make sure you dont have any spaces in your project path.
also you cant use an underscore in your package or project name.

answered Mar 29, 2013 at 15:22

karyochi's user avatar

I am new in ndk development in android.I have gone through the file system of ndk android.
Here, explaining what i have done.
1) i have created a folder named «jni» then create 2 file named Android.mk and ndkfoo.c.

In Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_MODULE    := ndkfoo
LOCAL_SRC_FILES := ndkfoo.c

include $(BUILD_SHARED_LIBRARY)

and in ndkfoo.c

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

then i have created NdkFooActivity class, in which i have written

// load the library - name matches jni/Android.mk
 static {
  System.loadLibrary("ndkfoo");
 }

But now when i build from cygwin in xp it creates .so file successfully then i run as android application. It gives me java.lang.UnsatisfiedLinkError in LOGCAT.

So, Please let me know where i am wrong.

Thanks in Advance,

Juan Cortés's user avatar

Juan Cortés

20.3k8 gold badges67 silver badges91 bronze badges

asked Jul 16, 2010 at 6:32

Indrajit Kumar's user avatar

Indrajit KumarIndrajit Kumar

4011 gold badge5 silver badges13 bronze badges

3

I think you forgot to change the package name.

Java_com_mindtherobot_samples_ndkfoo

It should be your package what you have specified creating project.

answered Mar 9, 2011 at 8:33

StarDust's user avatar

Also(just ran into this issue), please note that System.loadLibrary() will always throw an exception if you are testing on the Intel Atom x86 emulator. It works just fine on regular Android emulators and debugging on a physical device.

answered Dec 13, 2012 at 23:47

Daniel Rodriguez's user avatar

5

Although this has not been the OP’s problem, I had the same java.lang.UnsatisfiedLinkError because of missing

static {
    System.loadLibrary("mylibraryname");
}

answered Jan 20, 2012 at 6:53

18446744073709551615's user avatar

1

There’s a good chance the signature is wrong, as others have mentioned.

If you run the javah utility, you can find the exact signature. From the bin folder in your project, where the .apk is and the root of the Java class hierarchy is generated, run:

javah -o jni_sig.h com.mindtherobot.whatever.your.package.is.NdkFooActivity

…and, if you got the package name and class name correct, it will write out a header (called jni_sig.h) with the correct function signature(s) for any native functions. Copy that to your header and .c file, adding parameters as needed, and it should work correctly.

answered Sep 25, 2010 at 6:23

SomeCallMeTim's user avatar

SomeCallMeTimSomeCallMeTim

4,3742 gold badges27 silver badges27 bronze badges

1

Maybe not relevant anymore but as far as I know you also need to add the «lib» prefix to your native library name. In your case you need to change the Android.mk to
«LOCAL_MODULE := libndkfoo» and keep «System.loadLibrary(«ndkfoo»);» as it is. Check the ndk sample code.

answered Dec 11, 2012 at 20:41

Elis Popescu's user avatar

0

I’m pretty sure that should be:

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

Which SDK are you targeting and which version of the NDK do you have? Does the error you’re getting say that it couldn’t load the library at all or that there was an unimplemented method? Either way make sure you don’t have android:hasCode=»false» set on the application tag in your manifest.

You can also open up the APK file after a build using winrar or something similar to make sure that the libndkfoo.so file is actually being included with the package.

Either way if you aren’t declaring the native function in NdkFooActivity you will get that error, i.e.

public static native String invokeNativeFunction();

answered Jan 13, 2012 at 14:39

Justin Buser's user avatar

Justin BuserJustin Buser

2,80525 silver badges32 bronze badges

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

the problem is that you compile for a target processor and execute in other. if you compile in ARM(armeabi) then execute in armeabi based emulator.
create a file called application.mk in same folder as Android.mk and put inside it one of this:

  1. APP_ABI := x86
  2. APP_ABI := armeabi
  3. APP_ABI := mips
  4. APP_ABI := armeabi x86 mips //to compile in all target and you will get 3 *.so files

then compile->run.
it should work.

answered Aug 11, 2013 at 21:03

SRedouane's user avatar

SRedouaneSRedouane

4985 silver badges10 bronze badges

0

Create a file Application.mk in jni folder.Copy following line and paste it to Application.mk and save.Now build the project with your cgywin and run again

APP_ABI := armeabi armeabi-v7a

answered Nov 25, 2012 at 8:41

Sajal Saha's user avatar

Sajal SahaSajal Saha

1692 silver badges12 bronze badges

The method name Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

may be not same as that of your package name or class name.
To make this naming of method exactly same you must use javah.

This will make a header file which will be having the same method name that is required.To make this header file go to the classes folder in the bin of your project(make sure you have created the java file with static method and build it properly) by this command in your terminal

~/workspace/Android_Example2/bin/classes$

In this directory write the following command

sudo javah -jni com.NDK.android_example2.MainActivity

Change the package name and class name according to your project.This will create a com_NDK_android_example2_MainActivity.h in your classes folder.

Simply move this file into your jni folder. In this file, there will be static methods that you have created in the MainActivity.java file but they are just declared not implemented that you will implement in your C file.

NOTE: While Coping the method check that the method parameters are need to be declared, so make them declare in your C file.

Hope this help.

answered Jun 11, 2013 at 5:58

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Replace this

Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

With

Java_your_packege_name_your_Activity_Name_invokeNativeFunction

Example if your package is com.pack and Activity Name name is MainActivity then

Java_com_pack1_MainActivity_invokeNativeFunction 

Don’t forget to add reference in Activity.

// load the library — name matches jni/Android.mk

static {
        System.loadLibrary("ndkfoo");
      }

 public native String invokeNativeFunction();

Repeat all these step it should work :)

answered Jul 28, 2013 at 10:01

Vinayak's user avatar

VinayakVinayak

5,9661 gold badge31 silver badges30 bronze badges

I also had a java.lang.UnsatisfiedLinkError error. I verified everything mention in above answers but was still getting the error. I eventually discovered that the JNI method names cannot have underscores.

Example:
Java_com_example_app_NativeLib_print_out_stuff <- generates java.lang.UnsatisfiedLinkError: print_out_stuff

Rename the print_out_stuff function to something without underscores:
Java_com_example_app_NativeLib_printOutStuff <- works

answered Mar 29, 2013 at 4:07

Awesomeness's user avatar

AwesomenessAwesomeness

6528 silver badges14 bronze badges

here’s a tutorial how to use native code: here

make sure you dont have any spaces in your project path.
also you cant use an underscore in your package or project name.

answered Mar 29, 2013 at 15:22

karyochi's user avatar

I am new in ndk development in android.I have gone through the file system of ndk android.
Here, explaining what i have done.
1) i have created a folder named «jni» then create 2 file named Android.mk and ndkfoo.c.

In Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_MODULE    := ndkfoo
LOCAL_SRC_FILES := ndkfoo.c

include $(BUILD_SHARED_LIBRARY)

and in ndkfoo.c

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

then i have created NdkFooActivity class, in which i have written

// load the library - name matches jni/Android.mk
 static {
  System.loadLibrary("ndkfoo");
 }

But now when i build from cygwin in xp it creates .so file successfully then i run as android application. It gives me java.lang.UnsatisfiedLinkError in LOGCAT.

So, Please let me know where i am wrong.

Thanks in Advance,

Juan Cortés's user avatar

Juan Cortés

20.3k8 gold badges67 silver badges91 bronze badges

asked Jul 16, 2010 at 6:32

Indrajit Kumar's user avatar

Indrajit KumarIndrajit Kumar

4011 gold badge5 silver badges13 bronze badges

3

I think you forgot to change the package name.

Java_com_mindtherobot_samples_ndkfoo

It should be your package what you have specified creating project.

answered Mar 9, 2011 at 8:33

StarDust's user avatar

Also(just ran into this issue), please note that System.loadLibrary() will always throw an exception if you are testing on the Intel Atom x86 emulator. It works just fine on regular Android emulators and debugging on a physical device.

answered Dec 13, 2012 at 23:47

Daniel Rodriguez's user avatar

5

Although this has not been the OP’s problem, I had the same java.lang.UnsatisfiedLinkError because of missing

static {
    System.loadLibrary("mylibraryname");
}

answered Jan 20, 2012 at 6:53

18446744073709551615's user avatar

1

There’s a good chance the signature is wrong, as others have mentioned.

If you run the javah utility, you can find the exact signature. From the bin folder in your project, where the .apk is and the root of the Java class hierarchy is generated, run:

javah -o jni_sig.h com.mindtherobot.whatever.your.package.is.NdkFooActivity

…and, if you got the package name and class name correct, it will write out a header (called jni_sig.h) with the correct function signature(s) for any native functions. Copy that to your header and .c file, adding parameters as needed, and it should work correctly.

answered Sep 25, 2010 at 6:23

SomeCallMeTim's user avatar

SomeCallMeTimSomeCallMeTim

4,3742 gold badges27 silver badges27 bronze badges

1

Maybe not relevant anymore but as far as I know you also need to add the «lib» prefix to your native library name. In your case you need to change the Android.mk to
«LOCAL_MODULE := libndkfoo» and keep «System.loadLibrary(«ndkfoo»);» as it is. Check the ndk sample code.

answered Dec 11, 2012 at 20:41

Elis Popescu's user avatar

0

I’m pretty sure that should be:

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

Which SDK are you targeting and which version of the NDK do you have? Does the error you’re getting say that it couldn’t load the library at all or that there was an unimplemented method? Either way make sure you don’t have android:hasCode=»false» set on the application tag in your manifest.

You can also open up the APK file after a build using winrar or something similar to make sure that the libndkfoo.so file is actually being included with the package.

Either way if you aren’t declaring the native function in NdkFooActivity you will get that error, i.e.

public static native String invokeNativeFunction();

answered Jan 13, 2012 at 14:39

Justin Buser's user avatar

Justin BuserJustin Buser

2,80525 silver badges32 bronze badges

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

the problem is that you compile for a target processor and execute in other. if you compile in ARM(armeabi) then execute in armeabi based emulator.
create a file called application.mk in same folder as Android.mk and put inside it one of this:

  1. APP_ABI := x86
  2. APP_ABI := armeabi
  3. APP_ABI := mips
  4. APP_ABI := armeabi x86 mips //to compile in all target and you will get 3 *.so files

then compile->run.
it should work.

answered Aug 11, 2013 at 21:03

SRedouane's user avatar

SRedouaneSRedouane

4985 silver badges10 bronze badges

0

Create a file Application.mk in jni folder.Copy following line and paste it to Application.mk and save.Now build the project with your cgywin and run again

APP_ABI := armeabi armeabi-v7a

answered Nov 25, 2012 at 8:41

Sajal Saha's user avatar

Sajal SahaSajal Saha

1692 silver badges12 bronze badges

The method name Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

may be not same as that of your package name or class name.
To make this naming of method exactly same you must use javah.

This will make a header file which will be having the same method name that is required.To make this header file go to the classes folder in the bin of your project(make sure you have created the java file with static method and build it properly) by this command in your terminal

~/workspace/Android_Example2/bin/classes$

In this directory write the following command

sudo javah -jni com.NDK.android_example2.MainActivity

Change the package name and class name according to your project.This will create a com_NDK_android_example2_MainActivity.h in your classes folder.

Simply move this file into your jni folder. In this file, there will be static methods that you have created in the MainActivity.java file but they are just declared not implemented that you will implement in your C file.

NOTE: While Coping the method check that the method parameters are need to be declared, so make them declare in your C file.

Hope this help.

answered Jun 11, 2013 at 5:58

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Replace this

Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

With

Java_your_packege_name_your_Activity_Name_invokeNativeFunction

Example if your package is com.pack and Activity Name name is MainActivity then

Java_com_pack1_MainActivity_invokeNativeFunction 

Don’t forget to add reference in Activity.

// load the library — name matches jni/Android.mk

static {
        System.loadLibrary("ndkfoo");
      }

 public native String invokeNativeFunction();

Repeat all these step it should work :)

answered Jul 28, 2013 at 10:01

Vinayak's user avatar

VinayakVinayak

5,9661 gold badge31 silver badges30 bronze badges

I also had a java.lang.UnsatisfiedLinkError error. I verified everything mention in above answers but was still getting the error. I eventually discovered that the JNI method names cannot have underscores.

Example:
Java_com_example_app_NativeLib_print_out_stuff <- generates java.lang.UnsatisfiedLinkError: print_out_stuff

Rename the print_out_stuff function to something without underscores:
Java_com_example_app_NativeLib_printOutStuff <- works

answered Mar 29, 2013 at 4:07

Awesomeness's user avatar

AwesomenessAwesomeness

6528 silver badges14 bronze badges

here’s a tutorial how to use native code: here

make sure you dont have any spaces in your project path.
also you cant use an underscore in your package or project name.

answered Mar 29, 2013 at 15:22

karyochi's user avatar

I am new in ndk development in android.I have gone through the file system of ndk android.
Here, explaining what i have done.
1) i have created a folder named «jni» then create 2 file named Android.mk and ndkfoo.c.

In Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_MODULE    := ndkfoo
LOCAL_SRC_FILES := ndkfoo.c

include $(BUILD_SHARED_LIBRARY)

and in ndkfoo.c

#include <string.h>
#include <jni.h>

jstring Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

then i have created NdkFooActivity class, in which i have written

// load the library - name matches jni/Android.mk
 static {
  System.loadLibrary("ndkfoo");
 }

But now when i build from cygwin in xp it creates .so file successfully then i run as android application. It gives me java.lang.UnsatisfiedLinkError in LOGCAT.

So, Please let me know where i am wrong.

Thanks in Advance,

Juan Cortés's user avatar

Juan Cortés

20.3k8 gold badges67 silver badges91 bronze badges

asked Jul 16, 2010 at 6:32

Indrajit Kumar's user avatar

Indrajit KumarIndrajit Kumar

4011 gold badge5 silver badges13 bronze badges

3

I think you forgot to change the package name.

Java_com_mindtherobot_samples_ndkfoo

It should be your package what you have specified creating project.

answered Mar 9, 2011 at 8:33

StarDust's user avatar

Also(just ran into this issue), please note that System.loadLibrary() will always throw an exception if you are testing on the Intel Atom x86 emulator. It works just fine on regular Android emulators and debugging on a physical device.

answered Dec 13, 2012 at 23:47

Daniel Rodriguez's user avatar

5

Although this has not been the OP’s problem, I had the same java.lang.UnsatisfiedLinkError because of missing

static {
    System.loadLibrary("mylibraryname");
}

answered Jan 20, 2012 at 6:53

18446744073709551615's user avatar

1

There’s a good chance the signature is wrong, as others have mentioned.

If you run the javah utility, you can find the exact signature. From the bin folder in your project, where the .apk is and the root of the Java class hierarchy is generated, run:

javah -o jni_sig.h com.mindtherobot.whatever.your.package.is.NdkFooActivity

…and, if you got the package name and class name correct, it will write out a header (called jni_sig.h) with the correct function signature(s) for any native functions. Copy that to your header and .c file, adding parameters as needed, and it should work correctly.

answered Sep 25, 2010 at 6:23

SomeCallMeTim's user avatar

SomeCallMeTimSomeCallMeTim

4,3742 gold badges27 silver badges27 bronze badges

1

Maybe not relevant anymore but as far as I know you also need to add the «lib» prefix to your native library name. In your case you need to change the Android.mk to
«LOCAL_MODULE := libndkfoo» and keep «System.loadLibrary(«ndkfoo»);» as it is. Check the ndk sample code.

answered Dec 11, 2012 at 20:41

Elis Popescu's user avatar

0

I’m pretty sure that should be:

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

Which SDK are you targeting and which version of the NDK do you have? Does the error you’re getting say that it couldn’t load the library at all or that there was an unimplemented method? Either way make sure you don’t have android:hasCode=»false» set on the application tag in your manifest.

You can also open up the APK file after a build using winrar or something similar to make sure that the libndkfoo.so file is actually being included with the package.

Either way if you aren’t declaring the native function in NdkFooActivity you will get that error, i.e.

public static native String invokeNativeFunction();

answered Jan 13, 2012 at 14:39

Justin Buser's user avatar

Justin BuserJustin Buser

2,80525 silver badges32 bronze badges

JNIEXPORT jstring JNICALL Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction(JNIEnv* env, jobject javaThis) {
 return (*env)->NewStringUTF(env, "Hello from native code!");
}

the problem is that you compile for a target processor and execute in other. if you compile in ARM(armeabi) then execute in armeabi based emulator.
create a file called application.mk in same folder as Android.mk and put inside it one of this:

  1. APP_ABI := x86
  2. APP_ABI := armeabi
  3. APP_ABI := mips
  4. APP_ABI := armeabi x86 mips //to compile in all target and you will get 3 *.so files

then compile->run.
it should work.

answered Aug 11, 2013 at 21:03

SRedouane's user avatar

SRedouaneSRedouane

4985 silver badges10 bronze badges

0

Create a file Application.mk in jni folder.Copy following line and paste it to Application.mk and save.Now build the project with your cgywin and run again

APP_ABI := armeabi armeabi-v7a

answered Nov 25, 2012 at 8:41

Sajal Saha's user avatar

Sajal SahaSajal Saha

1692 silver badges12 bronze badges

The method name Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

may be not same as that of your package name or class name.
To make this naming of method exactly same you must use javah.

This will make a header file which will be having the same method name that is required.To make this header file go to the classes folder in the bin of your project(make sure you have created the java file with static method and build it properly) by this command in your terminal

~/workspace/Android_Example2/bin/classes$

In this directory write the following command

sudo javah -jni com.NDK.android_example2.MainActivity

Change the package name and class name according to your project.This will create a com_NDK_android_example2_MainActivity.h in your classes folder.

Simply move this file into your jni folder. In this file, there will be static methods that you have created in the MainActivity.java file but they are just declared not implemented that you will implement in your C file.

NOTE: While Coping the method check that the method parameters are need to be declared, so make them declare in your C file.

Hope this help.

answered Jun 11, 2013 at 5:58

Jagdeep Singh's user avatar

Jagdeep SinghJagdeep Singh

1,1901 gold badge16 silver badges34 bronze badges

Replace this

Java_com_mindtherobot_samples_ndkfoo_NdkFooActivity_invokeNativeFunction

With

Java_your_packege_name_your_Activity_Name_invokeNativeFunction

Example if your package is com.pack and Activity Name name is MainActivity then

Java_com_pack1_MainActivity_invokeNativeFunction 

Don’t forget to add reference in Activity.

// load the library — name matches jni/Android.mk

static {
        System.loadLibrary("ndkfoo");
      }

 public native String invokeNativeFunction();

Repeat all these step it should work :)

answered Jul 28, 2013 at 10:01

Vinayak's user avatar

VinayakVinayak

5,9661 gold badge31 silver badges30 bronze badges

I also had a java.lang.UnsatisfiedLinkError error. I verified everything mention in above answers but was still getting the error. I eventually discovered that the JNI method names cannot have underscores.

Example:
Java_com_example_app_NativeLib_print_out_stuff <- generates java.lang.UnsatisfiedLinkError: print_out_stuff

Rename the print_out_stuff function to something without underscores:
Java_com_example_app_NativeLib_printOutStuff <- works

answered Mar 29, 2013 at 4:07

Awesomeness's user avatar

AwesomenessAwesomeness

6528 silver badges14 bronze badges

here’s a tutorial how to use native code: here

make sure you dont have any spaces in your project path.
also you cant use an underscore in your package or project name.

answered Mar 29, 2013 at 15:22

karyochi's user avatar

Анализ ошибок

Эта ошибка является проблемой загрузки библиотеки, и отчет об ошибке обычно начинается с java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader. Как правило, программа вызывает System.loadLibrary («xxxxxxxx») во время выполнения процесса; выдается сообщение об ошибке, поскольку файл libxxxxxx.so не может быть найден. Мы можем решить эту ошибку в процессе расследования.

Анализ и решение проблемы

1. Проверьте, была ли библиотека so упакована в apk в процессе компиляции.

метод:
Найдите этот каталог проектаappbuildoutputsapk, А затем откройте его с помощью программного обеспечения для сжатияapp-debug.apkДля этого файла перейдите в библиотеки, чтобы найти файл libxxxxxx.so без ошибок.
решить:
Если да, переходите к следующему шагу. Если нет, проверьте, правильно ли вы поместили файл libxxxxxx.so, а затем заново упакуйте его.

2. Проверьте, загрузил ли проект библиотеку so.

Метод и решение:
Найдите приложение проектаbuild.gradleFile, посмотрите, введена ли зависимость файла libs. Правильная формулировка следующая:

android {
	sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}

Помните, что sourceSets необходимо поместить в блок кода Android. Если нет, добавьте это предложение и перекомпилируйте, проблема решена.

3. Проверьте, исключает ли NDK архитектуру вашего устройства.

метод:

android {
    defaultConfig {
        ........// Остальные настройки здесь опущены
        ndk {
            abiFilters  "armeabi"
        }
    }
}

Как показано на рисунке выше, этот параметр предназначен для загрузки только библиотеки so архитектуры armabi (в каталоге). Если это другая архитектура, она не будет найдена.
решить:
Мы можем добавить нужную нам архитектуру. Преимущество этого заключается в том, что размер apk может быть уменьшен. Код выглядит следующим образом:

android {
    defaultConfig {
        ........// Остальные настройки здесь опущены
        ndk {
            abiFilters  "armeabi","x86"
        }
    }
}

Таким образом, мы представили архитектуру x86, и мы должны обратить внимание на то, что библиотека в каждом каталоге должна быть каталогом соответствующей архитектуры.

4. Проверьте, есть ли у armeabi и armeabi-v7a библиотеки so.

Метод и решение:
Мы можем представить архитектуру armeabi-v7a, затем скопировать файлы из armeabi в каталог anmeabi-v7a, а затем перекомпилировать. Несогласованность файлов armeabi и armeabi-v7a также может привести к программным исключениям.

Резюме и другие исключения

Фактически, это исключение является проблемой загрузки, и также может быть, что соответствующая архитектура библиотеки so неверна. Вышеупомянутые четыре метода могут решить 90% проблем. Есть еще проблемы, которые можно прокомментировать. Давайте обсудим это вместе.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Java.lang.UnsatisfiedLinkError is a subclass of LinkageError Class. When Java Virtual Machine(JVM) did not find the method Which is declared as  “native” it will throw the UnsatisfiedLinkError. 

    Now let us do discuss when and why does it occur. Java.lang.UnsatisfiedLinkError occurs during the compilation of the program. It is because of the reason that compiler did not find the Native Library, a Library that contains native code which meant only for a specified operating system, Native library like .dll in Windows, .so in Linux and .dylib in Mac. The hierarchy of this Error is like the given below as follows:

    Java.lang.Object
        Java.lang.Throwable
            Java.lang.Error
                Java.lang.LinkageError
                    Java.lang.UnsatisfiedLinkError

    Example

    Java

    import java.io.*;

    public class GFG {

        static {

            System.loadLibrary("libfile");

        }

        native void cfun();

        public static void main(String[] args) {

            GFG g = new GFG();

            g.cfun();

        }

    }

    Output:

    As seen above now in order to handle this error, we need to make sure that the PATH should contain the given “DLL” file in Windows. We can also check the java.library.path is set or not. If we are running the java file using the Command Prompt in Windows we can use the Java -Djava.library.path=”NAME_OF_THE_DLL_FILE” -jar <JAR_FILR_NAME.jar> to run our java file. Another thing we can use is by giving the exact file location in System.LoadLibrary(“Exact File Path”) or System.load(“Exact File Path”) Method.

    Example

    Java

    import java.io.*;

    public class GFG {

        static

        {

            System.load(

                "C:/Users/SYSTEM/Desktop/CODES/libfile.dll");

        }

        native void cfun();

        public static void main(String[] args)

        {

            GFG g = new GFG();

            g.cfun();

        }

    }

    Output: When we run the above java file it will Compile Successfully and display the Output.

    Hello from C file

    Note:

    We will generate the .dll file from this C file by using the command- ‘gcc cfile.c -I C:/Program Files/Java/jdk1.8.0_111/include -I C:/Program Files/Java/jdk1.8.0_111/include/win32  -shared -o cfile.dll‘. Now when we run the above java file it will Compile Successfully and display the Output.

    Понравилась статья? Поделить с друзьями:
  • Java lang securityexception ошибка как исправить на андроид
  • Java lang runtimeexception как исправить на телефоне
  • Java lang runtimeexception как исправить minecraft
  • Java lang runtimeexception keypair generation error
  • Java lang runtimeexception error initializing quantumrenderer no suitable pipeline found