Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
canamgroup
Posts: 117
Registered: ‎07-16-2008
My Device: Not Specified
Accepted Solution

Questions regarding threads...

[ Edited ]

Hi,

 

I have a new application to do that needs network access.

I've read this EXCELLENT post by peter_strange:

http://supportforums.blackberry.com/t5/Java-Development/Connecting-your-BlackBerry-http-and-socket-c...

 

Since I cannot use BIS-B because I'm not an Alliance Partner, I wanted to take a look at the new Network API for OS 5.0 and see how it works.

 

I know that network connections need to be done in a separate thread.

 

I'm far from being an experienced Blackberry developer... so I have a few questions regarding threads.  I looked around the Internet, read the forum, read the documentation, did some tests and so far, I came up with this code:

 

public class HTTPConnection extends UiApplication {
    public static void main(String[] args) {
        HTTPConnection theApp = new HTTPConnection();
        theApp.enterEventDispatcher();
    }

    public HTTPConnection() {
        pushScreen(new HTTPConnectionScreen());
    }
}

class HTTPConnectionScreen extends MainScreen {
    public HTTPConnectionScreen() {
        setTitle("HTTPConnection");
        add(new RichTextField("Choose a connection type: "));

        final RadioButtonGroup rbGroup = new RadioButtonGroup();
        RadioButtonField radioButtonF1 = new RadioButtonField("Direct TCP", rbGroup, false);
        RadioButtonField radioButtonF2 = new RadioButtonField("WAP 1.0/1.1", rbGroup, false);
        RadioButtonField radioButtonF3 = new RadioButtonField("WAP 2.0", rbGroup, false);
        RadioButtonField radioButtonF4 = new RadioButtonField("BES/MDS", rbGroup, false);
        RadioButtonField radioButtonF5 = new RadioButtonField("BIS-B", rbGroup, false);
        RadioButtonField radioButtonF6 = new RadioButtonField("WiFi", rbGroup, false);
        add(radioButtonF1); add(radioButtonF2); add(radioButtonF3); add(radioButtonF4); add(radioButtonF5); add(radioButtonF6);
         
        FieldChangeListener listener = new FieldChangeListener() {
            public void fieldChanged(Field field, int context) {
                ConnectionThread ct = new ConnectionThread(rbGroup.getSelectedIndex()+1);
                ct.start();
            }
        };
         
        ButtonField buttonField = new ButtonField("Connect", ButtonField.CONSUME_CLICK);
        buttonField.setChangeListener(listener);
        add(buttonField);
    }

    /* over-ride default onSavePrompt method to avoid being asked if I want to save each time */
    protected boolean onSavePrompt() {
        return true;
    }
}

class ConnectionThread extends Thread {
    private int transportType;
    public ConnectionThread(int tt) {
        transportType=tt;
    }
    
    public void run() {
        ConnectionFactory connFact = new ConnectionFactory();
        ConnectionDescriptor connDesc = connFact.getConnection("URL", transportType, null);
        if (connDesc != null) {
            try {
                HttpConnection httpConn = (HttpConnection)connDesc.getConnection();
                httpConn.setRequestMethod(HttpConnection.POST);
                httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                                    
                OutputStream out = httpConn.openOutputStream();
                out.write(Integer.toString(transportType).getBytes());
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpConnection.HTTP_OK) {
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            Dialog.alert("--CONNECTION SUCCESSFUL--");
                        }
                    });
                }
                if (httpConn!=null) httpConn.close();
            } catch (IOException e) {
                System.err.println("Caught IOException: " + e.getMessage());
            }
        }
    }
}

 

Actually, this code works fine... but I want to improve it and I have a few questions:

 

1- I think that right now, everytime I click on the "Connect" button, I start a brand new thread. I would like to close that thread in the "run" method, but I don't really know how to access the "ct" variable from there.   Any advise on how to do this?  Or maybe always use the same thread until my application is closed?

 

2- In the FieldChangeListener of my "Submit" button, I want to access the radio box value.  What I did works, but I had to make my variable "final".  Is this the right way to do so?

 

3- Instead of displaying a Dialog with "Connection Successful", I would like to write something back in my main screen.  How could I do that?

 

