×
Namespaces

Variants
Actions
(Difference between revisions)

Exporting phonebook contact in vCard format in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
kiran10182 (Talk | contribs)
m
hamishwillee (Talk | contribs)
m (Hamishwillee - Add Abstract. Tidy wiki text)
(17 intermediate revisions by 7 users not shown)
Line 1: Line 1:
__NOTOC__
+
[[Category:Java ME]][[Category:PIM]][[Category:File Connection and PIM API (JSR-75)]][[Category:Series 40]][[Category:Symbian]][[Category:Series 40 3rd Edition FP1]][[Category:S60 3rd Edition (initial release)]][[Category:S60 3rd Edition FP1]][[Category:S60 3rd Edition FP2]][[Category:Series 40 6th Edition FP1]][[Category:Series 40 Developer Platform 2.0]][[Category:Nokia Belle]][[Category:Code Examples]]
__NOEDITSECTION__
+
{{Abstract|This code example demonstrates how to export contacts from phonebook to a file in vCard format. }}
{{CodeSnippet
+
 
|id= 
+
{{ArticleMetaData <!-- v1.2 -->
|platform=S60 3rd Edition, FP2
+
|sourcecode= [[Media:ExportingContact.zip]]
|devices=Nokia E65, Nokia E70
+
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|category=Java ME
+
|devices= Nokia 6131, Nokia E65, Nokia E70, Nokia C3-01, Nokia Asha 306, Nokia E7-00
|subcategory=Phonebook/Contacts DB
+
|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]
|creationdate=November 1, 2008
+
|platform= Series 40, S60, Nokia Belle
|keywords=javax.microedition.pim.PIM, javax.microedition.pim.ContactList, javax.microedition.pim.Contact, javax.microedition.pim.PIM.supportedSerialFormats, javax.microedition.pim.PIM.toSerialFormat
+
|devicecompatability= <!-- Compatible devices (e.g.: All* (must have GPS) ) -->
 +
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
 +
|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.PIM, javax.microedition.pim.ContactList, javax.microedition.pim.Contact, 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 -->
 +
|id= CS001210
 
}}
 
}}
  
 
==Overview==
 
==Overview==
  
This code snippet demonstrates how to export contact from phonebook to file in vCard format.  
+
To export a phonebook contact to a file, perform the following steps:
 +
# Get a list of available formats for exporting contact records by calling {{Icode|PIM.supportedSerialFormats}}. In this example user selects the format.
 +
# Open a file and create an output stream to it.
 +
# Get a contact from the list of contacts. In this example, the first contact from the list of contacts will be used.
 +
# Set output file stream, the contact that should be exported, encoding, and format name as parameters in {{Icode|PIM.toSerialFormat}} method. This method exports an event to a file using the specified format and encoding.
 +
# Close the file.
  
To export phonebook contact to file following steps should be performed:
 
# Get list of available formats for exporting contact records by calling <tt>PIM.supportedSerialFormats</tt>. In this snippet user will select format.
 
# Open file and create output stream to it.
 
# Get contact from list of contacts. In this snippet first contact from list of contacts will be used.
 
# Set output file stream, contact that should be exported, encoding and format name as parameters in <tt>PIM.toSerialFormat</tt> method. This method exports event to file using specified format and encoding.
 
# Close file.
 
  
 
==Source file: ExportContact.java==
 
==Source file: ExportContact.java==
Line 37: Line 52:
 
import javax.microedition.pim.ContactList;
 
import javax.microedition.pim.ContactList;
 
import javax.microedition.pim.Contact;
 
import javax.microedition.pim.Contact;
 +
import javax.microedition.pim.PIMException;
  
 
import javax.microedition.io.Connector;
 
import javax.microedition.io.Connector;
 
import javax.microedition.io.file.FileConnection;
 
import javax.microedition.io.file.FileConnection;
  
import java.util.Enumeration;
+
import java.io.IOException;
 
import java.io.OutputStream;
 
import java.io.OutputStream;
 +
 +
import java.util.Enumeration;
  
  
Line 80: Line 98:
 
         formatsList = new List("Choose vCard version", List.IMPLICIT);
 
         formatsList = new List("Choose vCard version", List.IMPLICIT);
  
         cmdExportContact = new Command("Export first contact", Command.SCREEN, 0);
+
         cmdExportContact = new Command("Export first contact", Command.OK, 0);
 
         formatsList.addCommand(cmdExportContact);
 
         formatsList.addCommand(cmdExportContact);
 
          
 
          
Line 97: Line 115:
 
     private boolean checkPIMSupport() {
 
     private boolean checkPIMSupport() {
 
         String propValue = System.getProperty("microedition.pim.version");
 
         String propValue = System.getProperty("microedition.pim.version");
         if(propValue != null) {
+
         return (propValue != null);
            return true;
+
        } else {
+
            return false;
+
        }
+
 
     }     
 
     }     
  
