invokeLater method

public final int invokeLater (Runnable runnable, long, boolean repeat) method

"puts the executable object into the queue of the application for the repeated execution"

That's great, but nobody knows how to stop the currently running thread?

Say for example:

UiApplication.getUiApplication () .invokeLater (new floor
{

public void run()
{
try {}

catch (Exception e) {}

}

(}, 50, true);

Since there is no direct reference to the executable object anonymous I can't find anyway to kill the thread after a certain condition has been reached.

Any ideas?

Thanx.

final int runnableId = app.invokeLater(runnable, 50, true);
...
app.cancelInvokeLater(runnableId);

Tags: BlackBerry Developers

Similar Questions

  • There the invokeLater cascading?

    Does anyone know if there is something similar to the cascading invokeLater method? I would after a few lines of code for execution after the main thread, if it is even logical in the context of the Cascades.

    Here's my background: I have a fairly complex list and a user operation can cause two major changes to the ListView. I want to 'break them up' from the user point of view, if the code runs each after the other it looks a little too quickly. Ideally, I would like to make one then the other one a fraction of a second later.

    You can use a QTimer, for example.

  • In another thread - another method and then run Sub...

    I wrote a method to extract a string from a webpage using StreamConnection and it works perfectly... except that it runs on the main thread.  I wonder if there is a simple way to have a method that returns an object (String in this case) something to run on a thread and return it to the first thread.

    Everything I try the only thing I can get to work on the second thread is what's on the run method void, but that returns nothing... because it sucks...

    Until now what I thought is to pass the variables I need in the constructor, then set the connection stream real term where I want retruned is written in a class variable and another method that returns the class variable that has been filled with the run method... but that doesn't seem to just... thought he worked in a simple test I ran...

    A slightly different way (but completely equivalent) to work in a another thread is to create a class that implements Runnable and feed a thread. If, for any reason, you do not want to expand Thread (because your worker class extends already something else and it would be difficult to refactor), then this variant is a lifeline. You do something like this:

    class WorkerClass extends AnotherClass implements Runnable {    // ...    public void run() {       // do time-consuming work here    }}
    
    // later...WorkerClass worker = new WorkerClass();// initialize worker object. Then: new Thread(worker).start();
    

    As it is easy to turn a class in an executable (you simply add "implements Runnable" and a run() method), it's an easy way to avoid the subclassing Thread.

    Regardless of how you use to perform work in a separate thread, there is always the question of how to get the results. With the help of the observer is a common way to handle this, but in general, this means that the results are returned in the worker thread, not the thread from the main event. If you want to update the user interface, this can be a problem. Another approach is to structure your code something like the following:

    /** * Process the results of some time-consuming operation. */public void acceptResults(ResultType result) {  // ...}
    
    /** * Start a thread to carry out time-consuming work in a * separate thread and deliver the results back in the * event dispatching thread. */public void launchWork() {  new Thread() {        public void run() {           final ResultType res = computeResults();          Runnable r = new Runnable() {                public void run() {                   acceptResults(res);               }         }         Application.getApplication().invokeLater(r);      }
    
           /**        * Do time-consuming work in this method       */       private ResultType computeResults() {         // connect to server, interpret reply, etc.       } }.start();}
    

    You have the right idea that is running in a thread separate is how to manage a time consuming task. The point of all, however, is that you (the event dispatching thread) don't want to wait for the task at hand. Both the observer model and the code here offer a solution for a worker thread to do the work without blocking the thread of the event. The invokeLater() method was kindly provided by BlackBerry people to give the worker threads neatly transfer control on the event dispatching thread when needed.

  • How can I update the UI without encountering a ' Application is not responding do not; completed process '?

    I'm trying to populate a table on the screen, and when the user clicks a Labelfield (20 lines are populated by click).

    When the user clicks the labelfield, following takes place:

    (1) a data segment is read from the SQLite database in a background thread.

    (2) data are then filled in the existing table on the screen (by adding more fields to the Table Layout Manager) in the invokeLater() method.

    I am currently facing a problem of ' Application is not responding do not; process is completed ' when I continue to load more items to say about 3 to 4 times (i.e. After about 60 to 80 lines are met).

    I fear that this could be caused by the user interface thread get resisted for a long time, while the population takes place. Is there another way to update the user interface, so that the application runs smoothly?

    I'd appreciate any help that I had with this problem for some time.

    You must use another thread to query the database and then creating and filling in the fields. After the creation of fields use the Manager.addAll () method to add an array of fields (in invokeLater() body of course).

  • ListField images update

    Hello

    I have a ListField, who I am complete with JSON data analyzed a HTTPConnection. Each line of this ListField has an image. I need to get each image on the server (I have the url in the data analyzed) so I need to establish an additional connection in each line for this. Who should be the right method to do this? I guess I should NEVER try to retrieve the images in the same invokeLater() method which is holdind the thread of events (and creating the ListField with data retrieved from the server and by attaching it to the screen), otherwise, this may cause my app go very slowly.

    Any ideas? Thanks in advance!

    Joan

    "the entire ListField" is actually only a reference to a. It's actually how to Java - only non-object privitives (such as int, char, long, etc.) are passed around in its entirety. The rest are represented and accessed through references. So don't worry - you don't carry huge amounts of memory wire to wire with your references ListField .

    Overall, you have two models of design working here - producer-consumer and publication / subscription. Your ListField is a producer of "download requests", which are consumed - one - by the download thread. However, the ListField subscribed (by providing his reference and, say, the line index, within the "download request") to the "full download" events that are published by the download thread.

    Moreover, you don't need nets more for it - the UI Thread (also called wire event, see ""that is the event Thread?"for reference") and the download Thread are everything you need here.

    If you want any kind of "load-balancing", however, you can create a download thread dispatcher and two or more threads of work for download.

  • 3 seconds delay after the application icon was clicked...

    I can't understand the following situation:

    When I I click on my blackberry application icon (in the Simulator), the application is fast, no problem. However, when I take that same code and place it on my blackberry, there are a few seconds of waiting time after that the icon has been clicked.

    can someone tell me how to reduce the delay? the first screen is nothing else than an image within an image field. I wanted to create a "splash" screen and I just show you a simple picture.

    After I click on the icon of the application (on my phone), I notice that there is activity because you see the arrows at the top right moving. but the user regular to non-techie, they do not know that the application has been started and they will just keep clicking on the icon over and over again.

    again, I click on the application icon and there are about 3 seconds just to show the image contained in the file of the project. If we're not going get the image from a remote site.

    the Simulator shows the quick image, but the phone creates a delay. any ideas how to minimize the delay on the application icon, click on?

    Thank you.

    CA

    I thought about it. I just moved the instantiation and several objects of a different class loading and later called these lines of code with an invokeLater method. My first screen contains only the image itself and the other class the rest of the code.

  • TouchEvent exception on vary basic app (9550 sim)

    I have recently interested in programming again and decided to start with the programming of blackberry. I get errors immediately the bat which is not encouraging, but I was hoping someone could help me.

    I created a basic "Getting Started"-based application first tutorial app. I added then added a button and a listener of field for this button that displays an alert dialog box. Very simple, but in my Simulator (9550) I get a runtime exception which stops at "TouchEventInternal.getGlobalX (int). This happens when I click 'OK' on the alert dialog.

    Here is the Stack Trace:

    Thread [Checklist(176)id=295857152] (Suspended (exception RuntimeException))
        TouchEventInternal.getGlobalX(int) line: 222
        ChecklistScreen(Screen).dispatchTouchEvent(TouchEvent) line: 1010
        UiEngineImpl.processMessage(Object, Message, boolean) line: 3388
        Checklist(Application).doProcessNextMessage(Message) line: 2268
        Checklist(Application).processNextMessage(Message) line: 1530
        Checklist(Application).enterEventDispatcher() line: 1371
        Checklist.main(String[]) line: 11
    

    And here is my Code:

    CheckList.java:

    package com.rim.samples.checklist;
    
    import net.rim.device.api.ui.UiApplication;
    
    public class Checklist extends UiApplication
    {
    
        public static void main(String[] args)
        {
            Checklist theApp = new Checklist();
            theApp.enterEventDispatcher();
        }
        public Checklist()
        {
            pushScreen(new ChecklistScreen());
        }
    }
    

    ChecklistScreen.java:

    package com.rim.samples.checklist;
    
    import java.util.*;
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.container.MainScreen;
    import net.rim.device.api.ui.component.*;
    
    public final class ChecklistScreen extends MainScreen
    {
        public ChecklistScreen()
        {
            super();
            ButtonField button = new ButtonField("Add New");
            FieldChangeListener action = new FieldChangeListener(){
                public void fieldChanged(Field field, int context)
                {
                    Dialog.alert("YOU PUSHED A BUTTON");
                }
            };
            button.setChangeListener(action);
            add(button);
        }
        public boolean onClose()
        {
            Dialog.alert("Cya!");
            System.exit(0);
            return true;
        }
    }
    

    Any help or advice would be appreciated

    Micah_H Hey!

    I guess you need to access the UI event handling, since it seems that you are outdoors. For example, you can use invokeLater () methods or invokeAndWait ().

    UiApplication.getUiApplication().invokeLater(new Runnable(){
        public void run() {
            Dialog.alert("YOU PUSHED A BUTTON");
        }
    });
    

    The other alternative is to set the CONSUME_CLICK function to your button:

    ButtonField button = new ButtonField("Add New", ButtonField.CONSUME_CLICK);
    

    Anyway, honestly, I surprised when your code works on previous 9530 Simulator. I don't know why!

    Kind regards

    Klerisson

  • InvokeLater Eclipse flags as undefined

    I try to make the LBS_LAB (location and GPS) laboratory works, using the ecliptic and 4.5 of the API.

    The test application has two classes, the class of the main application and the class LBS_LAB. The main passage is a pushScreen (new LBSScreen());

    The invokeLater is in a method:

    Public Sub log (final String msg) {}
    invokeLater (new Runnable() {}
    public void run() {}
    _logField.SetText (_logField.GetText () + "\n" + msg);
    }
    });
    }

    The project generates no locks Eclipse complains "invokeLater is undefined for the type of LBSScreen.

    Any ideas what I am doing wrong?

    invokelater is a method of application, not the screen.

    You can use UiApplication.getUiApplication () .invokeLater in many cases

  • Guard application launch at the start of the appliance, also need advice for the implementation of network methods

    Hi all

    I'm new to the development of Blackberry and I'm writing a relatively simple application to run on 7.1.

    So far the development was interesting, I managed to create my user interface using resources online (mainly this forum), but today I tried to implement some of the network classes that I need and now I just met constant problems.

    I use Eclipse SDK 3.7.2 (the one that comes with the plugin RIM)

    First question:

    I'm not sure what I changed, but today I noticed that whenever I start the Simulator (by sim 9360) my application is started during the initial startup process. I don't think he did this before, but to be honest, I wasn't paying much attention. I think it starts at the start of the device is because I put a breakpoint in the constructor for my class from the main screen, which is hit before the Simulator happens even to the point where it is ready for user interaction. In addition, once it is ready, if I press the BB button, I see my registered application.

    I don't have it set to automatic start in .xml descriptior enforcement.

    I started this application on the HelloBlackBerry sample, here is my main method for the entry of the application:

    public static void main( String[] args ) {
            appSettings = AppSettings.fetch();
            // Create a new instance of the application and make the currently
            // running thread the application's event dispatch thread.
            HelloBlackBerry theApp = new HelloBlackBerry();
            theApp.enterEventDispatcher();
            //openConnection();
    
        }
    
    
    

    As far as I know, this is the only entry point for the application.

    More code

        public HelloBlackBerry() {
            // Push a screen onto the UI stack for rendering.
            mainScreen = new ScreenHelloBlackBerry();
            pushScreen( mainScreen );
        }
    

    Here is the method of. my class AppSettings fetch()

        // Retrieves a copy of the effective properties set from storage.
        public static AppSettings fetch()
        {
            AppSettings savedSettings = (AppSettings) _store.getContents();
            return new AppSettings(savedSettings);
        }
    

    Some of this code that I wrote myself, the persistence store cause the launch of my car?

    I tried to reset the Simulator to the factory settings, no change.

    All applications initialized during the startup of the device and then closed shortly after?

    Part 2: Need advice for the implementation of functions of network in the application

    I need to implement some methods that will retrieve data from a web service, and I also need to send data to this service. What I've read, the ConnectionFactory is the way to go. I want my application to make a request when the application is open and can check on a set interval. I didn't know exactly how to go about adding another thread for networking, I understand that network connections should not be created on the thread main event, so I tried to do this:

    The constructor of my class that implements screen (ScreenHelloBlackBerry), I use the following to create a modal dialog box to prompt the user for a username, I also try networking wire in the same segment of spawning:

            public ScreenHelloBlackBerry(){...initialize fields and managers, add it all together...then near the end
    
    //This will open the confirm dialog when the application is launched
            UiApplication.getUiApplication().invokeLater(new Runnable() {
                  public void run() {
                      openConfirmDialog();
                    //start connection - Possibly broken
                      ConnectionThread ct = new ConnectionThread();
                      ct.start();
                  }
            });
    

    I don't know if it's somehow OK to do, but it seems to work for what I need. I want a user who launches the application at the prompt, and if a user switch applications, when they come back they wondered again (unless they close the app and reopen it).

    Here is my ConnectionThread:

    public class ConnectionThread extends Thread
    {
    
        public void run()
        {
    
              ConnectionFactory connFact = new ConnectionFactory();
              ConnectionDescriptor connDesc;
              connDesc = connFact.getConnection("http://www.google.com");
              if (connDesc != null)
              {
                  HttpConnection httpConn;
                  httpConn = (HttpConnection)connDesc.getConnection();
                  try
                  {
                      final int iResponseCode = httpConn.getResponseCode();
                      UiApplication.getUiApplication().invokeLater(new Runnable()
                      {
                          public void run()
                          {
                              Dialog.alert("Response code: " +
                                            Integer.toString(iResponseCode));
    
                          }
                       });
                      httpConn.close();
    
                   }
                   catch (IOException e)
                   {
                     System.err.println("Caught IOException: "
                          + e.getMessage());
                   }
              }
        }
    }
    

    At the moment it has basically unmodified code from a sample that I found, I'll be retooling to meet my needs whenever I can make it work. I HAD this work to the point where, after the closed user confirm this dialog, a few moments later a an alert dialog appears with the 302 response code. I don't know what changed, but now it doesn't work at all, and if I try to scroll with the debugger, I can't past the httpCon.getResponseCode (). I've seen some mistakes earlier on "no record of service was set up", and I also had once a timeout exception.

    I'm sure I'm doing this wrong, but at the same time as I said WAS working, and now it is not. If someone has done this far, thank you very much for your time and advice are much appreciated.

    Also, should I try to start the thread of the network of the UIApplication class instead of the screen? There is currently very little happening in the class that extends UIApplication, do I spend most of my business logic out of the class of the screen and in the UIApplication class?

    Thanks in advance!

    Hi all

    Just to conclude this topic for those who are interested, I found an excellent guide to the implementation of networks in applications of BB, click here for a link.

    About my application being started at the start of the simulator of the device, I found that on a device real this behavior is not complied with, and in addition, the behaviour seems to have stopped after uninstallation and reinstallation of my Simulator.

    See you soon,.

  • Application.invokeLater (Runnable) in Focus event handlers

    Several code examples use Application.invokeLater (Runnable) in onFocus and onUnfocus methods:

    protected void onUnfocus() {}

    -For example, a user rolling the trackball / slips the trackpad and the system decides that it is time to activate another area.  At this point, the system checks and invokes all sorts of methods - one of them is Field.removeFocus () that must call onUnfocus() in this area. If unUnfocus() is called when the system is not yet completed this transfer of focus. It might not be all-terrain with focus, just a 'right' to receive the focus.

    Or take the case when a new screen is pushed. This new screen has not been painted yet, the system has not yet checked if she has any field focusable, etc. - but your onUnfocus() is already known. Is it not strange that you'd better to be careful and annex an action after the dust has settled offshore?

  • Dialog box in the paint method

    I have an IllegalStackSizeException when I try to display a dialog box in the paint method.

    Here is an example:

    [Edit] Welcome to the forums! [/ Edit]

    Do you really need that Dialog.inform there? It's a very bad idea to have one any initiated interaction in paint, because it is called at unpredictable times. Worse still is the idea to execution of the painting of the block .

    If you absolutely, desperately need some user interface action will be initiated by paint (and frankly, you don't want to do), put it in invokeLater. Even if the painting is performed on the EventThread, you must leave the BB frame finish his current job, then come back and do something new.

    Dialog.Inform is a nice debugging tool, but it has its limits. You simply press one.

  • How to call this method?

    I wrote this method earlier, but I do not remember how to call it. Can someone help me?

    public class PostReview extends Thread {
        String _url = new String();
    
        public void Submit(String _url) {
            ConnectionFactory connFact = new ConnectionFactory();
            ConnectionDescriptor connDesc;
            connDesc = connFact.getConnection(_url);
            if (connDesc != null) {
                HttpConnection httpConn;
                httpConn = (HttpConnection)connDesc.getConnection();
                try {
                    final int iResponseCode = httpConn.getResponseCode();
                    UiApplication.getUiApplication().invokeLater(new Runnable()
                    {
                    public void run() {
                        //Dialog.alert("Response code: " + Integer.toString(iResponseCode));
                    }
                    });
                } catch (IOException e) {
                    Dialog.alert("Caught IOException: " + e.getMessage());
                }
            }
        }
    }
    

    You can simply call News PostReview.Submit (url). But why the class extends Thread If you aren't actually create or who runs an instance of thread?

  • Start a new Thread in the activate() method

    Hello

    When my application is started or resumed after a phone call etc... I would like to perform some tasks in the activate() method. First of all, I would like to start a new Thread to call web services a bit, and when it's done, I would like to update the user interface.

    I tried to do. I created a new class that extends the Thread in the run() method, I placed all the relevant web service calling and code in the method activate() my main thread that I have done:

    MyThread myThread = new MyThread();

    myThread.start ();

    But I noticed that nothing seems to be done. So I simplified my code by removing all web service of the run() method calls and replaced by a wait method (500), followed by a method call to update the user interface (in this case it creates just a new ButtonField, just for testing purposes).

    But ButtonField never gets created.

    The new thread doesn't seem to be from all.

    Any suggestions?

    Thank you very much.

    Have you tried setting stop and monitoring of execution points using println?

    First of all, is called same activate()?

    Secondly, run() is reached?

    When the thread does the work of the user interface, if you have that in a synchronized block try block invokeLater rather.

  • Unable to detect the rotation of the device of the method of sublayout of screen

    I'm developing an application compiled for OS 4.5. I need to find a way to detect the rotation of the unit and again fill the screen so that the fields are arranged according to the new dimensions.

    My idea was to save the display width and height in some private variables in my case screen and method of sublayout overloaded screen, check if the new values have been changed.

    What happens is that I get the old width and height again and again.

    I first read this post. In this document, @arkadyz points out how the order of the calls is a little weird and values returned by the view class are updated after sublayout is finished.  Therefore, there is no way to detect by the sublayout method.

    The proposed solution is to check the dimensions of the display within an invokeLater. Here's my test code:

    public class TestScreen extends MainScreen {
    
        public TestScreen(){
            super(Manager.NO_VERTICAL_SCROLL);
            populateScreem();
        }
    
        private void populatescreen(){
            deleteAll();
            //fields and containers added here. No need to add any to observe the issue.
        }
    
        public void sublayout(int width, int height){
            super.sublayout(width,height); //Tried calling this in the last line as well with identical result.     
    
            System.out.println(">>>>>>>>> Display.getWidth(before): " + Display.getWidth());
            System.out.println(">>>>>>>>> Display.getOrientation(before): " + Display.getOrientation());
            System.out.println(">>>>>>>>> Width argument value (before): " + width);
    
            UiApplication.getUiApplication().invokeLater(new Runnable(){
                public void run() {
    
                    System.out.println(">>>>>>>>> Display.getWidth(later): " + Display.getWidth());
                    System.out.println(">>>>>>>>> Display.getOrientation(later): " + Display.getOrientation());
                }
            }, 1000, false); //Playing with the time parameter does not change behavior.
        }
    }
    

    This gives exactly the same results. After that, I came to this post where @peter_strange

    provides a solution based on pushing a dummy screen, which detects the new width and height, and then passing the new values to the previous screen. I also tried, but it didn't work either.

    I also tried using the obsolete Graphics.getscreenWidth instead of Display.getWidth, and it did not work.

    Now, I am out of luck because I have almost tried everything and I can't provide a solution without resorting to the 4.7 or 6.0 API.

    Tested in BB 9550 Simulator v5.0.0.535 (Platform 2.13.0.108) and v5.0.0.306 real unit BB 9520 (Platform 4.2.0.113)

    Take a look at the following.  In my view, the following code can be used to detect changes in orientation.

    public class TestScreen extends MainScreen {
    
        int currentDisplayWidth = Display.getWidth();
        int currentDisplayOrientation = Display.getOrientation();
    
        public TestScreen(){
            super(Manager.NO_VERTICAL_SCROLL);
            populatescreen();
        }
    
        private void populatescreen(){
            deleteAll();
            //fields and containers added here. No need to add any to observe the issue.
        }
    
        public void sublayout(int width, int height){
            super.sublayout(width,height); //Tried calling this in the last line as well with identical result.     
    
            System.out.println(">>>>>>>>> Current sublayout width (before): " + currentDisplayWidth);
            System.out.println(">>>>>>>>> Display.getWidth(before): " + Display.getWidth());
            System.out.println(">>>>>>>>> Display.getOrientation(before): " + Display.getOrientation());
            System.out.println(">>>>>>>>> Width argument value (before): " + width);
            if ( Display.getWidth() != currentDisplayWidth ) {
                // process orientation change
                // ....
                // Now reset change detection variables.....
                currentDisplayWidth = Display.getWidth();
                currentDisplayOrientation = Display.getOrientation();
            }
        }
    }
    
  • getLocation() method cannot be called from event thread

    Hello

    I use a thread that runs an executable object, which gets gps location. This thread is called in the constructor of the form. The first time, it works fine, but then I get the error getLocation.

    class GetGPSThread extends Thread
    {
    GPSRunnable _gpsObject;
         
    GetGPSThread()
    {
    _gpsObject = new GPSRunnable();
    }
         
    public void run()
    {
    _gpsObject.run ();
          
    While (! _gpsObject.isFinished ())
    {
    try {}
    Sleep (200);
    } catch (InterruptedException e) {}
    Generative TODO catch block
    e.printStackTrace ();
    }
    }
          
    Renew the screen
    If (_gpsObject.getLatitude ()! = 0 & _gpsObject.getLongitude ()! = 0)
    {
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run()
    {
    loadScreen (_gpsObject.getLatitude (), _gpsObject.getLongitude ());
    }
    });
    }
    on the other
    {
    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run()
    {
    Dialog.Alert ("your position not found");
    }
    });
            
    }
         
    }
         
    }

    "This thread is called in the constructor of the screen".

    We see this code in your constructor?.

    I guess you really want to say this thread is 'start '.  Don't forget that

    . Run()

    does not run a Thread, it executes the run() method in the Thread.  To start a separate Thread, you must use

    . Shart().

Maybe you are looking for