Not able to show toast from native_activity

54 views
Skip to first unread message

niraj gandha

unread,
May 24, 2022, 5:36:43 PMMay 24
to android-ndk
Hello, 

I am trying to show the toast message from native activity without having any java or kotlin code. But I am facing error in showing it.

Code:
static void makeToast(JNIEnv *penv, jobject thiz, const char *text, engine *pEngine) {
JNIEnv* env;
pEngine->app->activity->vm->AttachCurrentThread(&env, nullptr);

jstring jstr = env->NewStringUTF(text); //Edit this text to your desired toast message!
jclass toast = env->FindClass("android/widget/Toast");
jmethodID methodMakeText =
env->GetStaticMethodID(
toast,
"makeText",
"(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;");
if (methodMakeText == nullptr) {
LOGE("toast.makeText not Found");
return;
}
//The last int is the length on how long the toast should be displayed
//0 = Short, 1 = Long
jobject toastobj = env->CallStaticObjectMethod(toast, methodMakeText,
thiz, jstr, 0);

jmethodID methodShow = env->GetMethodID(toast, "show", "()V");
if (methodShow == nullptr) {
LOGE("toast.show not Found");
return;
}
env->CallVoidMethod(toastobj, methodShow);
}

Here, I am facing crash due to Looper.prepare() not called. 
Logs:
2022-05-23 23:07:59.379 10429-10477/com.niraj.nativealert A/raj.nativealer: runtime.cc:677] JNI DETECTED ERROR IN APPLICATION: JNI GetMethodID called with pending exception java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
    runtime.cc:677]   at java.lang.Object com.android.internal.util.Preconditions.checkNotNull(java.lang.Object, java.lang.Object) (Preconditions.java:167)
    runtime.cc:677]   at android.os.Looper android.widget.Toast.getLooper(android.os.Looper) (Toast.java:182)
    runtime.cc:677]   at void android.widget.Toast.<init>(android.content.Context, android.os.Looper) (Toast.java:167)
    runtime.cc:677]   at android.widget.Toast android.widget.Toast.makeText(android.content.Context, android.os.Looper, java.lang.CharSequence, int) (Toast.java:495)
    runtime.cc:677]   at android.widget.Toast android.widget.Toast.makeText(android.content.Context, java.lang.CharSequence, int) (Toast.java:483)
    runtime.cc:677]
    runtime.cc:677]     in call to GetMethodID
2022-05-23 23:07:59.380 10429-10477/com.niraj.nativealert A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 10477 (Thread-2), pid 10429 (raj.nativealert)


Please help me with it or any link for how to do it.

Thanks,
Niraj
Reply all
Reply to author
Forward
0 new messages