Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Mobile and Embedded
  4. Qt Android: How to call Toast.makeText from Java?
QtWS25 Last Chance

Qt Android: How to call Toast.makeText from Java?

Scheduled Pinned Locked Moved Unsolved Mobile and Embedded
12 Posts 3 Posters 6.5k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    Carmoneer
    wrote on last edited by Carmoneer
    #2

    You need to create a static instance of your main java class object and call the method that way. So in your 'JavaMain':

    public class MyJavaMain extends QtActivity {
    
        // Singleton Instance
        public  static MyJavaMain mInstance;
    
        ...
    
        public MyJavaMain () {
            Log.d(QtApplication.QtTAG, "Java constructor called.");
            mInstance = this;
        }
    
        ...
    
        public static MyMethodCallToast(final String message) {
             mInstance.runOnUiThread(new Runnable() {
                public void run() {
                   Toast.makeText(mInstance.getApplicationContext(),
                                  message,
                                  Toast.LENGTH_SHORT).show();
               }
            });
        }  
    }
    

    Hopefully that helps. Cheers!

    I 1 Reply Last reply
    0
    • C Carmoneer

      You need to create a static instance of your main java class object and call the method that way. So in your 'JavaMain':

      public class MyJavaMain extends QtActivity {
      
          // Singleton Instance
          public  static MyJavaMain mInstance;
      
          ...
      
          public MyJavaMain () {
              Log.d(QtApplication.QtTAG, "Java constructor called.");
              mInstance = this;
          }
      
          ...
      
          public static MyMethodCallToast(final String message) {
               mInstance.runOnUiThread(new Runnable() {
                  public void run() {
                     Toast.makeText(mInstance.getApplicationContext(),
                                    message,
                                    Toast.LENGTH_SHORT).show();
                 }
              });
          }  
      }
      

      Hopefully that helps. Cheers!

      I Offline
      I Offline
      Ibrahim
      wrote on last edited by
      #3

      @Carmoneer Thanks, I get this error:

      W/dalvikvm( 7847): Exception thrown (Ljava/lang/NullPointerException;) while throwing internal exception (Ljava/lang/NullPointerException;)
      W/InputMethodManagerService(  589): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@429dfe58 (uid=10170 pid=7847)
      

      NullPointerException error?

      1 Reply Last reply
      0
      • C Offline
        C Offline
        Carmoneer
        wrote on last edited by
        #4

        I think it may be an issue with the signature call on the .cpp side, specifically "(Ljava/lang/String;I)V". Try:

        QString toastMessage = "My message";
        QAndroidJniObject javaMessage = QAndroidJniObject::fromString(toastMessage);
        QAndroidJniObject::callStaticMethod<void>("com/app/myApp/MyJavaMain",
                                                  "MyMethodCallToast",
                                                  "(Ljava/lang/String;)V",
                                                  javaMessage.object<jstring>());
        
        I 1 Reply Last reply
        0
        • C Carmoneer

          I think it may be an issue with the signature call on the .cpp side, specifically "(Ljava/lang/String;I)V". Try:

          QString toastMessage = "My message";
          QAndroidJniObject javaMessage = QAndroidJniObject::fromString(toastMessage);
          QAndroidJniObject::callStaticMethod<void>("com/app/myApp/MyJavaMain",
                                                    "MyMethodCallToast",
                                                    "(Ljava/lang/String;)V",
                                                    javaMessage.object<jstring>());
          
          I Offline
          I Offline
          Ibrahim
          wrote on last edited by
          #5

          @Carmoneer Thanks, but I get same error again. This NullPointerException is text.

          1 Reply Last reply
          0
          • I Offline
            I Offline
            Ibrahim
            wrote on last edited by
            #6

            I tried:

            // ToastMessage.java file
            ...
            public static void makeText(final String text) {
                mInstance.runOnUiThread(new Runnable() {
                  public void run() {
                    Toast.makeText(mInstance.getApplicationContext(), "text", Toast.LENGTH_LONG).show();
                  }
                });
              }
            ...
            

            This code give error. I put the string ("text") but I get still NullPointerException error.

            1 Reply Last reply
            0
            • C Offline
              C Offline
              Carmoneer
              wrote on last edited by Carmoneer
              #7

              The only other thing I can think of is maybe because you have a separate 'Toast' class, it's calling that nullpointerexception. I don't have a separate class for my Toast calls.

              Maybe

              Toast.makeText(Classname.class, message, Toast.LENGTH_SHORT).show();
              

              is what you need to do?

              I simply import android.widget.Toast and make my Toast calls.

              I 1 Reply Last reply
              0
              • C Carmoneer

                The only other thing I can think of is maybe because you have a separate 'Toast' class, it's calling that nullpointerexception. I don't have a separate class for my Toast calls.

                Maybe

                Toast.makeText(Classname.class, message, Toast.LENGTH_SHORT).show();
                

                is what you need to do?

                I simply import android.widget.Toast and make my Toast calls.

                I Offline
                I Offline
                Ibrahim
                wrote on last edited by
                #8

                @Carmoneer My ToastMessage.java file:

                package com.classes.java;
                
                import org.qtproject.qt5.android.bindings.QtActivity;
                import android.widget.Toast;
                
                public class ToastMessage extends QtActivity {
                  public static ToastMessage mInstance;
                
                  public ToastMessage() {
                    mInstance = this;
                  }
                
                  public static String msg() {
                    return "<HELLO WORLD!>";
                  }
                
                  public static void makeText(final String text) {
                    mInstance.runOnUiThread(new Runnable() {
                      public void run() {
                        Toast.makeText(mInstance.getApplicationContext(), "text", Toast.LENGTH_LONG).show();
                      }
                    });
                  }
                }
                

                I want to learn how to call java codes from C++. Have you an example project for the android toast message?

                1 Reply Last reply
                0
                • C Offline
                  C Offline
                  Carmoneer
                  wrote on last edited by Carmoneer
                  #9

                  This is how I extend the framework for QtActivity:

                  package com.app.myapp;
                  
                  import org.qtproject.qt5.android.bindings.QtApplication;
                  import org.qtproject.qt5.android.bindings.QtActivity;
                  
                  
                  import android.widget.Toast;
                  
                  
                  /** --------------------------------------------------------------------------
                  ** @MyJavaNatives
                  ** Static methods called from .cpp side. Sends data to .cpp
                  ** -------------------------------------------------------------------------*/
                  class MyJavaNatives
                  {
                      public static native void showToast(final String message);
                  }
                  
                  /** --------------------------------------------------------------------------
                  ** @JavaMain (Only one class can extend QtActivity)
                  ** -------------------------------------------------------------------------*/
                  public class JavaMain extends QtActivity {
                      // Singleton Instance
                      public  static JavaMain mInstance;
                  
                      public JavaMain() {
                          Log.d(QtApplication.QtTAG, "Java constructor called.");
                          mInstance = this;
                      }
                  
                      // Called at the start of the full lifetime.
                      @Override
                      public void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          Log.d(QtApplication.QtTAG, "onCreate Called");
                      }
                  
                  
                      // Called at the start of the visible lifetime.
                      @Override
                      protected void onStart() {
                          super.onStart();
                      }
                  
                      // Called at the start of the active lifetime.
                      @Override
                      public synchronized void onResume() {
                          super.onResume();
                      }
                  
                      // Called at the end of the active lifetime.
                      @Override
                      protected synchronized void onPause() {
                          super.onPause();
                      }
                  
                      // Called at the end of the full lifetime.
                      @Override
                      protected void onDestroy() {
                          // Clean up any resources including ending threads,
                          // closing database connections etc.
                          super.onDestroy();
                      }
                  
                      // Called at the end of the visible lifetime.
                      @Override
                      protected void onStop() {
                          // Suspend remaining UI updates, threads, or processing
                          // that aren’t required when the Activity isn’t visible.
                          // Persist all edits or state changes
                          // as after this call the process is likely to be killed.
                          super.onStop();
                   
                      }
                  
                      // Called before subsequent visible lifetimes
                      // for an activity process.
                      @Override
                      protected void onRestart() {
                          // Load changes knowing that the activity has already
                          // been visible within this process.
                          super.onRestart();
                      }
                  
                  
                      /** ------------------------------------------------------------------------
                      ** @Toast
                      ** Show toast messge.
                      ** -----------------------------------------------------------------------*/
                      public static void showToast(final String message) {
                          mInstance.runOnUiThread(new Runnable() {
                             public void run() {
                                 Toast.makeText(mInstance.getApplicationContext(),
                                                message,
                                                Toast.LENGTH_SHORT).show();
                             }
                          });
                      }
                  }
                  

                  and then on the .cpp to call the message:

                              QAndroidJniObject::callStaticMethod<void>("com/app/myapp/JavaMain",
                                                                        "showToast",
                                                                        "(Ljava/lang/String;)V",
                                                                        QAndroidJniObject::fromString("This is my toast message!").object<jstring>());
                  

                  That is the basics to setting up a 'Main' java class that extends QtActivity. Hopefully that should at least steer you in the right direction. Good luck :)

                  I 1 Reply Last reply
                  0
                  • C Carmoneer

                    This is how I extend the framework for QtActivity:

                    package com.app.myapp;
                    
                    import org.qtproject.qt5.android.bindings.QtApplication;
                    import org.qtproject.qt5.android.bindings.QtActivity;
                    
                    
                    import android.widget.Toast;
                    
                    
                    /** --------------------------------------------------------------------------
                    ** @MyJavaNatives
                    ** Static methods called from .cpp side. Sends data to .cpp
                    ** -------------------------------------------------------------------------*/
                    class MyJavaNatives
                    {
                        public static native void showToast(final String message);
                    }
                    
                    /** --------------------------------------------------------------------------
                    ** @JavaMain (Only one class can extend QtActivity)
                    ** -------------------------------------------------------------------------*/
                    public class JavaMain extends QtActivity {
                        // Singleton Instance
                        public  static JavaMain mInstance;
                    
                        public JavaMain() {
                            Log.d(QtApplication.QtTAG, "Java constructor called.");
                            mInstance = this;
                        }
                    
                        // Called at the start of the full lifetime.
                        @Override
                        public void onCreate(Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                            Log.d(QtApplication.QtTAG, "onCreate Called");
                        }
                    
                    
                        // Called at the start of the visible lifetime.
                        @Override
                        protected void onStart() {
                            super.onStart();
                        }
                    
                        // Called at the start of the active lifetime.
                        @Override
                        public synchronized void onResume() {
                            super.onResume();
                        }
                    
                        // Called at the end of the active lifetime.
                        @Override
                        protected synchronized void onPause() {
                            super.onPause();
                        }
                    
                        // Called at the end of the full lifetime.
                        @Override
                        protected void onDestroy() {
                            // Clean up any resources including ending threads,
                            // closing database connections etc.
                            super.onDestroy();
                        }
                    
                        // Called at the end of the visible lifetime.
                        @Override
                        protected void onStop() {
                            // Suspend remaining UI updates, threads, or processing
                            // that aren’t required when the Activity isn’t visible.
                            // Persist all edits or state changes
                            // as after this call the process is likely to be killed.
                            super.onStop();
                     
                        }
                    
                        // Called before subsequent visible lifetimes
                        // for an activity process.
                        @Override
                        protected void onRestart() {
                            // Load changes knowing that the activity has already
                            // been visible within this process.
                            super.onRestart();
                        }
                    
                    
                        /** ------------------------------------------------------------------------
                        ** @Toast
                        ** Show toast messge.
                        ** -----------------------------------------------------------------------*/
                        public static void showToast(final String message) {
                            mInstance.runOnUiThread(new Runnable() {
                               public void run() {
                                   Toast.makeText(mInstance.getApplicationContext(),
                                                  message,
                                                  Toast.LENGTH_SHORT).show();
                               }
                            });
                        }
                    }
                    

                    and then on the .cpp to call the message:

                                QAndroidJniObject::callStaticMethod<void>("com/app/myapp/JavaMain",
                                                                          "showToast",
                                                                          "(Ljava/lang/String;)V",
                                                                          QAndroidJniObject::fromString("This is my toast message!").object<jstring>());
                    

                    That is the basics to setting up a 'Main' java class that extends QtActivity. Hopefully that should at least steer you in the right direction. Good luck :)

                    I Offline
                    I Offline
                    Ibrahim
                    wrote on last edited by
                    #10

                    @Carmoneer Ohh thanks. I tried this project, but it give same error:

                    W/dalvikvm(18212): Exception thrown (Ljava/lang/NullPointerException;) while throwing internal exception (Ljava/lang/NullPointerException;)
                    I/InputDispatcher(  589): Delivering touch to (18212): action: 0x0, toolType: 1
                    I/InputDispatcher(  589): Delivering touch to (18212): action: 0x1, toolType: 1
                    

                    I am sharing this project source codes: Project Source Codes.

                    1 Reply Last reply
                    0
                    • douywD Offline
                      douywD Offline
                      douyw
                      wrote on last edited by
                      #11

                      There is an android-extra example called 'notification' in Qt SDK examples. Just change the notify function in NotificationClient.java to display the toast. Maybe it will work.

                      I 1 Reply Last reply
                      0
                      • douywD douyw

                        There is an android-extra example called 'notification' in Qt SDK examples. Just change the notify function in NotificationClient.java to display the toast. Maybe it will work.

                        I Offline
                        I Offline
                        Ibrahim
                        wrote on last edited by
                        #12

                        @douyw thanks, I tried this method and it is work. Interesting! I do not understand. What is the problem? How can I learn it?

                        1 Reply Last reply
                        0

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved