×
Namespaces

Variants
Actions
(Difference between revisions)

Importing a Phonebook contact in vCard format in Java ME

From Nokia Developer Wiki
Jump to: navigation, search
seppo_fn (Talk | contribs)
hamishwillee (Talk | contribs)
m (Hamishwillee - Add Abstract. Improve categories)
(13 intermediate revisions by 5 users not shown)
Line 1: Line 1:
__NOTOC__
+
[[Category:Java ME]][[Category:PIM]][[Category:File Connection and PIM API (JSR-75)]][[Category:Code Snippet]][[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:S60 5th Edition]]
__NOEDITSECTION__
+
{{Abstract|This code snippet demonstrates how to import a contact from a file to the Phonebook application. }}
{{CodeSnippet
+
 
|id= 
+
{{ArticleMetaData <!-- v1.2 -->
|platform=S60 3rd Edition, FP1
+
|sourcecode= [[Media:ImportingContact.zip]]
|devices=Nokia E65
+
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|category=Java ME
+
|devices= Nokia 6131, Nokia E65, Nokia C3-01, Nokia Asha 306, Nokia E7-00
|subcategory=Phonebook/ContactsDB
+
|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.fromSerialFormat, javax.microedition.pim.ContactList.importContact, javax.microedition.pim.Contact.commit
+
|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.fromSerialFormat, javax.microedition.pim.ContactList.importContact, javax.microedition.pim.Contact.commit
 +
|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= CS001187
 
}}
 
}}
  
 
==Overview==
 
==Overview==
  
This code snippet demonstrates how to import contact from file to phonebook.
+
To import a Phonebook contact from a file:
 
+
# Open the file that contains data for the contact and open the input stream from this file.
To import phonebook contact from file following steps should be performed:
+
# Set the input stream as the parameter in {{Icode|PIM.fromSerialFormat}}. This method returns an array of imported PIM items. The returned array may contain also other information, so additional checking is needed.
# Open file contains data for contact and open input stream from this file.
+
# Make a copy of each imported contact by calling the {{Icode|ContactList.importContact}} method of the already opened list.
# Set input stream as parameter in <tt>PIM.fromSerialFormat</tt>. This method returns array of imported PIM items. There are could be not only conact items in treturned array - so additional checking is needed.
+
# Save each copy in the contacts list by executing the {{Icode|Contact.commit}} method on each copied contact object.
# Make a copy of each imported contact by calling <tt>ContactList.importContact</tt> method of already opened list.
+
# Close the file.
# Save each copy in contacts list by executing <tt>Contact.commit</tt> method on each copied contact object.
+
# 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.
+
This MIDlet imports contacts from files in UTF-8 format without any transfer character encoding. Contact data in the file should be in vCard format.
  
 
==Source file: ImportContact.java==
 
==Source file: ImportContact.java==
Line 280: Line 294:
 
==Postconditions==
 
==Postconditions==
  
List of phonebook contacts is shown on display.  
+
A list of phonebook contacts is shown on the 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.
+
By pressing the "Import contact" menu command the user can import a contact from the file. The file with contact to be imported should be in the root directory of the memory card and named IMPORT_FILENAME constant. After importing, the contact list control displays the changes in the Phonebook contact list.
  
 
==Supplementary material==
 
==Supplementary material==
  
Executables and source files can be found in [[Media:ImportingContact.zip|ImportingContact.zip]]
+
Executables and source files are available at [[Media:ImportingContact.zip]].
 
+
[[Category:Java ME]][[Category:Code Examples]][[Category:PIM]][[Category:File Connection and PIM API (JSR-75)]]
+

Revision as of 09:59, 15 October 2012

This code snippet demonstrates how to import a contact from a file to the Phonebook application.

Article Metadata
Code ExampleTested with
Devices(s): Nokia 6131, Nokia E65, 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.fromSerialFormat, javax.microedition.pim.ContactList.importContact, javax.microedition.pim.Contact.commit
Created: dekudin (27 Nov 2008)
Last edited: hamishwillee (15 Oct 2012)

Contents

Overview

To import a Phonebook contact from a file:

  1. Open the file that contains data for the contact and open the input stream from this file.
  2. Set the input stream as the parameter in PIM.fromSerialFormat. This method returns an array of imported PIM items. The returned array may contain also other information, so additional checking is needed.
  3. Make a copy of each imported contact by calling the ContactList.importContact method of the already opened list.
  4. Save each copy in the contacts list by executing the Contact.commit method on each copied contact object.
  5. Close the file.

This MIDlet imports contacts from files in UTF-8 format without any transfer character encoding. Contact data in the 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

A list of phonebook contacts is shown on the display.

By pressing the "Import contact" menu command the user can import a contact from the file. The file with contact to be imported should be in the root directory of the memory card and named IMPORT_FILENAME constant. After importing, the contact list control displays the changes in the Phonebook contact list.

Supplementary material

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

192 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.

×