How to show Dialog from a static method

android, android-context, cocos2d-x, dialog, java

Solution

Try adding the appropriate lines in Cocos2dxActivity:

public class Cocos2dxActivity extends Activity {
    private static Cocos2dxActivity instance = null;
   @Override public void onCreate(Bundle b) {
     ...
     this.instance = this;
     }

     public static Cocos2dxActivity getInstance() {
        return instance;
     }



}

When you want to create your dialog:

if (Cocos2dxActivity.getInstance() != null)  {
    AlertDialog dialog = new AlertDialog(Cocos2dxActivity.getInstance());
    // rest of your dialog code goes here
}

Problem

In my game, which is done for both Android and IOS using `cocos2dx`, I have to show video(for Android). I am planning to show it in Dialog(on top of game view). Problem is that, I don't have any Activity referenced to show Dialog(as Dialogs can only be shown in Activities). Even though, In cocos2dx lib folder, there is a `Cocos2dxActivity` but I am not getting how to make use of it. From C++ code, I am calling a static method from Java class as below ``` void LMJNICommunicator::showVideo() { LOGD("initialiseDatabase inside LMJNICommunicator"); jmethodID methodID = 0; JNIEnv *pEnv = 0; pEnv = getJNIEnv(); jclass ret = pEnv->FindClass("com/mobinius/lostmonstersclass/LMDatabaseDataManager"); methodID = pEnv->GetStaticMethodID(ret, "showVideo", "()V"); if (! methodID) { LOGD("Failed to find static method id of %s", "showVideo"); return; } pEnv->CallStaticVoidMethod(ret,methodID); pEnv->DeleteLocalRef(ret); } ``` Static method(which is in normal Java class) which I am calling from C++ code ``` Class LMDatabaseDataManager { public static void showVideo() { Dialog dialog = new Dialog(Cocos2dxActivity.getInstance()); dialog.show(); // getting Can't create handler inside thread that has not called Looper.prepare() error } } ``` I tried to make use of `Handler` like this but did not get result(got same error in that post). Also tried to get a static `Context` like this. So, is my way correct? If not correct, please suggest a way how can I implement the same. Thanks. Edit: Finally got answer for this. Earlier I tried running on UI thread with Application static context as in this link but did not get... with Cocos2dxActivity activity instance I got it. ``` Class LMDatabaseDataManager { public static void showVideo() { Cocos2dxActivity.getInstance().runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Dialog dialog = new Dialog(Cocos2dxActivity.getInstance()); dialog.show(); } }); } } ```

Original source

Related problems