×
Namespaces

Variants
Actions
(Difference between revisions)

Exporting a calendar event in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
dekudin (Talk | contribs)
(New page: __NOTOC__ __NOEDITSECTION__ {{CodeSnippet |id=  |platform=S60 3rd Edition, FP2 |devices=Nokia E70 |category=Java ME |subcategory=Calendar |creationdate=October 29, 2008 |keywords=java...)
 
hamishwillee (Talk | contribs)
m (Hamishwillee - Bot update - Fix metadata)
(16 intermediate revisions by 6 users not shown)
Line 1: Line 1:
__NOTOC__
+
[[Category:Java ME]][[Category:Code Examples]][[Category:PIM]][[Category:File Connection and PIM API (JSR-75)]][[Category:Code Snippet]][[Category:Series 40]][[Category:Symbian]][[Category:S60 3rd Edition (initial release)]][[Category:Series 40 6th Edition FP1]][[Category:Series 40 Developer Platform 2.0]][[Category:Nokia Belle]]
__NOEDITSECTION__
+
{{ArticleMetaData <!-- v1.2 -->
{{CodeSnippet
+
|sourcecode= [[Media:ExportingCalendarEvent.zip]]
|id=&nbsp;
+
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|platform=S60 3rd Edition, FP2
+
|devices= Nokia E70, Nokia C3-01, Nokia Asha 306, Nokia E7-00
|devices=Nokia E70
+
|sdk= [http://www.developer.nokia.com/Develop/Java/ Nokia SDK 1.1 for Java], [http://www.developer.nokia.com/Develop/Java/ Nokia SDK 2.0 for Java (beta)], [http://www.developer.nokia.com/info/sw.nokia.com/id/ec866fab-4b76-49f6-b5a5-af0631419e9c/S60_All_in_One_SDKs.html/ Nokia Symbian SDKs]
|category=Java ME
+
|platform= Series 40, S60, Nokia Belle
|subcategory=Calendar
+
|devicecompatability= <!-- Compatible devices (e.g.: All* (must have GPS) ) -->
|creationdate=October 29, 2008
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|keywords=javax.microedition.pim.EventList, javax.microedition.pim.Event, javax.microedition.pim.PIM.supportedSerialFormats, javax.microedition.pim.PIM.toSerialFormat
+
|signing= <!-- Empty or one of Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 +
|keywords= javax.microedition.pim.EventList, javax.microedition.pim.Event, javax.microedition.pim.PIM.supportedSerialFormats, javax.microedition.pim.PIM.toSerialFormat
 +
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= <!-- After re-review: [[User:username]] -->
 +
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 +
|update-by= <!-- After significant update: [[User:username]]-->
 +
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 +
|creationdate= 20081127
 +
|author= [[User:Dekudin]]
 +
<!-- The following are not in current metadata -->
 +
|subcategory= Calendar
 +
|id= CS001186
 
}}
 
}}
  
 
==Overview==
 
==Overview==
  
This code snippet demonstrates how to export calendar events to file in specified format.
+
This code snippet demonstrates how to export calendar events to a file in a specified format.
  
To export calendar event to file following steps should be performed:
+
To export a calendar event to a file:
# Get list of available formats for exporting event records by calling <tt>PIM.supportedSerialFormats</tt>. In this snippet first avaliable format from list will be used.
+
# Get a list of available formats for exporting event records by calling {{Icode|PIM.supportedSerialFormats}}. In this snippet, the first avaliable format from the list is used.
# Open file and create output stream to it.
+
# Open the file and create an output stream to it.
# Give output file stream, event that should be exported, encoding and format name as parameters to <tt>PIM.toSerialFormat</tt> method. This method exports event to file using specified format and encoding.
+
# Give the output file stream, the event that should be exported, encoding and format name as parameters to the {{Icode|PIM.toSerialFormat}} method. This method exports the event to a file using a specified format and encoding.
# Close file.
+
# Close the file.
  
  
Line 44: Line 59:
  
 
import java.util.Enumeration;
 
import java.util.Enumeration;
import java.util.Hashtable;
+
import java.util.Vector;
 
import java.io.OutputStream;
 
import java.io.OutputStream;
  
Line 59: Line 74:
 
     private Command cmdExit;
 
     private Command cmdExit;
  
     // Contains pairs "listIndex - eventUID" for finding event by index
+
     // Contains events retrieved from PIM event list.
    // of its presentation in eventListCtrl.
+
     private Vector eventsArray;
     private Hashtable indicesToIds;
+
 
      
 
      
 
     private final String EXPORT_FILENAME = "exportEvent.txt";
 
     private final String EXPORT_FILENAME = "exportEvent.txt";
Line 77: Line 91:
 
      
 
      
 
     /**
 
     /**
     * Initializes components of midlet.
+
     * Initialises components of MIDlet.
 
     */   
 
     */   
 
     private void initializeComponents() {
 
     private void initializeComponents() {
Line 117: Line 131:
 
         try {
 
         try {
 
             // Create hashtable.
 
             // Create hashtable.
             indicesToIds = new Hashtable();
+
             eventsArray = new Vector();
 
              
 
              
 
             // Get list of events.
 
             // Get list of events.
Line 130: Line 144:
 
             }
 
             }
 
                          
 
                          
            int index = 0;
 
 
             Enumeration events = eventList.items();
 
             Enumeration events = eventList.items();
 
             while(events.hasMoreElements() == true) {
 
             while(events.hasMoreElements() == true) {
 
                 Event event = (Event)events.nextElement();
 
                 Event event = (Event)events.nextElement();
 +
                // Add event to vector of events
 +
                eventsArray.addElement(event);
 +
                // Add event's summary to list control
 
                 String eventSummary = event.getString(Event.SUMMARY,  
 
                 String eventSummary = event.getString(Event.SUMMARY,  
 
                         PIMItem.ATTR_NONE);
 
                         PIMItem.ATTR_NONE);
                String eventUID = event.getString(Event.UID,
 
                        PIMItem.ATTR_NONE);
 
                // Add event's summary to list control
 
 
                 eventListCtrl.append(eventSummary, null);
 
                 eventListCtrl.append(eventSummary, null);
                // Add pair "listIndex - eventUID" of event to hashtable
 
                indicesToIds.put(new Integer(index++), eventUID);
 
 
             }
 
             }
 
              
 
              
Line 170: Line 181:
  
 
             // Get event
 
             // Get event
             Event event = getEventByUID(getCurrentEventUID());
+
            int eventIndex = eventListCtrl.getSelectedIndex();
 +
             Event event = (Event)eventsArray.elementAt(eventIndex);
 
             if(event == null) {
 
             if(event == null) {
 
                 throw new Exception("No events for exporting were found.");
 
                 throw new Exception("No events for exporting were found.");
Line 200: Line 212:
 
             showAlert("Error", exc.getMessage());
 
             showAlert("Error", exc.getMessage());
 
         }
 
         }
     }
+
     }  
   
+
    /**
+
    * Gets UID of currently selected event in list.
+
    * @return UID of current event.
+
    */
+
    private String getCurrentEventUID() {
+
        // Get index of current event from list.
+
        int currentIndex = eventListCtrl.getSelectedIndex();
+
        // Return UID of selected event.
+
        return (String)indicesToIds.get(new Integer(currentIndex));
+
    }
+
   
+
    /**
+
    * Gets event by its UID.
+
    * @param uid - UID of event.
+
    * @return event or null if such event was not found.
+
    */
+
    private Event getEventByUID(String uid) {
+
        if(uid == null) {
+
            return null;
+
        }
+
       
+
        try {
+
            // Get list of events.
+
            EventList eventList = (EventList)PIM.getInstance().openPIMList(
+
                    PIM.EVENT_LIST, PIM.READ_WRITE);
+
 
+
            // Search through list of events for event with specified uid.
+
            Enumeration events = eventList.items();
+
            while(events.hasMoreElements() == true) {
+
                Event event = (Event)events.nextElement();
+
                String eventUID = event.getString(Event.UID, PIMItem.ATTR_NONE);
+
               
+
                if(eventUID.equals(uid) == true) {
+
                    eventList.close();
+
                    return event;
+
                }
+
            }
+
           
+
            // Close list of events.
+
            eventList.close();
+
           
+
        } catch(Exception exc) {
+
            return null;
+
        }       
+
       
+
        return null;
+
    }   
+
  
 
     /**
 
     /**
Line 287: Line 251:
 
      
 
      
 
     /**
 
     /**
     * Performs exit from midlet.
+
     * Performs exit from MIDlet.
 
     */     
 
     */     
 
     private void exitMIDlet() {
 
     private void exitMIDlet() {
Line 316: Line 280:
 
==Postconditions==
 
==Postconditions==
  
This code snippet represents midlet with list control, which contains summaries of events from PIM list of calendar events.  
+
This code snippet represents the MIDlet with a list control, which contains summaries of events from the PIM list of calendar events.  
  
By choosing event in list and pressing "Export event" menu command user can export selected event to file.  
+
By choosing an event from the list and pressing the "Export event" menu command the user can export the selected event to file.  
  
File with exported event will be created in root directory of memory card and have name as EXPORT_FILENAME constant. Event format will be chosen from list of provided formats, exported file will have utf-8 character encoding.
+
The file with the exported event will be created in the root directory of the memory card and have the name EXPORT_FILENAME constant. The event format will be chosen from the list of provided formats. The exported file will have UTF-8 character encoding.
  
 
==Supplementary material==
 
==Supplementary material==
  
Executables and source files can be found in [[Media:ExportingCalendarEvent.zip]]
+
Executables and source files are available at [[Media:ExportingCalendarEvent.zip]].
 
+
[[Category:Java ME]][[Category:Code Examples]]
+

Revision as of 07:57, 2 October 2012

Article Metadata
Code ExampleTested with
Devices(s): Nokia E70, Nokia C3-01, Nokia Asha 306, Nokia E7-00
CompatibilityArticle
Keywords: javax.microedition.pim.EventList, javax.microedition.pim.Event, javax.microedition.pim.PIM.supportedSerialFormats, javax.microedition.pim.PIM.toSerialFormat
Created: dekudin (27 Nov 2008)
Last edited: hamishwillee (02 Oct 2012)

Contents

Overview

This code snippet demonstrates how to export calendar events to a file in a specified format.

To export a calendar event to a file:

  1. Get a list of available formats for exporting event records by calling PIM.supportedSerialFormats. In this snippet, the first avaliable format from the list is used.
  2. Open the file and create an output stream to it.
  3. Give the output file stream, the event that should be exported, encoding and format name as parameters to the PIM.toSerialFormat method. This method exports the event to a file using a specified format and encoding.
  4. Close the file.


Source file: ExportCalendarEvent.java

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Alert;
 
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMItem;
import javax.microedition.pim.EventList;
import javax.microedition.pim.Event;
import javax.microedition.pim.PIMException;
 
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
 
import java.util.Enumeration;
import java.util.Vector;
import java.io.OutputStream;
 
public class ExportCalendarEvent extends MIDlet implements CommandListener {
 
private Display display;
 
// List where events will be placed.
private List eventListCtrl;
 
// Command for exporting selected event. Placed on eventListCtrl.
private Command cmdExportEvent;
// Command for exiting from application. Placed on eventListCtrl.
private Command cmdExit;
 
// Contains events retrieved from PIM event list.
private Vector eventsArray;
 
private final String EXPORT_FILENAME = "exportEvent.txt";
 
/**
* Constructor
*/

public ExportCalendarEvent() {
if(checkPIMSupport() == false) {
exitMIDlet();
}
 
initializeComponents();
}
 
/**
* Initialises components of MIDlet.
*/

private void initializeComponents() {
// Get display
display = Display.getDisplay(this);
 
// Create list control
eventListCtrl = new List("Events", List.IMPLICIT);
 
cmdExportEvent = new Command("Export event", Command.SCREEN, 0);
eventListCtrl.addCommand(cmdExportEvent);
 
cmdExit = new Command("Exit", Command.EXIT, 0);
eventListCtrl.addCommand(cmdExit);
 
eventListCtrl.setCommandListener(this);
 
// Add events to list control.
addEventsToListCtrl();
}
 
/**
* Checks PIM support.
* @return - true if PIM is supported, false otherwise.
*/

private boolean checkPIMSupport() {
String propValue = System.getProperty("microedition.pim.version");
if(propValue != null) {
return true;
} else {
return false;
}
}
 
/**
* Adds events to list.
*/

private void addEventsToListCtrl() {
try {
// Create hashtable.
eventsArray = new Vector();
 
// Get list of events.
EventList eventList = (EventList)PIM.getInstance().openPIMList(
PIM.EVENT_LIST, PIM.READ_WRITE);
 
// Check if "summary" and "uid" fields of event item are supported.
// If not supported, exit from application.
if(eventList.isSupportedField(Event.SUMMARY) == false ||
eventList.isSupportedField(Event.UID) == false) {
throw new Exception();
}
 
Enumeration events = eventList.items();
while(events.hasMoreElements() == true) {
Event event = (Event)events.nextElement();
// Add event to vector of events
eventsArray.addElement(event);
// Add event's summary to list control
String eventSummary = event.getString(Event.SUMMARY,
PIMItem.ATTR_NONE);
eventListCtrl.append(eventSummary, null);
}
 
// Close list of events.
eventList.close();
 
} catch(PIMException pimExc) {
// TODO: Handle error on working with PIM.
} catch(SecurityException secExc) {
// TODO: Handle error on access to PIM.
} catch(Exception exc) {
// If unknown error was catched, exit from application.
exitMIDlet();
}
}
 
/**
* Exports selected event to file in private folder.
*/

private void exportEvent() {
try {
// Get supported formats.
PIM pimInst = PIM.getInstance();
String[] formats = pimInst.supportedSerialFormats(PIM.EVENT_LIST);
if(formats.length == 0) {
throw new Exception("No formats for event exporting were found.");
}
 
// Get event
int eventIndex = eventListCtrl.getSelectedIndex();
Event event = (Event)eventsArray.elementAt(eventIndex);
if(event == null) {
throw new Exception("No events for exporting were found.");
}
 
// Open file for exporting event.
String path = System.getProperty("fileconn.dir.memorycard");
String fileName = path + EXPORT_FILENAME;
 
FileConnection file = (FileConnection)Connector.open(fileName,
Connector.READ_WRITE);
 
// If there is no file then create it
if(file.exists() == false) {
file.create();
}
 
// Export event.
OutputStream outStream = file.openOutputStream();
pimInst.toSerialFormat(event, outStream, "UTF-8", formats[0]);
 
// Close file.
outStream.close();
file.close();
 
showAlert("Info", "Event has been exported to " + fileName);
 
} catch(Exception exc) {
showAlert("Error", exc.getMessage());
}
}
 
/**
* Shows alert with specified title and text.
* @param title - Title of alert.
* @param message - text of alert.
*/

private void showAlert(String title, String message) {
Alert alert = new Alert(title);
alert.setString(message);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
 
/**
* From MIDlet.
* Signals the MIDlet that it has entered the Active state.
*/

public void startApp() {
display.setCurrent(eventListCtrl);
}
 
/**
* From MIDlet.
* Signals the MIDlet to enter the Paused state.
*/

public void pauseApp() {
// No implementation required.
}
 
/**
* From MIDlet.
* Signals the MIDlet to terminate and enter the Destroyed state.
*/

public void destroyApp(boolean unconditional) {
// No implementation required.
}
 
/**
* Performs exit from MIDlet.
*/

private void exitMIDlet() {
notifyDestroyed();
}
 
/**
* From CommandListener.
* Indicates that a command event has occurred on Displayable displayable.
* @param command - a Command object identifying the command.
* @param displayable - the Displayable on which this event has occurred.
*/

public void commandAction(Command command, Displayable displayable) {
// Handles "show details" command on selected event.
if(command == cmdExportEvent) {
exportEvent();
}
// Handles "exit" command.
if(command == cmdExit) {
exitMIDlet();
}
}
}


Postconditions

This code snippet represents the MIDlet with a list control, which contains summaries of events from the PIM list of calendar events.

By choosing an event from the list and pressing the "Export event" menu command the user can export the selected event to file.

The file with the exported event will be created in the root directory of the memory card and have the name EXPORT_FILENAME constant. The event format will be chosen from the list of provided formats. The exported file will have UTF-8 character encoding.

Supplementary material

Executables and source files are available at Media:ExportingCalendarEvent.zip.

125 page views in the last 30 days.
×