HomeScren.supportsIcons () throws a RuntimeException

When the following code is executed on a device or a simulator with OS 6.0 that has an active theme with a GIF animated for the bottom of the home screen, a RuntimeException ' Index 1 > = 1 ' is thrown:

try {
    updateIcons();
} catch (RuntimeException e) {
    Logger.logError("Runtime exception: " + e.getMessage());
}
private void updateIcons() {
    Logger.logDebugInfo("updateIcons");

    if (HomeScreen.supportsIcons()) {
        Logger.logDebugInfo("The current theme supports icons");
        HomeScreen.updateIcon(Bitmap.getBitmapResource("Main Icon.png"), 0);
        Logger.logDebugInfo("main icon updated");
        HomeScreen.setRolloverIcon(Bitmap.getBitmapResource("Main Icon Active.png"), 0);
        Logger.logDebugInfo("rollover icon set");
    } else {
        Logger.logDebugInfo("The current theme does not support icons");
    } 

    Logger.logDebugInfo("End of updateIcons");
}

The recorder is a wrapper class for net.rim.device.api.system.EventLogger.

The output of the code above in the event log is:

updateIcons
Runtime exception: Index 1 > = 1

If I remove the "if (HomeScreen.supportsIcons ()) ' line and the line"else", all right:

updateIcons
The current theme is supported by the icons
main icon updated
Turning icon set
End of updateIcons

I ran the code snippet at the start of the application, on the application of another point of entry starts and the menu command, click on and the result was always the same.

I created the application with BlackBerry Plugin for Eclipse Eclipse 3.4 (for BB OS4.7) v1.2, then I tried with BlackBerry Plugin for Eclipse v1.3 in Eclipse 3.6 (for BB OS6), but there was no difference in the behavior of HomeScreen.supportsIcons () on OS6.0 - he always threw a RuntimeException if the active theme had specified a theme animated for the bottom of the home screen.

The exception is thrown when the background is an animated GIF (no matter how it has been set to loop - forever or just once), but never when it's a static image or a slideshow.

So, I wonder if the supportsIcons check is really important and what would happen if the code is run on a device that uses a theme without icons (I have personally never met such person).

And, of course, my big question is: is this a bug or I do something wrong?

Thanks for the themes of the sample.  I was able to reproduce using them.  I reported this problem to our development team and it connected Issue Tracker here: https://www.blackberry.com/jira/browse/JAVAAPI-1796

Tags: BlackBerry Developers