I'm just a bit confused as to all put that together when using a separate thread.

 

Thanks for your advices!

 

Edit: Hid the URL I'm connecting to...

 

Please use plain text.
Developer
simon_hain
Posts: 16,137
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport

Re: Questions regarding threads...

that's what i call a good question! (now i wonder why the forums don't work with opera properly, anyhow, here my baldy formatted answer): 1. your thread "dies" when it is finished, no need to close it. 2. yes 3. you can use a callback. see for example http://www.javaworld.com/javaworld/javatips/jw-javatip10.html
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.
Developer
canamgroup
Posts: 117
Registered: ‎07-16-2008
My Device: Not Specified

Re: Questions regarding threads...

Thanks for your lightning fast answer! :smileyhappy:

 

Regarding #1: So nothing to change here... but I just want to make sure I fully understand.

 

If I understand correctly, I start a new thread when I click on the "Connect" button.  This automaticaly execute the code inside my "Run" method.  When the code in this method has finished executing, the thread "dies"... so that's why I don't need to close it.  The application is still running though.  So if I click on the "Connect" button again, then a new thread is started again that will eventually "dies" when the "Run" method is finished and  so on.  Am I right?

 

If I wanted to close completely my application, would I only need to add "System.exit(0);" somewhere in my "Run" method?

 

Regarding #2: I wanted to make sure I did this the right way (it's Eclipse who told me to make my variable "final").  I did a FieldChangeListener much like the example in the javadocs... and wanted to know how to access variables from the outer class in the inner class.  So nothing to change here as well :smileyhappy:

 

Regarding #3: I'll read your link.

 

Thanks again!

 

 

 

 

Please use plain text.
Developer
simon_hain
Posts: 16,137
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport

Re: Questions regarding threads...

yes, a system.exit shuts down your app, no questions asked. if, however, your app has remaining stuff outside of itself, like a phonelistener, applicationmenuitems, an optionsprovider, notifications etc, they are left behind (which is usually not the case, but i mention it to help your understanding). If you close the last screen of an UiApplication a system.exit is automatically performed (unless you overwrite onClose or close)
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.
Developer
canamgroup
Posts: 117
Registered: ‎07-16-2008
My Device: Not Specified

Re: Questions regarding threads...

Regarding #3: I read your link (many times!)... but I'm still confused as to how to do that.

 

I want to write stuff to the main screen in the "Run" method.

Since it's not from the same class and not from the same thread, I don't know how to do this.

Also, I don't want to make all my variables "final" cause some of them might have to change.

 

I know I'm asking a lot, but could you just give me an quick example on how to do this based on my situation?

 

Sorry, I'm still a newbie on Blackberry development... and it's been a while since I did OO coding.

Please use plain text.
Developer
simon_hain
Posts: 16,137
Registered: ‎07-29-2008
My Device: Z10 LE, Z30, Passport

Re: Questions regarding threads...

lets say you have a mainscreen that you want to update when your connection thread finishes. now you give the mainscreen as a parameter to the thread and call an update method (that you implement) when processing is done. to make this more universal to use, define an interface that has update as its method and let mainscreen implement it. your thread now takes this interface as a parameter and calls its update method. this allows you to implement the interface in other classes and use them with your thread.
----------------------------------------------------------
feel free to press the like button on the right side to thank the user that helped you.
please mark posts as solved if you found a solution.
@SimonHain on twitter
Please use plain text.
Developer
peter_strange
Posts: 19,604
Registered: ‎07-14-2008
My Device: Not Specified

Re: Questions regarding threads...

Here is a sample that uses the first approach as suggested by Simon - i.e. updates the screen directly.

http://supportforums.blackberry.com/t5/Java-Development/Sample-quot-Please-Wait-quot-screen-part-1/t...

 

I'm working on the article that does the second (the Observer Interface). 

 

I'm interested in any comments too....

Please use plain text.
Developer
canamgroup
Posts: 117
Registered: ‎07-16-2008
My Device: Not Specified

Re: Questions regarding threads...

I got it!

 

Thanks Simon for all your help and Peter for your great sample!

I'm waiting for part-2 :smileyhappy:

Please use plain text.