Line 125: Line 139:
 
     */
 
     */
 
     private void exportContact(String exportFormat) {
 
     private void exportContact(String exportFormat) {
 +
        FileConnection file = null;
 +
        OutputStream outStream = null;
 +
               
 
         try {
 
         try {
 
             // Get first contact
 
             // Get first contact
 
             Contact firstContact = getFirstContact();
 
             Contact firstContact = getFirstContact();
 +
            if(firstContact == null) {
 +
                throw new Exception("Contact list is empty.");
 +
            }
  
 
             // Create filename string
 
             // Create filename string
 
             String path = System.getProperty("fileconn.dir.memorycard");
 
             String path = System.getProperty("fileconn.dir.memorycard");
 
             if(path == null) {
 
             if(path == null) {
                 throw new Exception("Unable to get path to memorycard root directory.");
+
                 throw new Exception("Unable to get path to private directory.");
 
             }
 
             }
 
             String fileName = path + EXPORT_FILENAME;
 
             String fileName = path + EXPORT_FILENAME;
 
             // Open file for writing
 
             // Open file for writing
             FileConnection file = (FileConnection)Connector.open(fileName,  
+
             file = (FileConnection)Connector.open(fileName,  
 
                     Connector.READ_WRITE);
 
                     Connector.READ_WRITE);
 
             // If there is no file then create it
 
             // If there is no file then create it
Line 144: Line 164:
  
 
             // Export contact.
 
             // Export contact.
             OutputStream outStream = file.openOutputStream();
+
             outStream = file.openOutputStream();
 
             PIM.getInstance().toSerialFormat(firstContact, outStream, "UTF-8",  
 
             PIM.getInstance().toSerialFormat(firstContact, outStream, "UTF-8",  
 
                     exportFormat);
 
                     exportFormat);
 
            // Close file.
 
            outStream.close();
 
            file.close();
 
  
 
             showAlert("Info", "First contact was exported in " + fileName);
 
             showAlert("Info", "First contact was exported in " + fileName);
  
 +
        } catch(IOException ioExc) {
 +
            showAlert("IO error", ioExc.getMessage());
 +
        } catch(PIMException pimExc) {
 +
            showAlert("PIM error", pimExc.getMessage());
 
         } catch(Exception exc) {
 
         } catch(Exception exc) {
             showAlert("Error", exc.toString());
+
             showAlert("Error", exc.getMessage());
 +
        } finally {
 +
            // Try to close file.
 +
            try {
 +
                if(outStream != null) {
 +
                    outStream.close();
 +
                }
 +
                if(file != null) {
 +
                    file.close();
 +
                }
 +
            } catch(Exception exc) {
 +
                // Do nothing.
 +
            }
 
         }
 
         }
 
     }
 
     }
Line 165: Line 197:
 
     */
 
     */
 
     private Contact getFirstContact() {
 
     private Contact getFirstContact() {
 +
        ContactList contactList = null;
 +
        Contact contact = null;
 +
       
 
         try {
 
         try {
 
             PIM pimInst = PIM.getInstance();
 
             PIM pimInst = PIM.getInstance();
             ContactList contactList = (ContactList)pimInst.openPIMList(
+
             contactList = (ContactList)pimInst.openPIMList(
 
                     PIM.CONTACT_LIST, PIM.READ_WRITE);
 
                     PIM.CONTACT_LIST, PIM.READ_WRITE);
  
Line 176: Line 211:
 
             }
 
             }
  
             Contact contact = (Contact)contactEnum.nextElement();
+
             contact = (Contact)contactEnum.nextElement();
            contactList.close();
+
        } catch(PIMException pimExc) {
             return contact;
+
             contact = null;
              
+
        } finally {
        } catch(Exception exc) {
+
             // Try to close pim list
             return null;
+
            if(contactList != null) {
 +
                try {
 +
                    contactList.close();
 +
                } catch(Exception exc) {
 +
                    // Do nothing.
 +
                }
 +
             }
 
         }
 
         }
 +
       
 +
        return contact;
 
     }
 
     }
 
      
 
      
Line 250: Line 293:
 
==Postconditions==
 
==Postconditions==
  
List of supported versions of vCard format is shown on display.  
+
List of supported versions of the vCard format is shown on display.  
  
By choosing version of vCard format in list and pressing "Export first contact" menu command user can export first contact from phonebook to file. File will be created in root directory of memory card and will have name as EXPORT_FILENAME constant.
+
The user can export the first contact from the phonebook to file by choosing a version of vCard format from the list and pressing "Export first contact". The file will be created in the root directory of the memory card and will have the name of EXPORT_FILENAME constant.
  
 
==Supplementary material==
 
==Supplementary material==
  
Executables and source files can be found in [[Media:ExportingContact.zip|ExportingContact.zip]]
+
Executables and source files can be found in [[Media:ExportingContact.zip]].
 
+
[[Category:Java ME]][[Category:Code Examples]][[Category:PIM]]
+

Revision as of 09:51, 5 October 2012

This code example demonstrates how to export contacts from phonebook to a file in vCard format.

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

Contents

Overview

