I am new to blackberry development and I am creating a native blackberry application. On every screen of my application, I need to send and receive data to the server on the same connection.
What I have done so far is I have made a ConnectToServer class which has a bunch of methods for sending and receiving. I instantiate it on the main screen and I pass it to each screen as a parameter.
That class in not a thread because I only read and write when the user types in information and presses a button. So basically I am using the inputStream and outputStream on the event thread which I hear is BAD. Then I ask ConnectToServer to get me what the server sent. For instance, I get a vector which I use to make a ListField.
How can I make these UI updates?
public class Screen3 extends MainScreen {
ConnectToServer con;
Vector v;
public Screen3(String exerciseName, ConnectToServer connect)
{
con = connect;
con.send(exerciseName);
v = con.receiveVector();
mylist = new listField();
mylist.setSize(v.size());
add(mylist);
}
public void drawListRow(...)
{
graphics.drawText((String) v.elementAt(index)
}
}
So, there’s many ways to approach this. First of all, since it seems like you only want one instance of
ConnectToServer, and you are currently having to pass that around, you might try making that class a Singleton object. This is not necessary, and does not have anything to do with your threading problem, but I only offer it as a solution, for situations where you want to enforce that there’s only one instance of something, and want to avoid having to pass it around everywhere. A simple Singleton implementation might be this:And use it in your screens like this (no need to pass it into the constructor any more):
Now, on to the threading problem. You’re right that you should not be performing network requests on the main (aka “UI”, aka “Event”) thread. If you have a nice separate
ConnectToServerclass, that makes it easier to encapsulate this behaviour. Instead of UI clients using a synchronoussend()andreceiveVector()method, make one method that just kicks off the request, and another callback method that theConnectToServerclass will call when the response comes back. TheConnectToServerclass will use aThreadto perform this work, and thus avoid freezing the UI during the request.I’ll define an
interfacethat the UI clients will implement:And then the new (partial)
ConnectToServerclass:Note that you should also make your original
send()andreceiveVector()methods in this classprivate. They should only be called from inside the class now, not directly from UI clients.Then, you need to code your
Screenclasses like this:Also, you might also want to code the server class to protect against multiple UI clients making concurrent requests, allow current requests to be cancelled, etc. But the above should get you started on a solution that provides a responsive app, without freezing your UI.