Similar Questions

  • Odd screens RuntimeException

    Using Eclipse, targeting devices and better 8330, OS 4.5 & better...

    import java.util.Vector;
    import net.rim.device.api.ui.UiApplication;
    
    public class ScreensApp extends UiApplication {
    
        public static Vector screenV;
    
        public ScreensApp() {
            screenV = new Vector();
            pushScreen( new Screens2() );
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ScreensApp app = new ScreensApp( );
            app.enterEventDispatcher(); //point of no return
        }
    
    }
    
    import net.rim.device.api.ui.component.Dialog;
    import net.rim.device.api.ui.component.LabelField;
    import net.rim.device.api.ui.container.MainScreen;
    
    public class Screens2 extends MainScreen {
    
            public Screens2() {
    
                if (ScreensApp.screenV.isEmpty()) {
                    try {
                        Dialog.alert("screenV is empty!");
                    } catch ( RuntimeException e) {
                        System.out.println(  e.toString() );
                    }
                }
    
                LabelField label = new LabelField( "screens2 label" );
                add( label );
    
            }
    }
    

    These two classes are the essence of a problem, in that I am running.  I'm developing a simple, single-threaded (no requirement of network) application. The dialog box throws a RuntimeException [1], and I don't know why.  As Screens2 is pushed in the screen of ScreensApp stack and not running in parallel with ScreensApp, I thought he had run on the thread of the event and I wouldn't need to use invokelater or syncronize to get alert dialog to display.  If it's wrong, can someone please explain why (and how) that became a multi-threaded application (or whatever else happens to cause the RuntimeException)? Thank you in advance!

    [1] the error is "java.lang.RuntimeException: pushModalScreen called by a thread of non-event."

    Your problem is that you are trying to instantiate a modal dialog (your alert dialog box) to the constructor of the class Screens2. At the time when this constructor is running, the application has not yet entered the event dispatcher.

    The app is not in the dispatcher of events up to this after the Screens2 object is instantiated.  Get rid of the Dialog.alert here in the constructor.

  • Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver


    Dear Sir


    I have this problem to connect the JAVA oracle database. I use Eclipse March, here is my code:

    package db;

    import java.sql.Connection;

    to import java.sql.DriverManager;

    import java.sql.SQLException;

    public class {ConnectionFactory

    public static {connection getConnection()

    try {}

    Class.forName ("oracle.jdbc.OracleDriver");

    return DriverManager.getConnection ("jdbc:oracle:thin:@myhost:1521:orcl", "scott", "Tiger");

    } catch (ClassNotFoundException |) SQLException e) {}

    throw new RuntimeException (e);

    }

    }

    Public Shared Sub main (String [] args) {}

    Connection connection = ConnectionFactory.getConnection ();

    System.out.println ("Conexao criada com sucesso.");

    try {}

    Connection.Close;

    } catch (SQLException e) {}

    e.printStackTrace ();

    }

    }

    }

    Belown the error:

    Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver

    DB. ConnectionFactory.getConnection (ConnectionFactory.java:14)

    DB. ConnectionFactory.main (ConnectionFactory.java:19)

    Caused by: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver

    at java.net.URLClassLoader.findClass (unknown Source)

    at java.lang.ClassLoader.loadClass (unknown Source)

    to Sun.misc.Launcher$appclassloader$ AppClassLoader.loadClass (unknown Source)

    at java.lang.ClassLoader.loadClass (unknown Source)

    at java.lang.Class.forName0 (Native Method)

    at java.lang.Class.forName (unknown Source)

    DB. ConnectionFactory.getConnection (ConnectionFactory.java:11)

    ... 1 more

    Someone help me, please?

    Thank you

    Jurandyr F. Alves

    A ClassNotFound exception means just what it says: it can't find this class.

    Make sure that the ojdbc7.jar file is in your classpath.

  • Virtual keyboard hides part of the change to the field

    Hello

    I have a labelfield, field change and a button that are centered aligned vertically. The three fields, I added in a Verticalfield Manager which is then added to a horizontal region Manager. And finally the HFM is added to an another value for money. Now in the 9800 device or curve 9380, I noticed that when I touch the edit field, virtual keyboard is coming. And he hides the field partially change.

    I want to move things to the top when the virtual keyboard appeared. How can I do. My code is here:

           HorizontalFieldManager hfm = new HorizontalFieldManager();
            VerticalFieldManager vfmComponent = new VerticalFieldManager(USE_ALL_WIDTH);
            vfmComponent.add(lfServerUrl);
            vfmComponent.add(mEfURL);
            vfmComponent.add(mBtnSave);
            hfm.add(vfmComponent);
            int topEmptySpace = (Display.getHeight() - (Bitmap.getBitmapResource(mStrTopBar).getHeight() + hfm.getPreferredHeight() + 25)) / 2;
            hfm.setMargin(topEmptySpace, 0, 0, 0);
            VerticalFieldManager vfmMain = new VerticalFieldManager(VERTICAL_SCROLL| NO_HORIZONTAL_SCROLL );
            vfmMain.add(hfm);
            add(vfmMain);
    

    Help, please.

    When you start to need as many managers to get the look you want, then you know that you should really create your own Manager.

    These two should help you to do:

    http://supportforums.BlackBerry.com/T5/Java-development/how-to-extend-Manager/Ta-p/446749

    http://supportforums.BlackBerry.com/T5/Java-development/create-a-custom-layout-manager-for-a-screen/...

    For example, I hacked together a "centeringManager" and the screen, which should do what you want.  But please use this as a reference sample, understand what he does and maybe even improve it.

    In production code, I would really remove the centeredManager and centering Manager across all fields and place them, but then you must code a manager which includes margins, which would confuse the point of this example - as a basic implementation of a Manager.

    Hope it's what you want.

    public final class CenteringScreen extends MainScreen {
    
        /**
         * verticallyCenteringManager takes one Field and positions it
         * centered in the space it has.
         */
        VerticalFieldManager centeringManager = new VerticalFieldManager() {
            protected void sublayout(int maxWidth, int maxHeight) {
                if ( this.getFieldCount() > 1 ) {
                    throw new RuntimeException("Expecting only one Field or Manager to be added");
                }
                if ( this.getFieldCount() == 1 ) {
                    Field f = this.getField(0);
                    layoutChild(f, maxWidth, maxHeight);
                    int requiredTopMargin = (maxHeight - f.getHeight())/2;
                    int requiredLeftMargin = (maxWidth - f.getWidth())/2;
                    setPositionChild(f, requiredLeftMargin, requiredTopMargin);
                    setExtent(maxWidth, maxHeight);
                } else {
                    setExtent(0, 0);
                }
            }
        };
    
        /**
         * Fields added to centeredManager will be displayed 'centered' vertically
         * regardless of orientation of screen and presence or absence
         * of virtual keyboard
         */
        VerticalFieldManager centeredManager = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL | VerticalFieldManager.VERTICAL_SCROLLBAR);
    
        // Sample Fields to be added
        ButtonField sampleButton = new ButtonField("Button", ButtonField.FIELD_HCENTER);
        LabelField sampleLabel = new LabelField("Label", LabelField.FIELD_HCENTER);
        BasicEditField sampleBef = new BasicEditField("Text", "", 255, BasicEditField.FIELD_HCENTER);
    
        public CenteringScreen() {        
    
            super(Manager.NO_VERTICAL_SCROLL); // very important
            // The NO_VERTICAL_SCROLL means that the only Manager added to this Screen - centeringManager -
            // will be given as its maxHeight, the available screen height, regardless of
            // orientation or whether there is a virtual keyboard displayed
    
            // add Fields to centeredManager
            centeredManager.add(sampleButton);
            centeredManager.add(sampleLabel);
            centeredManager.add(sampleBef);
            centeringManager.add(centeredManager);
            this.add(centeringManager);
    
        }
    
    }
    
  • BrowserField encoding problem

    Hello! Please, help me! I spent almost all day, but have had no success. My BrouserField is showing '? ' characters instead of the non-English characters.
    I need to get the Ribbon XML, analyze and display in the BrowserFiled.
    I use these classes:

    (1) WaitScreen - PopupScreen from the example of knowledge base

    public class WaitScreen extends PopupScreen {
    
        private LabelField _ourLabelField = null;
    
        private WaitScreen(String text) {
            super(new HorizontalFieldManager());
            VerticalFieldManager _vfm = new VerticalFieldManager();
            _ourLabelField = new LabelField(text, Field.FIELD_HCENTER);
            _vfm.add(_ourLabelField);
            this.add(_vfm);
            this.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 225));
        }
    
        public static void showScreenAndWait(final Runnable runThis, String text) {
            final WaitScreen thisScreen = new WaitScreen(text);
            Thread threadToRun = new Thread() {
                public void run() {
                    // First, Waintdisplay this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().pushScreen(thisScreen);
                        }
                    });
                    // Now run the code that must be executed in the Background
                    try {
                        runThis.run();
                    } catch (Throwable t) {
                        t.printStackTrace();
                        throw new RuntimeException("Exception detected while waiting: " + t.toString());
                    }
                    // Now dismiss this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().popScreen(thisScreen);
                        }
                    });
                }
            };
            threadToRun.start();
        }
    }
    

    (2) RSSHandler - class auxiliary for analysis

    public class RSSHandler extends DefaultHandler {
        boolean isItem = false;
    
        boolean isTitle = false;
        boolean isLink = false;
        boolean isDescription = false;
        boolean isPubDate = false;
        boolean isGuid = false;
    
        public String[] title = new String[] {};
        public String[] link = new String[] {};
        public String[] description = new String[] {};
        public String[] pubDate = new String[] {};
        public String[] guid = new String[] {};
        String value = "";
    
        public void startElement(String uri, String localName, String name,
                Attributes attributes) throws SAXException {
            if (!isItem) {
                if (name.equalsIgnoreCase("item"))
                    isItem = true;
            } else {
                if (name.equalsIgnoreCase("title"))
                    isTitle = true;
                if (name.equalsIgnoreCase("link"))
                    isLink = true;
                if (name.equalsIgnoreCase("description"))
                    isDescription = true;
                if (name.equalsIgnoreCase("pubDate"))
                    isPubDate = true;
                if (name.equalsIgnoreCase("guid"))
                    isGuid = true;
            }
        }
    
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            if (isTitle || isLink || isDescription || isPubDate || isGuid)
                value = value.concat(new String(ch, start, length));
        }
    
        public void endElement(String uri, String localName, String name)
                throws SAXException {
            if (isItem && name.equalsIgnoreCase("item"))
                isItem = false;
            if (isTitle && name.equalsIgnoreCase("title")) {
                isTitle = false;
                Arrays.add(title, value);
                value = "";
            }
            if (isLink && name.equalsIgnoreCase("link")) {
                isLink = false;
                Arrays.add(link, value);
                value = "";
            }
            if (isDescription && name.equalsIgnoreCase("description")) {
                isDescription = false;
                Arrays.add(description, value);
                value = "";
            }
            if (isPubDate && name.equalsIgnoreCase("pubDate")) {
                isPubDate = false;
                Arrays.add(pubDate, value);
                value = "";
            }
            if (isGuid && name.equalsIgnoreCase("guid")) {
                isGuid = false;
                Arrays.add(guid, value);
                value = "";
            }
        }
    }
    

    (3) CaptionScreen (screen with BrowserField I need to show the result of the XML parsing)

    public class CaptionScreen extends MyMainScreen
    {
        private BrowserField _browserField;
    
        public CaptionScreen(Application app, String section)
        {
             //....
             GetArticles getArticles = new GetArticles("http://" + _urlWithArticles, _browserField);
             WaitScreen.showScreenAndWait(getArticles, "LOADING");
        }
    
        static class GetArticles implements Runnable {
            String _url = null;
            BrowserField _resultBrowser;
    
            public GetArticles(String urlToGet, BrowserField resultBrowser) {
                this._url = urlToGet;
                this._resultBrowser = resultBrowser;
            }
    
            public void run() {
                // Try to download new articles and parse the answer
                HttpConnection httpConn = null;
                InputStream is = null;
                RSSHandler rssHandler = new RSSHandler();
    
                try {
                    httpConn = GetConnection(_url);
    
                    is = httpConn.openInputStream();
                    try {
                        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
                        parser.parse(is, rssHandler);
                    }
                    catch (ParserConfigurationException e) {
                        e.printStackTrace();
                    }
                    catch (SAXException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (IOException ioe) {
                } catch (Exception e) {
                } finally {
                    try {
                        if ( httpConn != null ) {
                            httpConn.close();
                        }
                    } catch (Exception e) {
                    }
                    httpConn = null;
                }
    
                final String htmlArticles = generateHtml(rssHandler);
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        _resultBrowser.displayContent(htmlArticles, "");
                    }
                });
            }        
    
            // Method for html generation to showing in BrowserField
            private String generateHtml(RSSHandler rssHandler) {
                String result = "";
                if(rssHandler == null) {
                    return result;
                }
                result += "News";
    
                for(int i = 0; i < rssHandler.title.length; i++) {
                    result += rssHandler.title[i] + "
    " + "LINK
    " + rssHandler.description[i] + " "; } result += ""; return result; } private HttpConnection GetConnection(String _url) throws IOException { if (DeviceInfo.isSimulator()) { _url = _url + ";deviceSide=true"; } MyConnFact _myConnFact = new MyConnFact(); HttpConnection _httpConn = null; ConnectionDescriptor _connDesc = _myConnFact.getConnection(_url); if (_connDesc != null) { _httpConn = (HttpConnection)_connDesc.getConnection(); } return _httpConn; } } }

    It works very well (showing WaitScreeen, data download), but all characters not English shows as '?'
    I found a few discussions with the same problem (especially this one)

    http://supportforums.BlackBerry.com/T5/Java-development/how-to-show-other-languages-in-BrowserField/...

    and this one

    http://supportforums.BlackBerry.com/T5/Java-development/BrowserField-can-not-display-UTF-8-character...

    but I don't understand, how and where do I I implemented HttpConnection in my code.
    Please, give me advice or tell, how I change my code to solve this problem?

  • Extension of JavaScript causing a reload of the page

    Hello

    I created an extension of fast, based on dialogue by Tim Neil spinner code I found here https://github.com/tneil/WebWorks/tree/master/api/ui/Spinner/src/blackberry/ui/spinner

    Now, I have a basic function that takes a string and returns in a callback. This will be modified later to take a path of the image and returns a string containing an image of the data encoded in base64.

    Including the html from the application and function extension containing a script below.

    My problem is that on the successful recall, my 'onLoad' fuction is called again.

    Is there anyway to stop this happenning. OR I'm doing something wrong.

    See you soon.

    
    
    
    
    
    
    Invoke Extension
    
    
    
    
    ///===================================================
    
    public final class FunctionTest extends ScriptableFunction {
        public static final String NAME = "myfunction";
        private ScriptableFunction _callback = null;
    
        public Object invoke(Object obj, Object[] args) throws Exception
        {
            if (args.length == 2) {
                String strPath = (String)args[0];
                // Now get the callback method to fire
                _callback = (ScriptableFunction)args[1];
    
                Object[] result = new Object[1];
                result[0] = strPath;
                // Create a final thread safe result to pass into the thread object
                final Object[] threadedResult = result;
                // Create a new thread to make sure that the invoke of the JavaScript callback
                // does not initiate from the UI thread.  This can otherwise cause a deadlock scenario
                new Thread () {
                    public void run() {
                        try
                        {
                            // Pass the result of the spinner back to the handle of the JavaScript callback
                            _callback.invoke(_callback, threadedResult);
                        }
                        catch (Exception e) {
                            throw new RuntimeException(e.getMessage());
                        }
                    }
                }.start();
    
            }
    
            return UNDEFINED;
    
        }
    

    Reloading is caused the href = "" in your anchor tag. " A href empty, the page reloads. Try to use a button to trigger your code instead:

  • Download game files

    Hi all.

    I have 60 files on the web server. (The file size is less than 50 KB)

    I am trying to download one by one.

    Simulator: 8900

    connection: direct TCP (deviceside = true)

    The problem is to launch excetions: TCP or a closed connection.

    Code:

     public static void combine( String localName, String remoteName, int slices ){        HttpConnection conn = null;        InputStream in = null;        FileConnection file = null;        OutputStream out = null;        try        {            /*             * File connection             */            file = ( FileConnection )Connector.open( localName, Connector.READ_WRITE );            if( !file.exists() )            {                file.create();                file.setWritable( true );                out = file.openOutputStream();
    
                    if( slices > 0 )                {                    for( int i = 0; i < slices; i++ )                    {
    
                            /*                         * HTTP Connections                         */                        String currentFile = remoteName + "." + i + WebUtils.getConnectionParams();                        System.out.println( "Full URL: " + currentFile );
    
                            conn = ( HttpConnection )Connector.open( currentFile, Connector.READ, true );                        int responseCode = conn.getResponseCode();                        if( responseCode != 200 )                        {                            AssertUtils.fail( "Response Code = " + responseCode );                        }   
    
                            in = conn.openInputStream();
    
                            byte[] bytes = null;                        int len = ( int )conn.getLength();                        if( len > 0 )                        {                            int actual = 0;                            int bytesread = 0;                            bytes = new byte[ len ];                            while( ( bytesread != len ) && ( actual != -1 ) )                            {                                actual = in.read( bytes, bytesread, len - bytesread );                                out.write( bytes );                                bytesread += actual;                            }                        }
    
                            in.close();                        conn.close();
    
                            in = null;                        conn = null;
    
                        }
    
                        out.close();                    out = null;                }                else                {
    
                        /*                     * HTTP Connections                     */                    String currentFile = remoteName + WebUtils.getConnectionParams();                    System.out.println( "Full URL: " + currentFile );
    
                        conn = ( HttpConnection )Connector.open( currentFile, Connector.READ, true );                    int responseCode = conn.getResponseCode();                    if( responseCode != 200 )                    {                        AssertUtils.fail( "Response Code = " + responseCode );                    }
    
                        in = conn.openInputStream();
    
                        byte[] bytes = null;
    
                        int len = ( int )conn.getLength();                    if( len > 0 )                    {                        int actual = 0;                        int bytesread = 0;                        bytes = new byte[ len ];                        while( ( bytesread != len ) && ( actual != -1 ) )                        {                            actual = in.read( bytes, bytesread, len - bytesread );                            out.write( bytes );                            bytesread += actual;
    
                            }                    }
    
                        out.close();
    
                        in.close();                    conn.close();
    
                        in = null;                    conn = null;                    out = null;
    
                    }
    
                }        }        catch( Exception e )        {            AssertUtils.fail( e.getMessage() );        }        finally        {            if( conn != null )            {                try                {                    conn.close();                    conn = null;                }
    
                    catch( IOException e )                {                }            }            if( in != null )            {                try                {                    in.close();                    in = null;                }                catch( IOException e )                {                }            }            if( file != null )            {                try                {                    file.close();                }                catch( IOException e )                {                }                file = null;            }
    
                if( out != null )            {                try                {                    out.close();                }                catch( IOException e )                {                }                out = null;            }        }    }
    

    What is the problem with the code? Or what I should do to avoid these exceptions.

    Thank you.

    Hi Peter. Thanks for the reply.

    I added the loop with the capture of these erors and the problem has been resolved:

        private static void establish( ConnectionWrapper wrapper, String url, final int effortCount )    {        StreamConnection result = null;        int count = effortCount;
    
            while( true )        {            try            {                result = ( StreamConnection )Connector.open( url, Connector.READ_WRITE, true );                if( result != null )                {                    wrapper.Connection = ( HttpConnection )result;
    
                        break;                }            }            catch( Exception e )            {                count--;
    
                    if( count < 0 )                {                    throw new RuntimeException( "Failed to establish connection: " + e.getMessage() );                }
    
                    try                {                    Thread.sleep( 50 );                }                catch( Exception ex )                {                }
    
                    result = null;            }        }    }
    
  • PleaseWaitPopupScreen

    Hello, I use the code edition http://supportforums.blackberry.com/t5/Java-Development/Sample-quot-Please-Wait-quot-screen-part-1/t...

    I my case, I have a class of service that calls the connecction and Treaty the info leave in a vector.

    My code is:

    FieldChangeListener listener = new FieldChangeListener() {
       public void fieldChanged(Field field, int context) {
        ServiceHelper serviceHelper = new ServiceHelper();
            Vector result = serviceHelper.getProductList();
         Dialog.alert("Hello There");
         if (result.isEmpty()) {
            Dialog.alert("No data found");
         } else {
           String jsonString = (String) result.elementAt(0);
            Dialog.alert(jsonString);
         }
    }
    

    In the ServiceHelper class that I have:

    public Vector getProductList() {
      ConnectionThread ct = new ConnectionThread(
        Constants.ACTION_GET_PRODUCT_LIST);
    
      PleaseWaitPopupScreen.showScreenAndWait(ct, "Getting product list...");
      Vector responseVector = new Vector();
      if (ct.getResponseCode() == HttpConnection.HTTP_OK) {
        responseVector = ct.getResponseVector();
        Dialog.alert((String) responseVector.elementAt(0));
      }
      return responseVector;
    }
    

    But the PleaseWaitPopupScreen don't wait! It not immediately show the message "No data found" and on the PleaseWaiitScreen...

    Any clue?

    In fact, I think my article should be updated.  I think that the way you tried to use it, (i.e. citing as a blocking method), would in fact make it much easier to use. .

    In any case, I want you to try something.  Currently, the showScreenAndWait (.) method is:

        public static void showScreenAndWait(final Runnable runThis, String text) {
            final PleaseWaitPopupScreen thisScreen = new PleaseWaitPopupScreen(text);
            Thread threadToRun = new Thread() {
                public void run() {
                    // First, display this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().pushScreen(thisScreen);
                        }
                    });
                    // Now run the code that must be executed in the Background
                    try {
                        runThis.run();
                    } catch (Throwable t) {
                        t.printStackTrace();
                        throw new RuntimeException("Exception detected while waiting: " + t.toString());
                    }
                    // Now dismiss this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().popScreen(thisScreen);
                        }
                    });
                }
            };
            threadToRun.start();
        }
    

    Please change the following:

        public static void showScreenAndWait(final Runnable runThis, String text) {
            final PleaseWaitPopupScreen thisScreen = new PleaseWaitPopupScreen(text);
            /*
            Thread threadToRun = new Thread() {
                public void run() {
                    // First, display this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().pushScreen(thisScreen);
                        }
                    });
                    */
            Thread threadToRun = new Thread() {
                public void run() {
                    // Run the code that must be executed in the Background
                    try {
                        runThis.run();
                    } catch (Throwable t) {
                        t.printStackTrace();
                        throw new RuntimeException("Exception detected while waiting: " + t.toString());
                    }
                    while ( !thisScreen.isDisplayed() ) {
                        try {
                           Thread.sleep(500);
                        } catch (Exception e) {
                        }
                    }
                    // Now dismiss this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().popScreen(thisScreen);
                        }
                    });
                }
            };
            threadToRun.start();
            UiApplication.getUiApplication().pushModalScreen(thisScreen);
        }
    

    This means that the code is actually wait in showScreenAndWait (.).  I did not code this way initially because it's a little more complicated to explain. But I think that it is easier to use 100%.  According to me, a little more explanation is a small price to pay for ease of use.

    In any case if it works for you, then I will update the articles.

  • "Please wait" Popup goes away sooner than expected

    Hello

    My specs are:

    -Eclipse build IDE-20100218-1602

    -BlackBerry Java Plugin Version: 1.1.2.201004161203 - 16

    -BlackBerry Java SDK Version: 5.0.0.25

    I have a BrowserField2 which loads a specific page. While it loads I have 'Please wait' Popup but it goes far much more early to meet up with a blank screen until the page loads. This can confuse users.

    I want the Popup to stay until the page is loaded to 100%.

    What I am doing wrong?

    Heres part of my code:

    protected void onUiEngineAttached(boolean attached)    {        if(attached)        {            try            {             //Instantiate Web Content Request             GetWebContent getRequest = new GetWebContent(_browserField, _request);                //Pass background process and waiting message             PleaseWaitPopupScreen.showScreenAndWait(getRequest, _res.getString(LOADING_NEWS));            }            catch(Exception e)            {                                deleteAll();                add(new LabelField("ERROR:\n\n"));                add(new LabelField(e.getMessage()));            }        }    }
    
        public class GetWebContent implements Runnable     {       public GetWebContent(BrowserField _browserField, BrowserFieldRequest _request){           //constructor        }      public void run(){            //Get the Web Content for the BrowserField            _browserField.requestContent(_request);       }    }
    

    Here are some others:

    public static void showScreenAndWait(final Runnable runThis, String wait_message) {
            final PleaseWaitPopupScreen thisScreen = new PleaseWaitPopupScreen(wait_message);
            Thread threadToRun = new Thread() {
                public void run() {
                    // First, display this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().pushScreen(thisScreen);
                        }
                    });
                    // Now run the code that must be executed in the Background
                    try
                    {
                        runThis.run();
                    } catch (Throwable t)
                    {
                        t.printStackTrace();
                        throw new RuntimeException("Exception detected while waiting: " + t.toString());
                    }
                    // Now dismiss this screen
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().popScreen(thisScreen);
                        }
                    });
                }
            };
            threadToRun.start();
        }
    

    Help, please!

    you add the listener to the browserfield in your code.

    all you have to do now is to move the popup screen control in the listener methods.

    I would guess that abandoned, error etc all undisplay the popup, identical to documentLoaded.

    using the

    http://www.BlackBerry.com/developers/docs/6.0.0api/NET/rim/device/API/browser/Field2/BrowserFieldLis... net.rim.device.api.browser.field.ContentReadEvent)

    You can also view a progress if you wish.

  • How to convert the object Bitmap to byteArray.

    Hi all

    I had a problem in the conversion of the bitmap object to. BMP file.

    (Real need: capture the screen shot and convert that turned to the screen.) BMP image and I have to keep this image in the SCARD

    I shouldn't use any PNGEncodedImage or JPEGEncodedImage )

    I capture the screen shot using the

    Bitmap BM = new Bitmap (width, height);

    Display.screenshot (WB);

    to get the data from [] bytes of this bitmap object that I use

    Byte [] _bytes = getBytesFromBitmap (bitmap);

    public byte [] getBytesFromBitmap (Bitmap bmp) {}
    try {}
    int height = bmp.getHeight ();
    int width = bmp.getWidth ();
    int [] rgbdata = new int [width * height];
    ByteArrayOutputStream Bos = new ByteArrayOutputStream();
    DataOutputStream back = new DataOutputStream (bos);
    Graphics g = new Graphics (bmp);
    bmp.getARGB(rgbdata,0,width,0,0,width,height);
    for (int i = 0; i)< rgbdata.length="" ;="" i++)="">
    If (rgbdata [i]! = - 1) {}
    dos.writeInt (i);
    back. Flush();
    //l++;
    }
    }
    Bos.Flush ();
    Return bos.toByteArray ();
    }
    catch (Exception ex) {}
    Dialog.Alert ("getBytesFromBitmap:" + ex.toString ());
    Returns a null value.
    }

    If I use this byte array in the Sub statement I get the "IllegalArgumentException".

    BMPEncodedImage.createEncodedImage (_bytes, 0, _bytes .length);

    all can help me how I can get the byte [] data from the bitmap object?

    import java.io.ByteArrayOutputStream;import java.io.DataOutputStream;import java.io.IOException;
    
    import javax.microedition.lcdui.Image;
    
    /** * @author Samuel Halliday */public final class BMPGenerator {
    
        /**     * @param image     * @return     * @throws IOException     * @see {@link #encodeBMP(int[], int, int)}     */    public static byte[] encodeBMP(Image image) throws IOException {        int width = image.getWidth();        int height = image.getHeight();        int[] rgb = new int[height * width];        image.getRGB(rgb, 0, width, 0, 0, width, height);        return encodeBMP(rgb, width, height);    }
    
        /**     * A self-contained BMP generator, which takes a byte array (without any unusual     * offsets) extracted from an {@link Image}. The target platform is J2ME. You may     * wish to use the convenience method {@link #encodeBMP(Image)} instead of this.     * 

    * A BMP file consists of 4 parts:- *

      *
    • header
    • *
    • information header
    • *
    • optional palette
    • *
    • image data
    • *
    * At this time only 24 bit uncompressed BMPs with Windows V3 headers can be created. * Future releases may become much more space-efficient, but will most likely be * ditched in favour of a PNG generator. * * @param rgb * @param width * @param height * @return * @throws IOException * @see http://en.wikipedia.org/wiki/Windows_bitmap */ public static byte[] encodeBMP(int[] rgb, int width, int height) throws IOException { int pad = (4 - (width % 4)) % 4; // the size of the BMP file in bytes int size = 14 + 40 + height * (pad + width * 3); ByteArrayOutputStream bytes = new ByteArrayOutputStream(size); DataOutputStream stream = new DataOutputStream(bytes); // HEADER // the magic number used to identify the BMP file: 0x42 0x4D stream.writeByte(0x42); stream.writeByte(0x4D); stream.writeInt(swapEndian(size)); // reserved stream.writeInt(0); // the offset, i.e. starting address of the bitmap data stream.writeInt(swapEndian(14 + 40)); // INFORMATION HEADER (Windows V3 header) // the size of this header (40 bytes) stream.writeInt(swapEndian(40)); // the bitmap width in pixels (signed integer). stream.writeInt(swapEndian(width)); // the bitmap height in pixels (signed integer). stream.writeInt(swapEndian(height)); // the number of colour planes being used. Must be set to 1. stream.writeShort(swapEndian((short) 1)); // the number of bits per pixel, which is the colour depth of the image. stream.writeShort(swapEndian((short) 24)); // the compression method being used. stream.writeInt(0); // image size. The size of the raw bitmap data. 0 is valid for uncompressed. stream.writeInt(0); // the horizontal resolution of the image. (pixel per meter, signed integer) stream.writeInt(0); // the vertical resolution of the image. (pixel per meter, signed integer) stream.writeInt(0); // the number of colours in the colour palette, or 0 to default to 2n. stream.writeInt(0); // the number of important colours used, or 0 when every colour is important; // generally ignored. stream.writeInt(0); // PALETTE // none for 24 bit depth // IMAGE DATA // starting in the bottom left, working right and then up // a series of 3 bytes per pixel in the order B G R. for (int j = height - 1; j >= 0; j--) { for (int i = 0; i < width; i++) { int val = rgb[i + width * j]; stream.writeByte(val & 0x000000FF); stream.writeByte((val >>> 8 ) & 0x000000FF); stream.writeByte((val >>> 16) & 0x000000FF); } // number of bytes in each row must be padded to multiple of 4 for (int i = 0; i < pad; i++) { stream.writeByte(0); } } byte[] out = bytes.toByteArray(); bytes.close(); // quick consistency check if (out.length != size) throw new RuntimeException("bad math"); return out; } /** * Swap the Endian-ness of a 32 bit integer. * * @param value * @return */ private static int swapEndian(int value) { int b1 = value & 0xff; int b2 = (value >> 8 ) & 0xff; int b3 = (value >> 16) & 0xff; int b4 = (value >> 24) & 0xff; return b1 << 24 | b2 << 16 | b3 << 8 | b4 << 0; } /** * Swap the Endian-ness of a 16 bit integer. * * @param value * @return */ private static short swapEndian(short value) { int b1 = value & 0xff; int b2 = (value >> 8 ) & 0xff; return (short) (b1 << 8 | b2 << 0); } } Found form the Link mentioned below:
    http://javablog.co.uk/2007/12/26/j2me-bitmap-encoder/
  • simple pushScreen?

    Hi all.

    I develop for BB for a while and have not had the need to use the Dialog (s) so far.

    And now I'm in a bit of a quandary, because I can't get a simple pushScreen at work

    That's what I do:

    public class someClass {private UiApplication application; public someClass (UiApplication application){  this.application = application;} 
    
    public someMethod () {   synchronized(UiApplication.getEventLock())  {    try    {      application.pushScreen(settingsScreen);      //application.pushGlobalScreen(settingsScreen, 4, UiEngine.GLOBAL_SHOW_LOWER);    }    catch (Exception e)    {      throw new RuntimeException("FAILED to push settingsScreen");    }  }}
    

    After calling someMethod() first, nothing is displayed.

    Then I call it the second time, and I get the exception:

    "The attempt to push the screen so it is already displayed"!

    The exception would be ok if something was actually displayed on the screen, but it isn't.

    What did I miss?

    P.S. but if I use the commented on pushGlobalScreen() the screen. But the problem is that everything eventually (except on the end, FRO instance) dialog boxes only is shown.

    In fact

    the fact that you can combine flags did the trick:

    UiApplication.GLOBAL_SHOW_LOWER | UiApplication.GLOBAL_MODAL

    (first part says: just what is behidn this screen)

    (second part said: sulk me on top and wait to close)

    Thanks for the help!

  • NoClassDefFoundError

    I have an application that generates correctly, but gives a NoClassDefFoundError at runtime. I use Eclipse 3.5.2 with the following Blackberry SDK plugins:

    BlackBerry Java plug-in 1.1.2.201004161203 - 16 net.rim.EclipseJDE.feature.group
    BlackBerry Java SDK 5.0.0.25 net.rim.ejde.feature.componentpack5.0.0.feature.group
    BlackBerry Java SDK 4.7.0.53 net.rim.ejde.feature.componentpack4.7.0.feature.group
    BlackBerry Java SDK 4.6.1.36 net.rim.ejde.feature.componentpack4.6.1.feature.group
    BlackBerry Java SDK 4.6.0.21 net.rim.ejde.feature.componentpack4.6.0.feature.group
    BlackBerry Java SDK 4.5.0.21 net.rim.ejde.feature.componentpack4.5.0.feature.group

    NoClassDefFoundError is usually the result of a missing JAR, but in this case, I try to instantiate a class from my application JAR. In fact, the class in question is an inner class from another class that I already instantiated. Here is a fragment of the inner class:

    public class StructArrayFirst {    // Class implementation snipped...
    
        public static class Marshaller implements Marshal {
            private final String namespace;
            private final String name;
            private SoapSerializationEnvelope envelope;
    
            public Marshaller(String namespace, String name) {
                this.namespace = namespace;
                this.name = name;
            }
    
            public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected)
                    throws IOException, XmlPullParserException {
                String exitOnTag = parser.getName();
                if (!exitOnTag.equals(name)) {
                    throw new RuntimeException("Invalid tag. Expecting " + name + " got " + exitOnTag);
                }
    
                parser.nextTag();
    
                // Comment out this line and NoClassDefFoundError goes away.
                Object instance = readReturnInstance(parser);
    
                parser.require(XmlPullParser.END_TAG, null, name);
                return instance;
            }
    
            private Object readReturnInstance(XmlPullParser parser) throws XmlPullParserException, IOException {
                // Function body snipped...
            }
    

    I have the instantiate like this:

        public Marshal getMarshaller() {
            return new StructArrayFirst.Marshaller("", mTag);
        }
    

    The code as shown gives a NoClassDefFoundError when I try to make the instantiation. If I comment out the call to readReturnInstance, the problem goes away:

                // Comment out this line and NoClassDefFoundError goes away.
                //Object instance = readReturnInstance(parser);
    

    I'm puzzled as to why the presence of this line of code would result in a NoClassDefFoundError. Perhaps miss something elsewhere. Thanks for any light you might be able to do on that.

    -rich

    Found the problem. There was a code (not shown above) that attempted to access the class of primitive types (for example, int.class). It works in some Java environments (the code in question came originally from an Android project). BlackBerry obviously can't get an object of class for primitive types, but the compiler don't is not complaint. As long as the function that contains the offending code is never called, the class can be instantiated at run time. Perhaps packer is smart enough to omit unused functions. This caused some confusion since commenting the line mentioned above does not really solve the problem, but it causes the offending function not called. Would be nice if the compiler is complaining about this.

  • Adding static button in a drop-down list

    Hi all

    I add a list to verticalFieldManager with vertical scrolling function, and in the same crib from the bottom, I need to add a button (after clicking on the button I have to go on the other screen).

    Here, my problem is that whenever I scroll the list, the button does not scroll, it should look like the button on the top of the display to scroll and the list in the background. But whenever I scroll the list, list a scroll at the bottom of button.

    For more information, I add a screenshot, please find the attachment.

    I'd have a play with this, the thought took a little more time than I expected and there are a few "curve balls.

    In any case, here's some code that can do what you want.  There's some stuff in there, but see how you get on the revision of the code and the doc and the items I gave you to, to see if you can understand what is happening.

    Tested on OS 6.0 Simulator 9800, not on anything else.

    package mypackage;
    
    import java.util.Vector;
    
    import net.rim.device.api.system.Display;
    import net.rim.device.api.ui.Color;
    import net.rim.device.api.ui.Font;
    import net.rim.device.api.ui.Graphics;
    import net.rim.device.api.ui.Manager;
    import net.rim.device.api.ui.ScrollChangeListener;
    import net.rim.device.api.ui.TouchEvent;
    import net.rim.device.api.ui.XYRect;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.LabelField;
    import net.rim.device.api.ui.component.ListField;
    import net.rim.device.api.ui.component.ListFieldCallback;
    import net.rim.device.api.ui.component.SeparatorField;
    import net.rim.device.api.ui.component.Status;
    import net.rim.device.api.ui.container.MainScreen;
    import net.rim.device.api.ui.container.VerticalFieldManager;
    
    public class StaticButtonTestScreen extends MainScreen implements ListFieldCallback{
    
        private static int NUMBER_OF_ROWS_TO_ADD = 50;
        private static int NUMBER_OF_COLUMNS_TO_DISPLAY = 6;
    
        private Vector _listElements = new Vector();
        // We use a pretty crude method to supply the items to be displayed
        private ListField _listField;
        private int _requiredColumnWidth;
    
        StaticButtonTestScreen(){
    
            //! how wide will we make the columns?
            Font ourFont = this.getFont();
            _requiredColumnWidth = ourFont.getAdvance(" column 8 ");
            //! this example has fixed column widths.  They do not have to be.  Fixed is just simple to demonstrate.
    
            this.add(new LabelField("Above ListField", LabelField.FOCUSABLE));
            this.add(new SeparatorField());
            //! Add the ListField to a HorizontalFieldMaanger that can scroll horizontally.
            //! It is this that does the scrolling for us.
            StaticButtonManager myMan = new StaticButtonManager();
    
            //! Note the overridden methods in our ListField.
            _listField = new ListField() {
                //! OVerride layout so that you get the ListField defined the width that you want.
                protected void layout(int maxWidth, int maxHeight) {
                    int requiredWidth = Math.min(maxWidth, this.getPreferredWidth());
                    super.layout(requiredWidth, maxHeight);
                }
            };
            VerticalFieldManager vfm = new VerticalFieldManager(Manager.VERTICAL_SCROLLBAR | Manager.VERTICAL_SCROLL);
            // Put ListField in here so that it scrolls
            _listField.setCallback(this);
            _listField.setSize(NUMBER_OF_ROWS_TO_ADD);
            // setSearchable(true) so a key stroke will invoke indexOfList().  Try it
            _listField.setSearchable(true);
            for(int count = 0; count < NUMBER_OF_ROWS_TO_ADD; ++count) {
                String listItem = Integer.toString(count) + ".";
                _listElements.insertElementAt(listItem, count);
          }
            vfm.add(_listField);
            myMan.add(vfm);
            ButtonField bf = new SpecialButtonField("test");
            myMan.add(bf);
            this.add(myMan);
            this.add(new SeparatorField());
            this.add(new LabelField("Below ListField", LabelField.FOCUSABLE));
        }
    
        // Following methods are required by the ListFieldCallback interface
    
        public void drawListRow(ListField listField, Graphics graphics, int index, int y, int width) {
    
            int columnWidth = width/NUMBER_OF_COLUMNS_TO_DISPLAY;
            //! Use the width that we have, not the width we requested.
            //! There is a chance that they might be different, though I suspect this would only
            //! be seen during development when perhaps changes have not be made consistently. 
    
            int xpos = 0;
    
            // First column test data supplied from program
            String suppliedData = (String) this.get(listField, index);
            graphics.setColor(Color.BLACK);
            graphics.drawText(suppliedData, xpos, y);
            xpos +=  columnWidth;
    
            // Dummy up the other columns.....
            graphics.setColor(Color.RED);
            for ( int i = 1; i < NUMBER_OF_COLUMNS_TO_DISPLAY; i++ ) {
                graphics.drawText("c" + Integer.toString(i), xpos, y);
                xpos +=  columnWidth;
            }
    
        }
    
        public Object get(ListField listField, int index) {
             return _listElements.elementAt(index);
        }
    
        //! In theory, the "framework" can call this, so it should return the same
        //! value as the overridden getPreferredWidth().  But my testing suggests this is
        //! is actually never called.  But for consistency, set it correctly!
        public int getPreferredWidth(ListField litfield) {
            return _requiredColumnWidth * NUMBER_OF_COLUMNS_TO_DISPLAY;
        }
    
        // People don't know how to use this, so I'm coding this up as an example
        // In the sample code you can use the digits to find things...
        public int indexOfList(ListField listField, String prefix, int start) {
            // Search from where we currently are forward.
            for ( int i = start; i < _listElements.size(); i++ ) {
                String element = (String) this.get(listField, i);
                if ( element != null && prefix != null ) {
                    // Just being careful
                    if ( element.startsWith(prefix) ) {
                        return i;
                    }
                }
            }
            // Not found, search from beginning to where we are currently
            for ( int i = 0; i < start; i++ ) {
                String element = (String) this.get(listField, i);
                if ( element != null && prefix != null ) {
                    // Just being careful
                    if ( element.startsWith(prefix) ) {
                        return i;
                    }
                }
            }
            // Didn't find it, don't move....
            return start;
        }
    
    // Special Manager so that we can overlay the Fields
    // and because the standard optimised paint does not
    // cope with this, we need to invalidate() the Field on scroll to get
    // it repainted.
    
    // We also have a bit of work around
    
    class StaticButtonManager extends Manager implements ScrollChangeListener {
        // Implement ScrollChangeListener so tha on a scroll, we repaint
        // because the default action is optimised and does not cope
        // with the overlaid Fields.
        boolean scrollListenerSet = false;
        SpecialButtonField bf = null;
        XYRect ourExtent = new XYRect();
        public StaticButtonManager() {
            super(Manager.NO_VERTICAL_SCROLL | Manager.USE_ALL_HEIGHT);
        }
        // Override paintBackground just so we can see the extent of this Manager
        // Not necessary, just done to make it easier to see.
        public void paintBackground(Graphics g) {
            int currentBackgroundColor = g.getBackgroundColor();
            try {
                g.setBackgroundColor(0X00CCCCCC);
                g.clear();
            } finally {
                g.setBackgroundColor(currentBackgroundColor);
            }
        }
        // Only expect two Fields
        // 1) A VFM which will scroll to handle the ListField
        // 2) A button that we will stuck at the bottom right
        protected void sublayout(int maxWidth, int maxHeight) {
            maxHeight = Display.getHeight()/2;
            // Set the Height that the ListField will use when scrolling.
            if ( this.getFieldCount() != 2 ) {
                throw new RuntimeException("Incorrect number of Fields added");
            }
            VerticalFieldManager listFieldManager = (VerticalFieldManager) this.getField(0);
            if ( !scrollListenerSet ) {
                scrollListenerSet = true;
                listFieldManager.setScrollListener(this);
            }
            super.layoutChild(listFieldManager, maxWidth, maxHeight);
            super.setPositionChild(listFieldManager, 0, 0);
            if ( listFieldManager.getHeight() < maxHeight ) {
                maxHeight = listFieldManager.getHeight();
            }
            bf = (SpecialButtonField) this.getField(1);
            super.layoutChild(bf, maxWidth, maxHeight);
            super.setPositionChild(bf, maxWidth - bf.getWidth(), maxHeight - bf.getHeight());
            setExtent(maxWidth, maxHeight);
    
        }
        public void scrollChanged(Manager manager, int newHorizontalScroll, int newVerticalScroll) {
            this.invalidate(); // repaint everything....
        }
        /*
         * Might be needed, comment out code just in case
        public int getFieldAtLocation(int x, int y) {
            if ( x >= this.getWidth() - bf.getWidth() &&
                 y >= this.getHeight() - bf.getHeight() ) {
                return 1;
            }
            return super.getFieldAtLocation(x, y);
        }
        */
        // Just used to allow the user to use the trackpad to go horizontally and select the button.
        // Not really needed
        protected boolean navigationMovement(int dx, int dy, int status, int time) {
            boolean buttonInFocus = bf.isFocus();
            if ( dx > 0 && !buttonInFocus ) {
                bf.setFocus();
                return true;
            } else
            if ( dx < 0 && buttonInFocus ) {
                this.getField(0).setFocus();
                return true;
            }
            return super.navigationMovement(dx, dy, status, time);
        }
        // Because the Button keeps moving in relation t the manager
        // and the manager does not expect this,
        // We have to check the touch location ourselves
        protected boolean touchEvent(TouchEvent message) {
            int x = message.getX( 1 );
            int y = message.getY( 1 );
            getExtent(ourExtent);
            if( x < 0 || y < 0 || x > ourExtent.width || y > ourExtent.height ) {
                    // Outside the field
                    return false;
            }
            if ( x >= ourExtent.width - bf.getWidth() &&
                 y >= ourExtent.height - bf.getHeight() ) {
                bf.onClick();
                return true;
            }
            return false;
        }
    }
    // Special Button so that the Button can be clicked from the
    // Manager's touchEvent
    class SpecialButtonField extends ButtonField {
        public SpecialButtonField(String label) {
            super(label);
        }
        protected boolean navigationClick( int status, int time ) {
            onClick();
            return true;
        }
        public void onClick() {
            Status.show("Clicked: " + Integer.toString(_listField.getSelectedIndex()));
        }
    
    }
    
    }
    
  • substitute twice coach of field

    Hi to everyone!

    I am trying to replace a field twice.

    But I'm having a problem when the index of the selected item is 0.

    I'm going to null pointer exception.

    Can someone help me?

    ' Public Sub fieldChanged (field field, int context) {}
    TODO self-generating method stub
    if(Field == lst_City.typeField) {}
    String s_Type = (String) lst_City.typeField.getChoice (lst_City.typeField.getSelectedIndex ());
    s_Type = s_Type.toLowerCase ();
    lst_City.constructRestList (s_Type);
    {if (lst_City.typeField.getSelectedIndex () == 0)}
    lst_City.filteredRestListField = lst_City.restListField;
    }
    UiApplication.getUiApplication () .invokeLater (new Runnable() {}
    public void run()
    {
    Make changes to screen here.
    () lst_City.restListField.getManager replace (lst_City.restListField, lst_City.filteredRestListField);
    lst_City.restListField = lst_City.filteredRestListField;
    Invalidate() call on your display requires painting
    method to call.
    }
    });

    Best regards

    Can you clear this line to make sure that we know what is actually null.

    For example;

    If (lst_City == null) {}

    throw new RuntimeException ("lst_City is null");

    }

    If (lst_City.restListField == null) {}

    throw new RuntimeException ("lst_City.restListField is null");

    }

    Manager m = lst_City.restListField.getManager ();

    If (m == null) {}

    throw new RuntimeException ("lst_City.restListField.getManager () is null");

    }

    If (lst_City.filteredRestListField == null) {}

    throw new RuntimeException ("lst_City.restListField is null");

    }

    m.Replace (lst_City.filteredRestListField, lst_City.restListField);

    There is probably a bug in it, but you get the idea.

    Congatulations on your English.  I wish my French was 1/2 so good.

  • Response of HTTPConnection JSON server at BB on Wifi

    Hey there,

    I created a class that extends from the Thread:

    • Connect Wifi to my Tomcat server.
    • Request (GET method) of a resource (JSON object) on the server.
    • Lire read in response, and then analyze the JSON.

    The connection is successfully established, the response is read and then comes the analysis that is the problem. Apparently he received the JSON response in a bad shape. I think the problem is with the synchronization of threads, because I'm trying to use this response to build the user interface after the analysis.

    Here is the code:

    Class WifiThread:

    public class WifiThread extends Thread {
    
      private String _url;  private String _response; private String _interface = ";interface=wifi";
    
       public ConnectionThread(String url) {  this._url = url;   }
    
       public void run() {        HttpConnection conn = null;        InputStream in = null;        int code;
    
             try {
    
                       conn = (HttpConnection) Connector.open(this._url + this._interface, Connector.READ);            conn.setRequestMethod(HttpConnection.GET);
    
                code = conn.getResponseCode();
    
                if (code == HttpConnection.HTTP_OK) {                in = conn.openInputStream();                ByteArrayOutputStream out = new ByteArrayOutputStream();
    
                    byte[] buffer = new byte[in.available()];                int len = 0;
    
                    while (-1 != (len = inputStream.read(buffer))) {                    out.write(buffer);                                   }
    
                    out.flush();                this._response = new String(out.toByteArray());
    
                    System.out.println(this._response);
    
                    if (out != null){                    out.close();                }                if (in != null){                    in.close();                }                if (conn != null){                    conn.close();                }            }
    
            } catch (Exception e) {            System.out.println("HTTP Thread: " + e.toString());            throw e;        }   }  
    

    That's how his name:

    public myApp extends UiApplication {
    
        public myApp() {
    
              String url = "http://[IP.Address]:[Port]/[Resource]"          WifiThread thread = new WifiThread(url);          thread.start();          thread.run();
    
              String response = thread.get_response();
    
              // Parse JSON string:          JSONObject jsonObj = MyParser.fromJSON(response);
    
              // Create UI          // ...
    
        }}
    

    Any help would be great. Thank you!

    I've seen this code before:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ubyte [] buffer = new byte [in.available ()];
    int len = 0;
    {While (-1! = (len = {inputStream.read (buffer)))}
    out. Write (buffer);
    }
    out. Flush();
    This ._response = new String (out.toByteArray ());

    Can you tell me where you got it.  I want to see if I have removed it because I think that it is inefficient and made assumptions about the encoding.

    I suspect that you are sent a stream of UTF-8 bytes, in which case you can replace the above with something like:

    Byte [] responseBytes is (in) IOUtilities.streamToBytes;.

    try {}

    This ._response = new String (responseBytes, "UTF - 8");

    catch (Exception e) {}

    throw new RuntimeException ("unexpected decoding error:" + try);

    }

    If you have additional problems can empty you out the json using something like:

    System.out.println (this._response);

    and review to ensure that it matches what you expect and are Json valid.

    I hope this helps.

Maybe you are looking for