To export a phonebook contact to a file, perform the following steps:

  1. Get a list of available formats for exporting contact records by calling PIM.supportedSerialFormats. In this example user selects the format.
  2. Open a file and create an output stream to it.
  3. Get a contact from the list of contacts. In this example, the first contact from the list of contacts will be used.
  4. Set output file stream, the contact that should be exported, encoding, and format name as parameters in PIM.toSerialFormat method. This method exports an event to a file using the specified format and encoding.
  5. Close the file.


Source file: ExportContact.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.ContactList;
import javax.microedition.pim.Contact;
import javax.microedition.pim.PIMException;
 
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
 
import java.io.IOException;
import java.io.OutputStream;
 
import java.util.Enumeration;
 
 
public class ExportContact extends MIDlet implements CommandListener {
 
private Display display;
 
// List for displaying vCard formats.
private List formatsList;
 
// Command for exporting first contact in list contacts.
private Command cmdExportContact;
// Command for exiting from application.
private Command cmdExit;
 
private final String EXPORT_FILENAME = "exportedContact.vcf";
 
/**
* Constructor
*/

public ExportContact() {
if(checkPIMSupport() == false) {
exitMIDlet();
}
 
initializeComponents();
}
 
/**
* Initializes components of midlet.
*/

private void initializeComponents() {
// Get display
display = Display.getDisplay(this);
 
// Create list control
formatsList = new List("Choose vCard version", List.IMPLICIT);
 
cmdExportContact = new Command("Export first contact", Command.OK, 0);
formatsList.addCommand(cmdExportContact);
 
cmdExit = new Command("Exit", Command.EXIT, 0);
formatsList.addCommand(cmdExit);
 
formatsList.setCommandListener(this);
 
showVCardVersions();
}
 
/**
* Checks PIM support.
* @return - true if PIM is supported, false otherwise.
*/

private boolean checkPIMSupport() {
String propValue = System.getProperty("microedition.pim.version");
return (propValue != null);
}
 
/**
* Gets supported vCard formats and adds it to formatList.
*/

private void showVCardVersions() {
// Get supported formats for exporting contacts.
PIM pimInst = PIM.getInstance();
String[] formats = pimInst.supportedSerialFormats(PIM.CONTACT_LIST);
 
int formatsCount = formats.length;
for(int index = 0; index < formatsCount; ++index) {
String format = formats[index];
if(format.startsWith("VCARD") == true) {
formatsList.append(formats[index], null);
}
}
}
 
/**
* Exports selected event to file in private folder.
*/

private void exportContact(String exportFormat) {
FileConnection file = null;
OutputStream outStream = null;
 
try {
// Get first contact
Contact firstContact = getFirstContact();
if(firstContact == null) {
throw new Exception("Contact list is empty.");
}
 
// Create filename string
String path = System.getProperty("fileconn.dir.memorycard");
if(path == null) {
throw new Exception("Unable to get path to private directory.");
}
String fileName = path + EXPORT_FILENAME;
// Open file for writing
file = (FileConnection)Connector.open(fileName,
Connector.READ_WRITE);
// If there is no file then create it
if(file.exists() == false) {
file.create();
}
 
// Export contact.
outStream = file.openOutputStream();
PIM.getInstance().toSerialFormat(firstContact, outStream, "UTF-8",
exportFormat);
 
showAlert("Info", "First contact was exported in " + fileName);
 
} catch(IOException ioExc) {
showAlert("IO error", ioExc.getMessage());
} catch(PIMException pimExc) {
showAlert("PIM error", pimExc.getMessage());
} catch(Exception exc) {
showAlert("Error", exc.getMessage());
} finally {
// Try to close file.
try {
if(outStream != null) {
outStream.close();
}
if(file != null) {
file.close();
}
} catch(Exception exc) {
// Do nothing.
}
}
}
 
/**
* Returns first contact from phonebook
* @return first contact from phonebook or null if no contacts were found
* or error occurs.
*/

private Contact getFirstContact() {
ContactList contactList = null;
Contact contact = null;
 
try {
PIM pimInst = PIM.getInstance();
contactList = (ContactList)pimInst.openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
 
Enumeration contactEnum = contactList.items();
if(contactEnum.hasMoreElements() == false) {
contactList.close();
return null;
}
 
contact = (Contact)contactEnum.nextElement();
} catch(PIMException pimExc) {
contact = null;
} finally {
// Try to close pim list
if(contactList != null) {
try {
contactList.close();
} catch(Exception exc) {
// Do nothing.
}
}
}
 
return contact;
}
 
/**
* 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(formatsList);
}
 
/**
* 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) {
if(command == cmdExportContact) {
int selectIndex = formatsList.getSelectedIndex();
exportContact(formatsList.getString(selectIndex));
}
if(command == cmdExit) {
exitMIDlet();
}
}
}


Postconditions

List of supported versions of the vCard format is shown on display.

The user can export the first contact from the phonebook to file by choosing a version of vCard format from the list and pressing "Export first contact". The file will be created in the root directory of the memory card and will have the name of EXPORT_FILENAME constant.

Supplementary material

Executables and source files can be found in Media:ExportingContact.zip.

121 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×