×
Namespaces

Variants
Actions
(Difference between revisions)

Importing a Phonebook contact in vCard format in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
Forum Nokia KB (Talk | contribs)
m (Protected "Importing phonebook contact in vCard format in Java ME" [edit=sysop:move=sysop])
Forum Nokia KB (Talk | contribs)

Revision as of 17:15, 4 December 2008


Article Metadata
Tested with
Devices(s): Nokia E65
CompatibilityArticle
Keywords: javax.microedition.pim.PIM, javax.microedition.pim.ContactList, javax.microedition.pim.Contact, javax.microedition.pim.PIM.fromSerialFormat, javax.microedition.pim.ContactList.importContact, javax.microedition.pim.Contact.commit
Created: (01 Nov 2008)
Last edited: Forum Nokia KB (04 Dec 2008)

Overview

This code snippet demonstrates how to import contact from file to phonebook.

To import phonebook contact from file following steps should be performed:

  1. Open file contains data for contact and open input stream from this file.
  2. Set input stream as parameter in PIM.fromSerialFormat. This method returns array of imported PIM items. There are could be not only conact items in treturned array - so additional checking is needed.
  3. Make a copy of each imported contact by calling ContactList.importContact method of already opened list.
  4. Save each copy in contacts list by executing Contact.commit method on each copied contact object.
  5. Close file.

This midlet imports contacts from files in "UTF-8" character encoding format without any transfer character encoding. Contact data in file should be in vCard format.

Source file: ImportContact.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.ContactList;
import javax.microedition.pim.Contact;
import javax.microedition.pim.PIMException;
 
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
 
import java.util.Enumeration;
import java.io.InputStream;
 
public class ImportContact extends MIDlet implements CommandListener {
 
private Display display;
 
// List where contacts will be placed.
private List contactListCtrl;
 
// Command for exporting selected contact. Placed on contactListCtrl.
private Command cmdImportContact;
// Command for exiting from application. Placed on contactListCtrl.
private Command cmdExit;
 
// Name of file with contact data to be imported.
private final String IMPORT_FILENAME = "importcontact.vcf";
 
/**
* Constructor
*/

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

private void initializeComponents() {
// Get display
display = Display.getDisplay(this);
 
// Create list control
contactListCtrl = new List("contacts", List.IMPLICIT);
 
cmdImportContact = new Command("Import contact", Command.SCREEN, 0);
contactListCtrl.addCommand(cmdImportContact);
 
cmdExit = new Command("Exit", Command.EXIT, 0);
contactListCtrl.addCommand(cmdExit);
 
contactListCtrl.setCommandListener(this);
 
// Add contacts to list control.
addContactsToListCtrl();
}
 
/**
* 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 contacts to list.
*/

private void addContactsToListCtrl() {
try {
// Get list of contacts.
ContactList contactList = (ContactList)PIM.getInstance().openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
 
// Check if "name" field of contact item is supported.
// If not supported, exit from application.
if(contactList.isSupportedField(Contact.NAME) == false) {
throw new Exception();
}
 
// Clear list control.
contactListCtrl.deleteAll();
 
// Add contacts to list control.
Enumeration contacts = contactList.items();
while(contacts.hasMoreElements() == true) {
Contact contact = (Contact)contacts.nextElement();
String[] name = contact.getStringArray(Contact.NAME,
PIMItem.ATTR_NONE);
String family = name[Contact.NAME_FAMILY];
// Add contact's summary to list control
contactListCtrl.append(family, null);
}
 
// Close list of contacts.
contactList.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();
}
}
 
/**
* Import contact from file placed private folder.
* @return true if contact was imported successfully, false - otherwise.
*/

private boolean importContactFromFile() {
try {
// Open file for importing contact.
String path = System.getProperty("fileconn.dir.memorycard");
String fileName = path + IMPORT_FILENAME;
 
FileConnection file = (FileConnection)Connector.open(fileName,
Connector.READ_WRITE);
 
// If there is no file then create it
if(file.exists() == false) {
throw new Exception("File for importing was not found.");
}
 
// Export contact.
InputStream inStream = file.openInputStream();
 
PIMItem[] items = PIM.getInstance().fromSerialFormat(inStream, "UTF-8");
// Assume what there is only one contact item in file.
if(items.length > 0) {
importContactToList((Contact)items[0]);
}
 
// Close file.
inStream.close();
file.close();
 
showAlert("Info", "Contact was imported from file.");
 
} catch(Exception exc) {
showAlert("Error", exc.getMessage());
return false;
}
 
return true;
}
 
/**
* Imports contact to phonebook list of contacts.
* @param importedContact - contact to be imported.
* @throws javax.microedition.pim.PIMException - on PIM error.
*/

private void importContactToList(Contact importedContact)
throws PIMException {
// Open list of contacts
ContactList contactList = (ContactList)PIM.getInstance().openPIMList(
PIM.CONTACT_LIST, PIM.READ_WRITE);
 
// contact list creates new contact based on imported contact
Contact newcontact = contactList.importContact(importedContact);
 
// Save new contact to list
newcontact.commit();
// Close list of contacts
contactList.close();
}
 
/**
* 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(contactListCtrl);
}
 
/**
* 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 contact has occurred on Displayable displayable.
* @param command - a Command object identifying the command.
* @param displayable - the Displayable on which this contact has occurred.
*/

public void commandAction(Command command, Displayable displayable) {
// Handles "show details" command on selected contact.
if(command == cmdImportContact) {
if(importContactFromFile() == true) {
addContactsToListCtrl();
}
}
// Handles "exit" command.
if(command == cmdExit) {
exitMIDlet();
}
}
}


Postconditions

List of phonebook contacts is shown on display.

By pressing "Import contact" menu command user can import contact from file. File with contact to be imported should be placed in root directory of memory card and have name as IMPORT_FILENAME constant. After importing contact list control will display changes in phonebook contact list.

Supplementary material

Executables and source files can be found in ImportingContact.zip

139 page views in the last 30 days.
×