Home > Articles > Programming > Java

  • Print
  • + Share This

Data Access Using StreamConnection

The StreamConnection interface defines the minimal capabilities that a stream connection must have. Here are the specific modifications that need to be made to the existing AddressBookMIDLet:

  • Remove the dbAddress.addAddress() method calls from the AddressBookMIDLet() constructor. This can be removed because, instead of manually adding the entries to the database, the new code in this example will retrieve the addresses over the Internet by using J2ME's networking capabilities.

  • Add the Connection-specific code to the AddressDB constructor (directly after opening the record store). The Connection-specific code in the two examples will simply retrieve the addresses via TCP/IP and will manually add each address to the address book.

StreamConnection connStream = null;
InputStream inStream = null;
byte[] b = new byte[255];
String address, name;
int commalocation = 0;
try {
   connStream = (StreamConnection)
               Connector.open("http://localhost/addressbook.txt");
   inStream = connStream.openInputStream();
   int count = inStream.read(b);
   address = new String(b);
   address = address.trim();
   StringTokenizer st = new StringTokenizer(address, "\n");
   while (st.hasMoreTokens()) {
      address = st.nextToken();
commalocation = address.indexOf(','); name = address.substring(0, commalocation); address = address.substring(commalocation + 1); addAddress(name, address); } } catch (IOException e) { System.out.println(e); e.printStackTrace();
}

The code above works fine but has a slight problem. I've had to hard-code the byte array to be 255 because the StreamConnection interface doesn't provide any way to evaluate the size of the data being downloaded. To do this, I can make use of the ContentConnection interface and the handy getLength() method.

One other problem is the lack of the J2SE java.util.StringTokenizer class in J2ME. I could have written my own string parser class, but a quick Web search revealed that the Open Source JavaOS project had developed an Open Source StringTokenizer class that would work just fine. Incorporating this class supports the efficient processing of the text file using a standard Java class.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.