The example below create an event and send it to a destination number. It also imports event into its native database.

 import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.pim.*;
import javax.wireless.messaging.*;

public class CreateEventMIDlet  extends MIDlet  implements MessageListener {
    
    private final static int DEFAULT_PORT = 6553;
    private final static String SMS_PREFIX = "sms://:";
    
    private final EventCreationScreen mainScreen;
    
    private MessageConnection conn;
    private Message nextMessage;
    private OperationsQueue queue = new OperationsQueue();
    private final Display display;
    Alert alert;
    
    public CreateEventMIDlet() {
        
        mainScreen = new EventCreationScreen(this, DEFAULT_PORT);
        display = Display.getDisplay(this);
        
    }
    
    void sendMessage(String number, byte[] text) {
        
        if (conn != null) {
            
            try {
                
                BinaryMessage requestSMS = (BinaryMessage) conn.newMessage(
                        MessageConnection.BINARY_MESSAGE);
                String address = new StringBuffer("sms://")
                .append(number).append(":").append(DEFAULT_PORT).toString();
                requestSMS.setAddress(address);
                requestSMS.setPayloadData(text);
                conn.send(requestSMS);
                
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    public void startApp() {
        
        Displayable current = Display.getDisplay(this).getCurrent();
        
        if (current == null) {
            
            // check that the API is available
            boolean isAPIAvailable =(
                    System.getProperty("microedition.pim.version") != null);
            
            StringBuffer sbuf = new StringBuffer(
                    getAppProperty("MIDlet-Name"));
            
            sbuf.append("\n").append(
                    getAppProperty("MIDlet-Vendor")).
                    append(isAPIAvailable?"":"\nPIM API not available");
            
            Alert alertScreen = new Alert(null,sbuf.toString(),null,
                    AlertType.INFO);
            
            alertScreen.setTimeout(3000);
            
            if (!isAPIAvailable) {
                
                display.setCurrent(alertScreen, mainScreen);
                
            } else {
                
                display.setCurrent(alertScreen, mainScreen);
                
                // List connections from PushRegistry
                String smsConnections[] = PushRegistry.listConnections(true);
                
                // Chech the connections.
                // We'll assume only one is of interest
                for (int i = 0; i < smsConnections.length; i++) {
                    if (smsConnections[i].startsWith(SMS_PREFIX)) {
                        try {
                            conn =(MessageConnection)
                            Connector.open(smsConnections[i]);
                            
                            BinaryMessage incomingMessage =
                                    (BinaryMessage) conn.receive();
                            
                            showIncomingMessage(incomingMessage);
                            conn.close();
                            
                        } catch (IOException e) {
                            e.printStachTrace();
                        } catch (SecurityException e) {
                            e.printStachTrace();
                        }
                    }
                }
                
                // Build the connection string
                String connection = SMS_PREFIX + DEFAULT_PORT;
                
                try {
                    
                    // Initiate the connection and add listener
                    conn = (MessageConnection) Connector.open(connection);
                    conn.setMessageListener(this);
                    
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
            
        } else {
            
            Display.getDisplay(this).setCurrent(current);
        }
    }
    
    public void pauseApp() {  }
    
    public void destroyApp(boolean unconditional) {
        
        try {
            // Close the connection on exit
            if (conn != null) {
                conn.close();
            }
        } catch (IOException e) {
        }
        
        queue.abort();
    }
    
    // Asynchronous callback for inbound message.
    public void notifyIncomingMessage(MessageConnection conn) {
        
        if (conn == this.conn && conn != null) {
            try {
                // Create a ReceiveScreen upon message removal
                BinaryMessage incomingMessage =
                        (BinaryMessage) conn.receive();
                
                showIncomingMessage(incomingMessage);
            } catch (IOException e) {
                e.printStachTrace();
            } catch (SecurityException e) {
                e.printStachTrace();
            }
        }
        
    }
    
    void showIncomingMessage(BinaryMessage msg) {
        display.setCurrent(new IncomingEventForm(this, msg));
    }
    
    void showMessage(String message) {
        showError(message, mainScreen);
    }
    
    void showMessage(String message, Displayable mainScreen) {
        showError(message, mainScreen);
    }
    
    void showError(String message, Displayable next) {
        
        if(alert == null) {
            alert = new Alert("");
        }
        
        alert.setTitle("Error");
        alert.setString(message);
        display.setCurrent(alert, next);
    }
    
    // adds an operation the queue
    void enqueueOperation(Operation operation) {
        queue.enqueueOperation(operation);
    }
    
    // shows the main screen
    void showMain() {
        display.setCurrent(mainScreen);
    }
}

import java.io.*;
import java.util.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.pim.*;
import javax.wireless.messaging.*;

class EventCreationScreen extends Form implements CommandListener {
    
    private final Command sendCommand, exitCommand;
    private final TextField number, duration, topic;
    private final DateField dateTime;
    private final CreateEventMIDlet parent;
    private final int port;
    
    public EventCreationScreen(CreateEventMIDlet parent, int port) {
        
        super("Create an event");
        this.parent = parent;
        this.port = port;
        
        sendCommand = new Command("Send", Command.OK, 1);
        exitCommand = new Command("Exit", Command.EXIT, 1);
        
        number = new TextField("Dest. number","",20,TextField.PHONENUMBER);
        
        dateTime = new DateField("Date", DateField.DATE_TIME,
                TimeZone.getDefault());
        
        dateTime.setDate(new Date());
        duration = new TextField("Duration (min)","30",24,TextField.NUMERIC);
        topic = new TextField("Subject","",24,TextField.ANY);
        
        append(number);
        append(dateTime);
        append(duration);
        append(topic);
        
        addCommand(sendCommand);
        addCommand(exitCommand);
        setCommandListener(this);
    }
    
    public void commandAction(Command cmd, Displayable displayable) {
        
        if (cmd == sendCommand) {
            
            parent.enqueueOperation(new
                    SendEvent(number.getString(),
                    dateTime.getDate(),
                    duration.getString(),
                    topic.getString()));
            
        } else if (cmd == exitCommand) {
            parent.notifyDestroyed();
        }
    }
    
    private class SendEvent implements Operation {
        
        private final String number, duration, topic;
        private final Date date;
        
        SendEvent(String number,Date date,
                String duration,String topic) {
            
            this.number = number;
            this.date = date;
            this.duration = duration;
            this.topic = topic;
        }
        
        public void dotask() {
            
            int length = 0;
            
            try {
                length = Integer.parseInt(duration);
            } catch (NumberFormatException e) {
                return;
            }
            
            if (length <= 0) {
                parent.showMessage("Duration needs to be positive",
                        EventCreationScreen.this);
            } else if (number == null || number.length() == 0) {
                parent.showMessage("Number not entered",
                        EventCreationScreen.this);
            } else if (topic == null || topic.length() == 0) {
                parent.showMessage("Subject not entered",
                        EventCreationScreen.this);
            } else {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                EventList eventList = null;
                
                try {
                    
                    PIM pim = PIM.getInstance();
                    String listNames[] = pim.listPIMLists(PIM.EVENT_LIST);
                    
                    if (listNames.length > 0) {
                        eventList = (EventList) pim.openPIMList(
                                PIM.EVENT_LIST,
                                PIM.READ_WRITE, listNames[0]);
                        
                        Event newEvent = eventList.createEvent();
                        
                        if (eventList.isSupportedField(Event.SUMMARY)) {
                            
                            newEvent.addString(Event.SUMMARY,
                                    PIMItem.ATTR_NONE,topic);
                        }
                        
                        if (eventList.isSupportedField(Event.START)) {
                            newEvent.addDate(Event.START,PIMItem.ATTR_NONE,
                                    date.getTime());
                        }
                        
                        if (eventList.isSupportedField(Event.END)) {
                            newEvent.addDate(Event.END,PIMItem.ATTR_NONE,
                                    date.getTime() + 60 * 1000 * length);
                        }
                        
                        // let's check that VCALENDAR/1.0 is supported
                        String supportedFormats[] =
                                PIM.getInstance().supportedSerialFormats(
                                PIM.EVENT_LIST);
                        
                        for (int i=0;i<supportedFormats.length;i++) {
                            if (supportedFormats[i].equals(
                                    "VCALENDAR/1.0")) {
                                
                                PIM.getInstance().toSerialFormat(newEvent,
                                        out, "UTF-8","VCALENDAR/1.0");
                                
                                break;
                            }
                        }
                        
                        if (out.size() == 0) {
                            parent.showMessage("VCALENDAR/1.0 not supported",
                                    EventCreationScreen.this);
                        }
                        
                        eventList.importEvent(newEvent);
                        newEvent.commit();
                        
                    } else {
                        parent.showMessage("No Event list available",
                                EventCreationScreen.this);
                    }
                    
                } catch (PIMException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                } finally {
                    
                    try {
                        
                        if (eventList != null) {
                            eventList.close();
                        }
                        
                    } catch (PIMException e) {
                    }
                    
                }
                
                if (out.size() > 0) {
                    parent.sendMessage(number, out.toByteArray());
                }
            }
            
        }
    }
}

import java.io.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.pim.*;
import javax.wireless.messaging.*;

class IncomingEventForm  extends Form  implements CommandListener {
    
    private Command acceptCommand, exitCommand, backCommand;
    private TextField number, duration, topic;
    private DateField dateTime;
    private final CreateEventMIDlet parent;
    private Event event;
    
    IncomingEventForm(CreateEventMIDlet parent, BinaryMessage msg) {
        
        super("Event Received");
        this.parent = parent;
        
        backCommand = new Command("Back", Command.BACK, 2);
        exitCommand = new Command("Exit", Command.EXIT, 2);
        
        addCommand(backCommand);
        addCommand(exitCommand);
        
        setCommandListener(this);
        parent.enqueueOperation(new LoadEvent(msg));
        
    }
    
    public void commandAction(Command cmd, Displayable displayable) {
        
        if (cmd == acceptCommand) {
            parent.enqueueOperation(new InsertEvent());
        } else if (cmd == exitCommand) {
            parent.notifyDestroyed();
        } else if (cmd == backCommand) {
            parent.showMain();
        }
    }
    
    private String findName(String number) {
        
        String[] allLists = PIM.getInstance().listPIMLists(PIM.CONTACT_LIST);
        
        if (allLists.length > 0) {
            
            String results[] = new String[allLists.length];
            
            for (int i = 0; i < allLists.length; i++) {
                results[i] = findNameInList(number, allLists[i]);
            }
            
            for (int i = 0; i < allLists.length; i++) {
                if (results[i] != null) {
                    return results[i];
                }
            }
            
        }
        
        return null;
    }
    
    private String findNameInList(String number, String list) {
        
        ContactList contactList = null;
        
        try {
            
            contactList = (ContactList) PIM.getInstance()
            .openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY, list);
            
            if (contactList.isSupportedField(Contact.TEL)
            && contactList.isSupportedField(Contact.FORMATTED_NAME)) {
                
                Contact pattern = contactList.createContact();
                pattern.addString(Contact.TEL, PIMItem.ATTR_NONE, number);
                Enumeration matching = contactList.items(pattern);
                
                if (matching.hasMoreElements()) {
                    
                    Contact ci = (Contact) matching.nextElement();
                    // FORMATTED_NAME is mandatory
                    return ci.getString(Contact.FORMATTED_NAME, 0);
                    
                }
            }
            
        } catch (PIMException e) {} catch (SecurityException e){}
        
        finally {
            
            if (contactList != null) {
                try {
                    contactList.close();
                } catch (PIMException e) {
                }
            }
        }
        
        return null;
    }
    
    private class InsertEvent implements Operation {
        
        public void dotask() {
            
            EventList eventList = null;
            
            try {
                
                PIM pim = PIM.getInstance();
                String listNames[] = pim.listPIMLists(PIM.EVENT_LIST);
                
                if (listNames.length>0) {
                    
                    eventList = (EventList) pim.openPIMList(PIM.EVENT_LIST,
                            PIM.READ_WRITE,
                            listNames[0]);
                    
                    // Check that the fields are supported
                    if (eventList.isSupportedField(Event.SUMMARY) &&
                            eventList.isSupportedField(Event.START) &&
                            eventList.isSupportedField(Event.END)) {
                        // event cannot be null at this stage
                        eventList.importEvent(event).commit();
                        
                        parent.showMessage(
                                "Event inserted in the local database");
                    }
                    
                } else {
                    parent.showMessage("No Event list found");
                }
            } catch (PIMException e) {
                e.printStackTrace();  } catch (SecurityException e) {
                    
                    e.printStackTrace();} finally {
                        if (eventList != null) {
                            try {
                                eventList.close();
                            } catch (PIMException e){  }
                        }
                    }
        }
    }
    
    // This operations reads an event from a TextMessage
    private class LoadEvent implements Operation {
        
        private final BinaryMessage msg;
        
        LoadEvent(BinaryMessage msg) {
            this.msg = msg;
        }
        
        public void dotask() {
            
            PIMItem items[] = null;
            
            try {
                
                items = PIM.getInstance().fromSerialFormat(
                        new ByteArrayInputStream(msg.getPayloadData()),  
                        "UTF-8");
                
            } catch (PIMException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();}
            
            if (items != null && items.length>0) {
                
                event = (Event) items[0];
                int summaryCount = event.countValues(Event.SUMMARY);
                int startCount = event.countValues(Event.START);
                int endCount = event.countValues(Event.END);
                
                if (summaryCount>0 && startCount>0 && endCount>0) {
                    
                    topic = new TextField("topic",event.getString(
                            Event.SUMMARY, 0),
                            24,TextField.ANY);
                    
                    String source = msg.getAddress();
                    String phoneNumber = source.substring(6,
                            source.lastIndexOf(':'));
                    
                    String sourceName = findName(phoneNumber);
                    
                    if (sourceName != null) {
                        
                        number = new TextField("From",  sourceName,20,
                                TextField.ANY |  TextField.UNEDITABLE);
                        
                    } else {
                        
                        number = new TextField("From",  phoneNumber,20,
                                TextField.PHONENUMBER |  
                                TextField.UNEDITABLE);
                        
                    }
                    
                    long startDate = event.getDate(Event.START, 0);
                    long length = event.getDate(Event.END, 0) - startDate;
                    length /= 60000;
                    
                    dateTime = new DateField("on",DateField.DATE_TIME,
                            TimeZone.getDefault());
                    
                    dateTime.setDate(new Date(startDate));
                    duration = new TextField("duration (min)",
                            "" + length,24,  TextField.ANY);
                    
                    append(number);
                    append(topic);
                    append(dateTime);
                    append(duration);
                    
                    acceptCommand = new Command("Accept", Command.OK, 1);
                    addCommand(acceptCommand);
                    
                } else {
                    
                    append(new StringItem("", 
                            "Incoming event was incomplete"));
                    
                }
            } else {
                
                event = null;
                acceptCommand = null;
                append(new StringItem("", "Error during message decoding"));
                
            }
        }
    }
    
}

import java.util.*;

class OperationsQueue implements Runnable {
    
    private volatile boolean running = true;
    private final Vector operations = new Vector();
    
    OperationsQueue() {
        new Thread(this).start();
    }
    
    void enqueueOperation(Operation nextOperation) {
        
        operations.addElement(nextOperation);
        
        synchronized (this) {
            notify();
        }
    }
    
    void abort() {
        
        running = false;
        
        synchronized (this) {
            notify();
        }
    }
    
    public void run() {
        
        while (running) {
            while (operations.size() > 0) {
                
                try {
                    ((Operation) operations.firstElement()).dotask();
                } catch (Exception e) {
                }
                
                operations.removeElementAt(0);
                
            }
            
            synchronized (this) {
                
                try {
                    wait();
                } catch (InterruptedException e) {
                }
                
            }
        }
    }
    
}

interface Operation {
    void execute();
}

 

 

 Related Tips