Database Mobitex

  • Upload
    spak10

  • View
    226

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 Database Mobitex

    1/184

    Developers Guide

    BlackBerry

    Database API

    Version 2.0

  • 8/8/2019 Database Mobitex

    2/184

    BlackBerry -- Database API Developers Guide, Version 2.0Last revised 4/17/00

    Part Number PDF-02734-001

    1997-2000, RESEARCH IN MOTION LIMITED

    RIM, Research In Motion, the RIM logo, BlackBerry, and the BlackBerry logo aretrademarks of Research In Motion Limited. Research In Motion and RIM areregistered, U.S. Patent and Trademark Office.

    Complies with software O/S version 2.0 and applications version 2.0.

    Windows is a trademark of Microsoft Corporation. Intel is a registered trademark ofIntel Corporation.

    Warning: This document is for the use of licensed users only. Any unauthorizedcopying, distribution or disclosure of information is a violation of copyright laws.

    While every effort has been made to ensure technical accuracy, information in thisdocument is subject to change without notice and does not represent a commitmenton the part of Research In Motion Limited.

    Research In Motion Limited295 Phillip StreetWaterloo, OntarioCanada N2L 3W8Tel. (519) 888-7465Fax (519) 888-6906

    Web site: www.rim.netE-mail: [email protected]

    Printed In Canada KM0200/database api.doc

  • 8/8/2019 Database Mobitex

    3/184

  • 8/8/2019 Database Mobitex

    4/184

  • 8/8/2019 Database Mobitex

    5/184

    1.IntroductionThe Database API provides data storage solutions for developers creatingapplications for the BlackBerry. The database library manages memory andthe flash file system for the handheld.

    This document:

    Describes the developers experience

    Provides developers with instructions on using the Databaseapplication

    Provides developers with a complete listing of the Database APImembers

    About this guide

    This guide includes general information on the Database API, as well asa complete listing of all its functions.

    Throughout this guide, the simulator will be referred to as theBlackBerry simulator.

    Note Notes provide additional information to help complete a task.

    Tip Tips offer an alternative method of performing an action

    WARNING Warnings follow any procedure or paragraph containinginstructions that, if followed improperly, could result indamaging the device or software.

    The names of program groups, icons, folders, windows, etc. will appearin bold text. An example is the Research In Motion program group.

  • 8/8/2019 Database Mobitex

    6/184

    6 Introduction About this guide

    Developers Guide BlackBerry

    Menu options, menu names, fields, tabs, checkboxes etc. will appear inArialfont. References to buttons will also appear in this fashion, with thehot key underlined where applicable. An example would be the Next>button.

    All programming elements such as returns, events, constants, structures,parameters, etc. will appear in Courier New font. An example would bethe COMM_RX_ERROR error code.

  • 8/8/2019 Database Mobitex

    7/184

    2.Programming tutorialThe database library for the BlackBerry Handheld provides theapplication developer with a rich set of database functions, and abstractsthe complicated details of the file system. The library manages memoryand the flash file system, and is designed for efficiency and ease-of-use.

    This chapter guides you through the basic programming experience of

    working with the Database API. The source code for the sampleapplication is included with the BlackBerrySoftware Developers Kit.The following procedures are intended to give an overview of some ofthe databases capabilities; for more details on how to use these andother features of the Database API, please refer to the API referencesection of this document.

    Class level descriptions

    Database

    The Database can store multiple FlashObjects (orDatabaseRecords) which store data in a format specified by thedeveloper. The Database is responsible for saving data to flash, and forupdating a list of database views attached to it. A Database may beautomatically backed up and restored.

    FlashObject

    A FlashObject corresponds to a fixed-size structure that can be used tostore data in a format specified by the developer. It can be thought of asa C structure that can be stored in flash as well as in RAM. AFlashObject is the most efficient way to store data in a database, but asit does not allow for fields to be resized, the size must be fixed at compile

  • 8/8/2019 Database Mobitex

    8/184

    8 Programming tutorial Class level descriptions

    Developers Guide BlackBerry

    time. Each FlashObject must have an associated structure that isinherited from FlashObjectData. This structure is where the actualdata is stored. The FlashObject knows how to access its data structure,and also looks after loading it into RAM from flash and saving it to flashfrom RAM as necessary.

    DatabaseRecord

    A DatabaseRecord is another object that can be used to store data.Unlike a FlashObject, a DatabaseRecords fields are dynamicallysized. As such, it is best used for data with length that will vary at runtime, like character strings. Fields may also be added to and removedfrom a DatabaseRecord at run time. Each DatabaseRecord object mayhold up to 254 fields at any time, and a field type can be associated witheach field.

    DatabaseView

    Databases may have up to 16 views attached to them. Each view isupdated every time a record is added, updated or deleted. The followinglists the types of views available:

    DatabaseListView: This view stores an array of record handles.For example, the message screen uses a ListView to hold the

    handles of the message. DatabaseSortedListView: This view stores a sorted array of

    record handles. For example, the Address Book uses a sorted listview to hold record handles of the addresses.

    DatabaseIndexView: This view can be used to provide fastlookup of database record handles that match certain keywords.For each record, the application can insert many keywords intothe index. To search the index, a DatabaseSearchIndexView isused to perform and hold the results of the search.

    PersistentStore

    A PersistentStore can be used to store a small C-style data structurein flash. Example uses include storing user option settings.PersistentStore data may be automatically backed up and restored.

  • 8/8/2019 Database Mobitex

    9/184

    Programming tutorial Features of the Database API 9

    Developers Guide BlackBerry

    DataBuffer

    A DataBuffer can be used to hold an arbitrary amount of data. It maybe thought of as a simple stream object.

    Bitfield

    A Bitfield acts like an array of bits. Bit-oriented operations (set, clean,etc) can be performed on individual array entries, or on the array as awhole.

    DbrecordBitField

    The DbrecordBitField class is derived form the Bitfield class andprovides one bit for each possible record handle.

    Features of the Database API

    Storage of data

    The Database API is well-suited to many applications, especially those

    that have complex data management concerns. An Address Bookapplication, for instance, may contain hundreds of records that need tobe sorted quickly, and the user must be able to search through therecords without noticing any delay. Because the format of the data storedby the Database API can be defined statically or dynamically by anapplication, the data for almost any application could be stored using theDatabase API.

    Memory structure

    Limitations are imposed on the Database API by the device architecture.The most obvious of these is the limited memory available on the device.Currently the device has 2Mb of flash memory and 256K of RAMmemory that must be shared by all applications running on the device.The flash memory is divided into 64K blocks giving a hard upper limiton the amount of data that can be stored as a single block. Applicationdevelopers are advised that the file system is optimized for handling

  • 8/8/2019 Database Mobitex

    10/184

    10 Programming tutorial Setting up a database

    Developers Guide BlackBerry

    data stored either as short blocks (less than 80 bytes) or larger blocks(roughly 4K). Applications which require storage of data in blocks largerthan 20K should be reassessed to consider partitioning of the data.

    The Database API manages these concerns internally on an applications

    behalf. RAM is used only when necessary, so that other applications willhave as much RAM available as possible. Large blocks of data aresubdivided internally in many of the data structures, so that findinglarge contiguous blocks of Flash space becomes less of a concern.

    Compatibility with the UI Engine

    Since the Database API was developed at RIM alongside the otherapplications that run on the device, it was designed to work asseamlessly as possible with elements of the UI Engine, such as lists. A

    database list view, for example, can interact easily with the handle-baseddesign of the UI Engine list. The view manages a subset of the records ina database, and the UI Engine list displays only the handles in thatsubset.

    Setting up a database

    Setting up a database is straightforward. As an example, we will produce

    a simple Contact Manager application that stores names and associatedemail addresses.

    First, we will define classes to contain the data we plan to store. For thepurposes of this example, each contact will contain a first name, a lastname, and any number of email addresses. Since the number of emailaddresses is variable, we need to use a DatabaseRecord as the baseclass for a Contact.

    To set first name and last name

    1. Define a function called set_name.

    bool Contact::set_name( const char *

    first_name_ptr, const char* last_name_ptr )

    {

  • 8/8/2019 Database Mobitex

    11/184

    Programming tutorial Setting up a database 11

    Developers Guide BlackBerry

    2. Search for a field with the first name tag usingget_first_field_handle.

    DbFieldHandle first_name_handle =

    get_first_field_handle( FIELDTAG_FIRST_NAME );

    3. Update the field contents with the new name. If no first name fieldwas found, first_name_handle is NULL, and a new first name fieldwill be created.

    first_name_handle = update_field(

    first_name_handle, FIELDTAG_FIRST_NAME,

    first_name_ptr, DB_TEXT );

    4. Repeat steps 2 and 3 for the last name tag.

    DbFieldHandle last_name_handle =get_first_field_handle( FIELDTAG_LAST_NAME );

    last_name_handle = update_field( last_name_handle,

    FIELDTAG_LAST_NAME, last_name_ptr, DB_TEXT );

    return(

    first_name_handle != DB_INVALID_FIELD_HANDLE &&

    last_name_handle != DB_INVALID_FIELD_HANDLE);

    }

    To get first name and last name

    1. Define a function called get_name.

    bool Contact::get_name( char * & first_name_ptr,

    const char * & last_name_ptr )

    {

    2. Search for a field with the first name tag using

    get_first_field_handle.

    DbFieldHandle first_name_handle =

    get_first_field_handle( FIELDTAG_FIRST_NAME );

    if( first_name_handle == DB_INVALID_FIELD_HANDLE )

    {

  • 8/8/2019 Database Mobitex

    12/184

    12 Programming tutorial Setting up a database

    Developers Guide BlackBerry

    3. If no first name is found in the record, the return value is NULL.

    first_name_ptr = NULL;

    }

    4. Otherwise, return a pointer to the first name of the record usingget_field_data_ptr.

    else {

    first_name_ptr = (char*) get_field_data_ptr(

    first_name_handle );

    }

    5. Repeat steps 2 through 4 for the last_name tag.

    DbFieldHandle last_name_handle =

    get_first_field_handle( FIELDTAG_LAST_NAME );

    if( last_name_handle == DB_INVALID_FIELD_HANDLE )

    {

    last_name_ptr = NULL;

    }

    else {

    last_name_ptr = (char*) get_field_data_ptr(

    last_name_handle );

    }

    return true;

    }

    To add an email address

    1. Define a function called add_email.

    bool Contact::add_email( const char*email_address_ptr, DbFieldHandle field_handle )

    {

  • 8/8/2019 Database Mobitex

    13/184

    Programming tutorial Storing contacts 13

    Developers Guide BlackBerry

    2. If field_handle == DB_INVALID_FIELD_HANDLE, add a newemail field; if it is valid, update the existing field.

    DbFieldHandle new_email_handle = update_field(

    field_handle, FIELDTAG_EMAIL_ADDRESS,

    email_address_ptr, DB_TEXT );

    return( new_email_handle !=

    DB_INVALID_FIELD_HANDLE );

    }

    To remove an email address

    1. Define a function called remove_email.

    bool Contact::remove_email( DbFieldHandle

    email_field_handle )

    {

    2. Remove the field specified by email_field_handle.

    return( delete_field( email_field_handle ) );

    }

    Storing contactsWe need a database that will store our Contact objects as temporarystorage during backup and restore operations.

    To store contact objects

    1. Declare a Database object at global scope, and aDatabaseBusyStatus object that the database library will displayduring any processor-intensive operations, to inform the user thatwork is being done in the background

    DatabaseBusyStatus ContactBusyStatus;

    Database GlobalContactDatabase( "Contacts",

    &ContactBusyStatus)

  • 8/8/2019 Database Mobitex

    14/184

    14 Programming tutorial Displaying contacts in a list

    Developers Guide BlackBerry

    2. Declare a Contact object that the database will use for temporarystorage during backup and restore operations.

    Contact GlobalBRContact( GlobalContactDatabase );

    3. If the database is to use the backup and restore object that we havecreated, we must inform the database that it is available by addingthe following line to our PagerMain function:

    GlobalContactDatabase.set_backup_restore_object_ptr(

    &GlobalBRContact );

    Displaying contacts in a list

    Next, we would like to display the contact records in a sorted list. Aneasy way to sort the contacts would be to have aDatabaseSortedListView. We must define an object derived fromDatabaseSortedListView, and implement the compare_objects( )function so that the database library knows how to sort the contacts. Forour purposes, we will always sort by first name.

    To sort the contacts

    1. Define a function called compare_objects that the database library

    will call when objects need to be sorted.

    int ContactListView::compare_objects(

    DbRecordHandle contact_1_handle, DbRecordHandle

    contact_2_handle )

    {

    2. Construct the two objects to be compared (in this case namedcontact_1_handleandcontact_2_handle).

    Contact contact_1( GlobalContactDatabase,contact_1_handle );

    Contact contact_2( GlobalContactDatabase,

    contact_2_handle );

  • 8/8/2019 Database Mobitex

    15/184

    Programming tutorial Displaying contacts in a list 15

    Developers Guide BlackBerry

    3. Get the names of the contacts we are comparing using get_name.

    char * first_name_1, * first_name_2;

    char * last_name_1, * last_name_2;

    contact_1.get_name( first_name_1, last_name_1 );

    contact_2.get_name( first_name_2, last_name_2 );

    4. If the first contact has no first name, and the second contact does, thesecond contact should be placed first in the list.

    (If the second contact has no first name, we will sort based on lastname.)

    if( first_name_1 == NULL ) {

    // The first contact has no first name

    if( first_name_2 != NULL ) {

    // The second contact has a first name,

    // so it should go first.

    // Return > 0 to indicate the second one

    // should go first.

    return 1;

    }

    }

    5. If the first contact has a first name and the second does not, the firstcontact should be placed first in the list.

    else {

    if( first_name_2 == NULL ) {

    // Return < 0 to indicate

    // the first one should go first.

    return -1;

    }

  • 8/8/2019 Database Mobitex

    16/184

    16 Programming tutorial Displaying contacts in a list

    Developers Guide BlackBerry

    6. If both contacts have first names, the first names must be compared.

    (If they are equal, we will sort based on last name.)

    else {

    int strcmp_result =

    strcmp( first_name_1, first_name_2 );

    if (strcmp_result != 0 ) {

    // The first names are not equal,

    // so return the result of strcmp

    // to indicate which should come first.

    return( strcmp_result );

    }

    }

    7. If the contacts have the same first name, we will sort based on lastname in much the same way.

    }

    if( last_name_1 == NULL ) {

    // The first contact has no last name

    if( last_name_2 != NULL ) {

    // The second contact has a last name,

    // so it should go first.

    // Return > 0 to indicate

    // the second one should go first.

    return 1;

    }

    8. If both last names are NULL, the two contacts are equal.

    else {

    return 0;

    }

    }

  • 8/8/2019 Database Mobitex

    17/184

    Programming tutorial Defining another contact view 17

    Developers Guide BlackBerry

    9. If the second contact has no last name, the first contact should gofirst. Return < 0 to indicate that the first one should go first.

    else {

    if( first_name_2 == NULL ) {

    return -1;

    }

    10. If both contacts have last names, compare them and return the result.

    else {

    return( strcmp( last_name_1, last_name_2 ) );

    }

    }

    }

    Defining another contact viewWe want to define two views: one that contains all of the contacts in thedatabase, and one that contains only the contacts with email addresses.

    To decide whether a contact should appear in the email view, we need toimplement the is_view_member function.

    To define the email contact view1. Determine whether a particular contact should be included with the

    view of contacts with email addresses.

    bool ContactEmailListView::is_view_member(

    DbRecordHandle db_record_handle )

    {

    Contact contact( GlobalContactDatabase,

    db_record_handle );

    2. Search for an email address in the contact record. If there is one,return TRUE, because we want to include this record in the view.

    return( contact.get_first_email() !=

    DB_INVALID_FIELD_HANDLE );

    }

  • 8/8/2019 Database Mobitex

    18/184

    18 Programming tutorial Editing a contact

    Developers Guide BlackBerry

    Now, we can define user interface elements that correspond to thedatabase elements we have defined already. Details for all of the userinterface elements that are used in this example can be found in the UIEngine API document.

    Editing a contact

    First, we will define a class derived from Edit called ContactEdit thatwill keep track of a field handle and a field tag for the Edit field. Thatway, when the user is entering or editing a contact, we will always knowwhat type of data should be stored in the field. When the user attemptsto remove an email address, for example, the ContactEdit field willknow which field handle must be removed from the correspondingContact.

    To associate the data in an edit field withthe data in a record field

    1. Construct the Edit buffer. The data in each field can have amaximum length as specified by the constantMAXLEN_CONTACT_DATA.

    ContactEdit( const char* label_ptr,

    DbFieldTag tag = DB_INVALID_FIELD_TAG,

    DbFieldHandle handle = DB_INVALID_FIELD_HANDLE)

    : Edit( label_ptr, MAXLEN_CONTACT_DATA,

    MAXLEN_CONTACT_DATA )

    , m_field_handle( handle )

    , m_field_tag( tag )

    {}

    2. Return the field handle associated with this edit field.

    DbFieldHandle get_field_handle()

    {

    return( m_field_handle );

    }

    3. Return the field tag associated with this edit field.

    DbFieldTag get_field_tag()

    {

  • 8/8/2019 Database Mobitex

    19/184

    Programming tutorial Displaying a list using different views 19

    Developers Guide BlackBerry

    return( m_field_tag );

    }

    protected:

    DbFieldTag m_field_tag;

    DbFieldHandle m_field_handle;

    };

    We will also need a ContactList object, which is derived from the UIEngines List object. We want to be able to display a list for either oneof our views: the view of all Contacts, and the view of just theContacts with email addresses. The List object and theDatabaseListView object are designed to work together easily.

    Displaying a list using

    different viewsWhen the UI Engine wishes to display a particular record on the LCD, itwill call the NowDisplaying function, passing in the index in the listcorresponding to that record. The NowDisplaying function mustconvert the index to a record handle, so we need a get_handle memberfunction.

    This function checks whether all contacts or only email contacts are

    being displayed, and returns a handle from the appropriate view.DbRecordHandle ContactList::get_handle( int index )

    {

    if( m_show_all_contacts_flag ) {

    return( m_all_view[ index ] );

    }

    else {

    return( m_email_view[ index ] );

    }

    }

    Now we can define the NowDisplaying function. Its main task is toconvert a database record into a string that can be displayed on the LCD.

  • 8/8/2019 Database Mobitex

    20/184

    20 Programming tutorial Displaying a list using different views

    Developers Guide BlackBerry

    To display

    1. Define a function called NowDisplaying.

    void ContactList::NowDisplaying( const int index )

    {

    2. Get the record handle of the contact to be displayed.

    DbRecordHandle db_handle_to_display =

    get_handle( index );

    3. Construct the appropriate contact object.

    if( db_handle_to_display != DB_NULL_HANDLE )

    {

    Contact contact( GlobalContactDatabase,

    db_handle_to_display );

    4. Get the first and last names of the contact, and use RimSprintf() tocombine them into a single string.

    char full_name_buffer[ MAXLEN_CONTACT_DATA * 2 ];

    char * first_name_ptr, * last_name_ptr;

    contact.get_name( first_name_ptr, last_name_ptr );

    RimSprintf( full_name_buffer,

    sizeof(full_name_buffer), "%s%s%s",

    first_name_ptr ? first_name_ptr : "",

    first_name_ptr && last_name_ptr ? " " : "",

    last_name_ptr ? last_name_ptr : "" );

    5. Tell the UI Engine to display the string.

    PutColumn( full_name_buffer );

    }

    }

  • 8/8/2019 Database Mobitex

    21/184

    Programming tutorial Updating a list 21

    Developers Guide BlackBerry

    Updating a list

    When the number of entries in the list changes (for example, when weadd or remove an item from the view, or when we decide to show email

    contacts instead of all contacts), we need to update the UI Engine withthe new number of entries in the view.

    To update a list

    1. Define a function called update_num_entries.

    void ContactList::update_num_entries()

    {

    2. Depending on whether we are showing all contacts or just emailcontacts, tell the UI Engine how many handles are in the appropriateview.

    if( m_show_all_contacts_flag ) {

    SetNumEntries( m_all_view.get_num_handles() );

    }

    else {

    SetNumEntries( m_email_view.get_num_handles() );

    }

    3. Tell the UI Engine to Redraw the visible portion of the list in case ishas changed.

    Redraw();

    }

    To switch between the views

    1. Define a function calledshow_all

    .void ContactList::show_all( bool show_all_contacts

    )

    {

  • 8/8/2019 Database Mobitex

    22/184

    22 Programming tutorial UI/Database interaction

    Developers Guide BlackBerry

    2. Set the show_all _contacts_flag appropriately.

    m_show_all_contacts_flag = show_all_contacts;

    3. Update the UI Engine and the display.

    update_num_entries();}

    UI/Database interaction

    To convert a selected item in the list to a database record handle, use thefollowing code:

    list_index = m_contact_list.GetSelectedIndex();

    db_handle = m_contact_list.get_handle( list_index );

    The contact list screen has menu items that allow the user to switchbetween the view of all contacts and email contacts.

    To switch between two different views

    1. If the user has selected the Show all contacts menu item, updatethe list accordingly.

    case CONTACT_LIST_MENU_SHOWALL:// Show all of the contacts

    m_contact_list.show_all();

    m_title.SetText( "All Contacts" );

    break;

    2. If the user has selected the Show Email contacts menu item,update the list accordingly.

    case CONTACT_LIST_MENU_SHOWEMAIL:

    // Show only the contacts with an email address

    m_contact_list.show_all( false );

    m_title.SetText( "Email Contacts" );

    break;

  • 8/8/2019 Database Mobitex

    23/184

    Programming tutorial Editing a contact 23

    Developers Guide BlackBerry

    Editing a contact

    When the user wishes to edit a contact, we need to set up the screen toshow the information that already exists for that contact.

    To display a contacts information

    1. Construct a Contact object to modify.

    Contact contact( GlobalContactDatabase );

    2. Reconstruct the Contact object so we can edit it.

    if( db_record_handle != DB_NULL_HANDLE ) {

    contact.reconstruct( db_record_handle );

    3. Populate the name fields on the screen.

    char * first_name_ptr, * last_name_ptr;

    contact.get_name( first_name_ptr, last_name_ptr );

    // Place the names in the name fields

    if( first_name_ptr ) {

    m_first_name_edit.Insert( first_name_ptr );

    }

    if( last_name_ptr ) {

    m_last_name_edit.Insert( last_name_ptr );

    }

    4. Enumerate the email fields, and place each one on the screen.

    DbFieldHandle email_field_handle =

    contact.get_first_email();

    while( email_field_handle !=DB_INVALID_FIELD_HANDLE ) {

    5. Construct a new contact field to hold the email address.

    ContactEdit* contact_edit_ptr =

    new ContactEdit( "Email:",

  • 8/8/2019 Database Mobitex

    24/184

    24 Programming tutorial Adding an email address

    Developers Guide BlackBerry

    Contact::FIELDTAG_EMAIL_ADDRESS,

    email_field_handle );

    6. Set the properties of the edit field so that it handles email addressesin an effective way.

    if( contact_edit_ptr ) {

    contact_edit_ptr->AddProperties(

    Edit::CR_TO_ROLL_DOWN | Edit::EMAIL_FIELD );

    7. Insert the field contents into the edit field.

    contact_edit_ptr->Insert(

    (char * const) contact.get_field_data_ptr(

    email_field_handle ) );

    }

    8. Find the next email field. If one exists, go to Step 5. If not, the screenis complete.

    email_field_handle =

    contact.get_next_email( email_field_handle );

    }

    }

    Adding an email addressTo add an email address to the contact, we will add a ContactEdit fieldto the screen with a field handle of DB_INVALID_FIELD_HANDLE, toindicate that this particular email address has not yet been saved. Whenwe save the contact, the email addresses on the screen will all be savedwith the contact.

    To add an email address

    1. Create a new field and add it to the screen.

    case CONTACT_EDIT_MENU_ADDEMAIL:

    {

    ContactEdit* new_email_ptr =

    new ContactEdit( "Email:",

    Contact::FIELDTAG_EMAIL_ADDRESS );

  • 8/8/2019 Database Mobitex

    25/184

    Programming tutorial Saving a contact 25

    Developers Guide BlackBerry

    2. Set the properties of the email field so that it handles emailaddresses in an effective way.

    if( new_email_ptr ) {

    new_email_ptr->AddProperties(

    Edit::CR_TO_ROLL_DOWN | Edit::EMAIL_FIELD );

    AddField( *new_email_ptr );

    3. Set the focus to the new field.

    SetFieldwithFocus( new_email_ptr );

    }

    break;

    }

    Saving a contact

    When the user decides to save the contact, we need to extract the contactinformation from the fields that are on the screen.

    To save a contact

    1. If the user selects the Save contact menu item, get the first and lastnames entered in the edit fields.

    case CONTACT_EDIT_MENU_SAVE:

    {

    const char * first_name_ptr =

    m_first_name_edit.GetBuffer();

    const char * last_name_ptr =

    m_last_name_edit.GetBuffer();

    2. If the user attempts to save a contact without entering a name, bringup a dialog box to notify the user, and dont save the record.

    if( *first_name_ptr == '\0' &&

    *last_name_ptr == '\0' ) {

  • 8/8/2019 Database Mobitex

    26/184

    26 Programming tutorial Saving a contact

    Developers Guide BlackBerry

    OKDialog ok_dialog(

    "The contact must have a name." );

    ok_dialog.Go( m_ui_engine );

    break;

    }

    3. Set the names for the contact.

    contact.set_name( first_name_ptr, last_name_ptr );

    4. Go through all of the fields on the screen, and add the emailaddresses that are stored in the email fields.

    Field* field_ptr = GetFirstField();

    while( field_ptr != NULL ) {

    5. If the field is either the first_name or last_name field, it doesn'tcontain an email address, so ignore it.

    if( field_ptr != &m_first_name_edit &&

    field_ptr != &m_last_name_edit ) {

    6. When you arrive at an email field, add the address.

    ContactEdit* contact_edit =

    (ContactEdit*) field_ptr;

    const char * email_address =

    contact_edit->GetBuffer();

    7. If the email_address field is not empty, add or update the address.

    if( email_address != NULL &&

    *email_address != '\0' ) {

    contact.add_email( email_address,

    contact_edit->get_field_handle() );

    }

    }

  • 8/8/2019 Database Mobitex

    27/184

    Programming tutorial Removing an Email field 27

    Developers Guide BlackBerry

    8. Get the next field on the screen. If one exists, go to Step 5. If not, theemail addresses have all been added to the record.

    field_ptr = GetNextField( field_ptr );

    }

    9. Save the record with all of the fields.

    contact.save();

    return;

    }

    Removing an Email field

    If the users cursor is positioned over an email field, and the menu needsto be displayed, we want to allow the user to remove the email field sowe show the Remove Email menu item.

    To display the Remove Email menu item

    1. Get the field where the cursor is currently positioned.

    Field* current_field_ptr = GetFieldwithFocus();

    2. If it is neither the first or the last name, it must be an email address,so enable the Remove Email menu item.

    if( current_field_ptr != &m_first_name_edit &&

    current_field_ptr != &m_last_name_edit ) {

    m_menu.ShowItem(

    CONTACT_EDIT_MENU_REMOVEEMAIL );

    }

    3. If it is the first or last name field, we dont want to show the menuitem.

    else {

    m_menu.HideItem(CONTACT_EDIT_MENU_REMOVEEMAIL);

    }

    4. Set the default menu item to Save.

    m_menu.SetSelectedIndex( CONTACT_EDIT_MENU_SAVE );

  • 8/8/2019 Database Mobitex

    28/184

    28 Programming tutorial Removing an Email field

    Developers Guide BlackBerry

    If the user selects the Remove Email menu item, we must to remove theemail address.

    If the ContactEdit field has a valid handle, the email address hasalready been saved with the record, so we need to remove it from the

    record and the LCD.

    If the field handle is invalid, the email address has not been saved, so weonly need to remove it from the LCD.

    To remove an email address from therecord / LCD

    1. If the address has been saved in the record, it will have a valid fieldhandle, and well want to remove it from the record.

    case CONTACT_EDIT_MENU_REMOVEEMAIL:

    {

    ContactEdit* contact_edit =

    (ContactEdit*) current_field_ptr;

    DbFieldHandle field_handle =

    contact_edit->get_field_handle();

    if( field_handle != DB_INVALID_FIELD_HANDLE ) {

    contact.remove_email( field_handle );

    }

    2. In either case, we need to remove the email address from the LCD.

    RemoveField( *contact_edit );

    break;

    }

  • 8/8/2019 Database Mobitex

    29/184

    Database API Removing an Email field 29

    Developers Guide BlackBerry

    3.Database APIThe Database API provides data storage solutions for developers. Thefollowing are the classes with which you need to be familiar.

    API classes Start on page

    FlashObject class 32

    DatabaseRecord class 45

    Database class 66

    DatabaseView class 87

    DatabaseListView class 95

    DatabaseSortedListView class 105

    DatabaseIndexView class 110

    DatabaseIndexSearch class 118

    PersistentStore class 136

    DataBuffer class 146

    BitField class 160

    Database This is a simple database that can store multipleFlashObjects (or DatabaseRecords) which store data in a formatspecified by the developer. The database is responsible for saving data toflash, and for updating a list of database views attached to it. A Databasemay be automatically backed up and restored.

    FlashObject A FlashObject corresponds to a fixed-size structurethat can be used to store data in a format specified by the developer. Itcan be thought of as a C structure that can be stored in flash as well as inRAM. A FlashObject is the most efficient way to store data in adatabase, but as it does not allow for fields to be resized, the size must be

    fixed at compile time. Each FlashObject must have an associated

  • 8/8/2019 Database Mobitex

    30/184

    30 Database API Removing an Email field

    Developers Guide BlackBerry

    structure that is inherited from FlashObjectData. This structure iswhere the actual data is stored. The FlashObject knows how to accessits data structure, and also looks after loading it into RAM from flashand saving it to flash from RAM as necessary.

    DatabaseRecord -- A DatabaseRecord is another object that can beused to store data. Unlike a FlashObject, a DatabaseRecords fieldsare dynamically sized. As such, it is best used for data with length thatwill vary at run time, like character strings. Fields may also be added toand removed from a DatabaseRecord at run time. EachDatabaseRecord object may hold up to 254 fields at any time, and afield type can be associated with each field.

    DatabaseView Databases may have up to 16 views attached to them.Each view is updated every time a record is added, updated or deleted.

    The following lists the kinds of views provided: DatabaseListView -- This view stores an array of record

    handles. For example, the message screen uses a List Viewto hold the handles of the message.

    DatabaseSortedListView This view stores a sortedarray of record handles. For example, the Address Book usesa sorted list view to hold record handles of the addresses.

    DatabaseIndexView Like the index at the back of atextbook, this view can be used to provide fast lookup of a

    database record handles that match certain keywords. Foreach record, the application can insert many keywords intothe index. To search the index, a DatabaseIndexSearch isused to perform and hold the results of the search.

    PersistentStore -- A Persistent Store can be used to store a small C-style data structure in flash. Example uses include storing user optionsettings. PersistentStore data may be automatically backed up andrestored.

    DataBuffer -- A DataBuffer can be used to hold an arbitrary amount ofdata. It may be thought of as a simple stream object.

    Bitfield -- A Bitfield acts like an array of bits. Bit-oriented operations(set, clean, etc) can be performed on individual array entries, or on thearray as a whole.

  • 8/8/2019 Database Mobitex

    31/184

    Database API What is Flash memory? 31

    Developers Guide BlackBerry

    DbrecordBitField This class is derived form the Bitfield class andprovides one bit for each possible record handle.

    What is Flash memory?

    Flash memory is non-volatile memory that can retain its contentswithout power. On the device, code and data are stored in flash.

    Reading from flash is just like reading from RAM. However, writing toflash is relatively slow and requires using special OS commands.

    The Database API members are optimized to make the most efficient useof RAM and flash memory. Ideally, you need not be concerned with howthe data is stored.

    Database class hierarchy

    The following class hierarchy describes how the Database,FlashObjects, and DatabaseViews classes fit together.

    Flash Object

    Database

    Record

    User Flash

    Object Data

    User Flash

    Object

    Flash Object

    Data

    1 1

    User

    Database

    Record

    1 1

    Database 1 Database

    View

    1

    Database List

    ViewDatabase

    Index View

    Database

    Index

    Search

    1

    Database

    Sorted List

    View

    User Database View

    Database API class hierarchy

  • 8/8/2019 Database Mobitex

    32/184

    32 Database API FlashObject class

    Developers Guide BlackBerry

    FlashObject class

    A FlashObject corresponds to a record in a database. The data

    associated with a FlashObject is held in a FLASHOBJECTDATAstructure.

    There is a one to one correspondence between the FlashObject classhierarchy and the FlashObjectData class hierarchy.

    The following is an alphabetical list of FlashObject class members.

    _FlashObject::~FlashObject .......................................................35_FlashObject::clear_db_record_handle....................................33_FlashObject::clear_dirty_flag ..................................................34

    _FlashObject::delete_object .......................................................34_FlashObject::FlashObject..........................................................34_FlashObject::get_data_length..................................................36_FlashObject::get_data_ptr........................................................36_FlashObject::get_data_version................................................37_FlashObject::get_db_record_handle.......................................37_FlashObject::get_db_record_id ...............................................38_FlashObject::get_dirty_flag .....................................................38_FlashObject::get_summary_info.............................................43_FlashObject::load ......................................................................38

    _FlashObject::moved_in_flash..................................................39_FlashObject::read ......................................................................43_FlashObject::reconstruct ..........................................................39_FlashObject::reinitialize ...........................................................40_FlashObject::save ......................................................................40_FlashObject::set_data_version.................................................40_FlashObject::set_db_record_id................................................41_FlashObject::set_summary_info .............................................44_FlashObject::write.....................................................................44_FlashObject::zero_data.............................................................42

    _struct FlashObjectData.............................................................33

  • 8/8/2019 Database Mobitex

    33/184

    Database API FlashObject class 33

    Developers Guide BlackBerry

    struct FlashObjectData

    The FlashObjectData structure contains all member dataassociated with the object.

    struct FlashObjectData

    {

    byte dirty_flag : 1;

    byte reserved_flags : 7;

    byte data_version

    DbRecordId db_record_id;

    void

    initialize (void)

    {

    dirty_flag = true;reserved_flags = 0

    db_record_id( DB_NULL_RECORD_ID )

    data_version = 0

    }

    };

    You should inherit a class from FlashObjectData that containsmembers for the data you would like to store.

    FlashObject::clear_db_record_handle

    Used to clear the database record handle associated with theFlashObject

    virtual bool clear_db_record_handle()

    Return value

    TRUE if successful and FALSE otherwise

  • 8/8/2019 Database Mobitex

    34/184

    34 Database API FlashObject class

    Developers Guide BlackBerry

    FlashObject::clear_dirty_flag

    Clears the dirty flag, which is set when changes are made to theFlashObjectData object

    void clear_dirty_flag()

    Return value

    No return value

    FlashObject::delete_object

    Removes the data associated with this FlashObject from Flashmemory

    virtual void delete_object()

    Return value

    No return value

    FlashObject::FlashObject

    This member is a constructor.

    FlashObject (Database & init_database,

    DbRecordHandle init_db_record_handle =

    DB_NULL_HANDLE,

    FlashObjectData * init_ram_data_ptr = NULL)

    Parameters

    &init_database

    A reference to the database where the FlashObject will be stored

    init_db_record_handle

    This parameter is a handle to the record associated with an existingFlashObject, or DB_NULL_HANDLE, if a new, blank one is to becreated.

    *init_ram_data_ptr

    A pointer to a FLASHOBJECTDATA structure that can be used when theobjects data needs to be loaded into memory

  • 8/8/2019 Database Mobitex

    35/184

    Database API FlashObject class 35

    Developers Guide BlackBerry

    Return value

    No return value

    Remarks

    There are three ways to use this constructor:

    1. To construct a new, blank FlashObject

    Pass in the database where the object should be stored,DB_NULL_HANDLE for the record handle, and a pointer to aFLASHOBJECTDATA structure stored in RAM that the object will usewhen data is loaded.

    2. To construct a read-only FlashObject

    Pass in the database where the object should be stored, the record handleof the object to be read, and NULL for the RAM pointer. The resultingobject can be read very quickly and with no RAM overhead, but its datacannot be modified. It would be useful during a sorting algorithm, forexample, where objects need to be created, but only so that data can becompared, not modified.

    3. To construct a FlashObject that can be read and written

    Pass on the database where the object should be stored, the record

    handle of the object (if it exists already) and a pointer to aFLASHOBJECTDATA structure stored in RAM that the object will usewhen data is loaded.

    FlashObject::~FlashObject

    This member is a destructor.

    virtual ~FlashObject()

    Return Value

    No return value

  • 8/8/2019 Database Mobitex

    36/184

    36 Database API FlashObject class

    Developers Guide BlackBerry

    FlashObject::get_data_length

    Provides the length of the data object associated with theFlashObject

    virtual int get_data_length()const

    Return value

    An integer denoting the number of bytes stored in the data object

    Remarks

    You should override this function so that it returns the size of thestructure derived from FlashObjectData that is associated with theobject.

    FlashObject::get_data_ptr

    Provides a pointer to the data object associated with theFlashObject.

    FlashObjectData * get_data_ptr() const

    Return value

    A pointer to the data associated with the current FlashObject

    Remarks

    It is recommended that you add a function to your derived class calledget_data_ptr () that casts the return value ofFlashObject::get_data_ptr () to a pointer to the class derivedfrom FlashObjectData associated with this object.

    For example, if you have derived a structure MYDATA fromFlashObjectData, and a class MyObject from FlashObject that storesa MYDATA Structure, you could define the function:

    MyData*

    MyObject::

    get_data_ptr()

    {

    return (MyData*) FlashObject::get_data_ptr())

    };

  • 8/8/2019 Database Mobitex

    37/184

    Database API FlashObject class 37

    Developers Guide BlackBerry

    This will allow you to access the members of the structure moreconveniently, as you wont have to manually cast the return value ofFlashObject::get_data_ptr() each time you need to access amember of the structure.

    FlashObject::get_data_version

    Provides the version number of the data stored in theFlashObject

    byte get_data_version() const

    Return value

    The version number of the data stored in the FlashObject

    Remarks

    Anytime the data format changes significantly enough that old recordscannot be used by new code, the version number of the data should bechanged, to ensure that the data in the old format is not misinterpretedwhen it is loaded. If the version number of a record does not match theversion number specified in its Database's constructor, the virtualfunction Database::incompatible_record_version() will becalled, and the application will have a chance to resolve the versionconflict.

    FlashObject::get_db_record_handle

    Provides the unique record handle associated with thisFlashObject

    DbRecordHandle get_db_record_handle()

    Return value

    The database record handle associated with the FlashObject

    Remarks

    If the FlashObject has not yet been saved to flash, this function willreturn DB_NULL_HANDLE.

  • 8/8/2019 Database Mobitex

    38/184

    38 Database API FlashObject class

    Developers Guide BlackBerry

    FlashObject::get_db_record_id

    Provides the unique record identifier

    DbRecordId get_db_record_id() const

    Return valueThe database record ID associated with the FlashObject

    Remarks

    Each record has a unique record ID associated with it. The record ID isunique within the database only, whereas the record handle is uniqueacross all databases on the device.

    The database will assign each record a unique identifier when it is saved

    for the first time. An application may modify the unique ID to any value;no check is performed to verify that the new value actually is uniquewithin the database.

    FlashObject::get_dirty_flag

    Indicates whether the data has changed

    bool get_dirty_flag()

    Return valueTRUE if the FlashObjectData has been changed since the last call toclear_dirty_flag() and FALSE otherwise

    FlashObject::load

    Copies the data associated with this FlashObject into RAM fromflash, and changes the data pointer to point at the RAM copy

    virtual bool load()

    Return value

    TRUE if the FlashObjectData could be loaded into RAM and FALSE ifthe object has no RAM pointer associated with it (i.e. it was constructedas a read-only object)

  • 8/8/2019 Database Mobitex

    39/184

    Database API FlashObject class 39

    Developers Guide BlackBerry

    Remarks

    The FlashObjectData must be loaded into RAM before it can bemodified. Data loaded into RAM and not saved to flash will not beretained through a device reset. To retain the data, it must be saved.

    FlashObject::moved_in_flash

    Indicates when the data associated with this FlashObject hasbeen moved by the flash file system

    virtual bool moved_in_flash()const

    Return value

    TRUE if the FlashObjectData has moved in flash and FALSE otherwise

    Remarks

    An application may use pointers to point into flash to read data in theFlashObjectData. However, if FlashObject::moved_in_flashreturns TRUE, its an indication that these pointers are now invalid. It isrecommended that the application reconstruct the FlashObject andretrieve the updated pointers before any other operation.

    FlashObject::reconstruct

    Allows a FlashObject to be reconstructed with a newDbRecordHandle, without destroying the object

    virtual bool reconstruct (DbRecordHandle

    init_db_record_handle)

    Parameters

    init_db_record_handle

    This parameter is a handle to the database record associated with thisflash object. If DB_NULL_HANDLE, this function reconstructs a blankobject.

    Return value

    TRUE if the operation succeeded and FALSE otherwise

  • 8/8/2019 Database Mobitex

    40/184

    40 Database API FlashObject class

    Developers Guide BlackBerry

    FlashObject::reinitialize

    Reloads the FlashObject into RAM, and initializes theassociated FlashObjectData object.

    virtual bool reinitialize ()

    Return value

    TRUE if the operation succeeded and FALSE if the object has no RAMpointer associated with it (i.e. it was constructed as a read only object)

    FlashObject::save

    Copies the data associated with this FlashObject from RAM to

    flash, and changes the data pointer to point at the flash copyvirtual DbRecordHandle save()

    Return value

    TRUE if the FlashObjectData could be saved to flash

    Remarks

    Data loaded into RAM but not saved to flash will not be retainedthrough a device reset. To retain the data, it must be saved. After the

    data has been saved to flash it cannot be modified without loading theobject again.

    FlashObject::set_data_version

    Allows an application to specify the version number of the datastored in the FlashObject

    bool set_data_version( byte new_version )

    Parameters

    new_version

    The version number that should be associated with the data in theFlashObject

  • 8/8/2019 Database Mobitex

    41/184

    Database API FlashObject class 41

    Developers Guide BlackBerry

    Return value

    This function has a return value of TRUE if the version number could bechanged and FALSE otherwise. A failure usually indicates that the recordcould not be loaded into RAM so that the version number could bechanged.

    Remarks

    Anytime the data format changes significantly enough that old recordscannot be used by new code, the version number of the data should bechanged, to ensure that the data in the old format is not misinterpretedwhen it is loaded. If the version number of a record does not match theversion number specified in its Database's constructor, the virtualfunction Database::incompatible_record_version() will becalled, and the application will have a chance to resolve the version

    conflict.

    FlashObject::set_db_record_id

    Used internally to set the unique record identifier

    void set_db_record_id (DbRecordId new_db_record_id)

    Parameters

    new_db_record_idThe new value of the unique record ID

    Return value

    No return value

    Remarks

    The Database API library uses FlashObject::set_db_record_idinternally.

    The database will assign each record a unique identifier when it is savedfor the first time. An application may modify the unique ID to any value;no check is performed to verify that the new value actually is uniquewithin the database.

    This function could be used to set the record identifier of the record to aparticular value. For example, to map records from an external database

  • 8/8/2019 Database Mobitex

    42/184

    42 Database API FlashObject class

    Developers Guide BlackBerry

    to this one.

    FlashObject::zero_data

    Zeros the data in the FlashObjectData and can be used to wipesensitive information from the system

    void zero_data()

    Return value

    No return value

  • 8/8/2019 Database Mobitex

    43/184

    Database API FlashObject class 43

    Developers Guide BlackBerry

    FlashObject members for Backup/Restore

    Note The FlashObject class has member functions that are specificallyfor backup and restore operations. They are presented here forinformation purposes only.

    FlashObject::get_summary_info

    Reserved for use by backup and restore operations and iscurrently not used

    virtual unsigned int get_summary_info()

    Return value

    An unsigned int representing summary information about theFlashObjectData

    Remarks

    The summary information associated with the FlashObject is for useby backup and restore operations. You should overloadget_summary_info and set_summary_info if your applicationrequires a fast synchronization with the device.

    These functions can also be used to provide a quick summary of the

    database records.

    FlashObject::read

    Copies formatted data from the DataBuffer into the data areaassociated with the FlashObject

    virtual bool read (DataBuffer & data_buffer)

    Parameters&data_buffer

    A reference to a stream of data

    Return value

    TRUE if FlashObjectData could be read from the DataBuffer andFALSE if the data in the buffer was not properly formatted

  • 8/8/2019 Database Mobitex

    44/184

    44 Database API FlashObject class

    Developers Guide BlackBerry

    FlashObject::set_summary_info

    Sets the summary information associated with the Flash Object

    virtual bool set_summary_info byte data_version

    unsigned int summary_info)

    Parameters

    data_version

    The version number that should be associated with the data stored in therecord

    Return value

    TRUE if the summary information could be set and FALSE otherwise

    RemarksThe summary information associated with the FlashObject is for useby backup and restore operations. For example, you may wish tooverload set_summary_info and get_summary_info if yourapplication requires a fast synchronization with the device.

    These functions can also be used to provide a quick summary of thedatabase records.

    FlashObject::writePlaces a formatted copy of the data into the DataBuffer.

    virtual bool write (DataBuffer & data_buffer)

    Parameters

    data_buffer

    A pointer to a data stream where the objects data should be placed

    Return valueTRUE if the data of the object could be placed in the DataBuffer andFALSE if not enough memory could be allocated in the DataBuffer tohold the object data

  • 8/8/2019 Database Mobitex

    45/184

    Database API DatabaseRecord class 45

    Developers Guide BlackBerry

    DatabaseRecord class

    DatabaseRecord objects are used to hold general-purpose data in a

    database. A DatabaseRecord is derived from FlashObject. A recordconsists of fields. Each field has an associated handle (DbFieldHandle) ,tag (DbFieldTag), data length, and data.

    Each field within a database record has a unique field handle. The fieldhandle is a single byte, allowing up to 254 separate fields per record (0and DB_INVALID_FIELD_HANDLE are reserved for internal use).

    The field tag is a single byte that may be used by the application todifferentiate the type of data in each field. Multiple fields of the same

    data type within the same database record will have the same field tag.

    Constants and Definitions

    The following constants are used by DatabaseRecord.

    typedef byte DbFieldHandle;

    typedef byte DbFieldTag;

    const DbFieldHandle DB_INVALID_FIELD_HANDLE = ((DbFieldHandle) -1 );

    const DbFieldTag DB_INVALID_FIELD_TAG = (

    (DbFieldTag) -1 );

    const unsigned short DB_INVALID_DATA_LENGTH = (

    (unsigned short) -1 );

    const int DB_TEXT = -INT_MAX;

  • 8/8/2019 Database Mobitex

    46/184

    46 Database API DatabaseRecord class

    Developers Guide BlackBerry

    The following is an alphabetical list of DatabaseRecord class members.

    _DatabaseRecord::~DatabaseRecord.......................................50_DatabaseRecord::add_field .....................................................47_DatabaseRecord::append_to_field .........................................49

    _DatabaseRecord::DatabaseRecord..........................................50_DatabaseRecord::delete_field..................................................51_DatabaseRecord::delete_fields................................................51_DatabaseRecord::error .............................................................52_DatabaseRecord::get_data_length..........................................52_DatabaseRecord::get_field_data_length................................53_DatabaseRecord::get_field_data_ptr......................................53_DatabaseRecord::get_field_tag ...............................................54_DatabaseRecord::get_first_field_handle................................54_DatabaseRecord::get_next_field_handle ...............................55

    _DatabaseRecord::get_num_fields...........................................57_DatabaseRecord::is_field_writeable.......................................65_DatabaseRecord::load ..............................................................57_DatabaseRecord::prepend_to_field........................................57_DatabaseRecord::read ..............................................................64_DatabaseRecord::reconstruct ..................................................58_DatabaseRecord::reinitialize ...................................................58_DatabaseRecord::replace_field_data......................................59_DatabaseRecord::save ..............................................................60_DatabaseRecord::set_field_tag................................................60_DatabaseRecord::update_field................................................61_DatabaseRecord::write.............................................................64

  • 8/8/2019 Database Mobitex

    47/184

    Database API DatabaseRecord class 47

    Developers Guide BlackBerry

    DatabaseRecord::add_field

    Provides the ability to add new fields to a database record

    Form 1: DbFieldHandle add_field (DbFieldTag field_tag,

    int data_length = 0)

    Form 2: DbFieldHandle add_field (DbFieldTag field_tag,

    const void * data1_ptr,

    const void * data2_ptr = NULL,

    const void * data3_ptr = NULL,

    int data1_length = DB_TEXT,

    int data2_length = DB_TEXT,

    int data3_length = DB_TEXT)

    Form 3: DbFieldHandle add_field (DbFieldTag field_tag,

    const void * data1_ptr,

    int data1_length,const void * data2_ptr = NULL,

    int data2_length = DB_TEXT,

    const void * data3_ptr = NULL,

    int data3_length = DB_TEXT)

    Parameters

    field_tag

    The value to be set in the field tag of the new field

    data_length

    The length of the data to be added

    *data1_ptr

    A pointer to the first block of data to be added

    *data2_ptr

    A pointer to the second block of data to be added

    *data3_ptr

    A pointer to the third block of data to be added

    data1_length

    The length of the first block of data to be added

    data2_length

    The length of the second block of data to be added

  • 8/8/2019 Database Mobitex

    48/184

    48 Database API DatabaseRecord class

    Developers Guide BlackBerry

    data3_length

    The length of the third block of data to be added

    Return Value

    This function has a return value of the field handle of the new field. On

    failure, this function returns DB_INVALID_FIELD_HANDLE.

    Remarks

    The data for the field may be specified by up to three blocks of data. Thisis for convenience only, and the specified blocks of data will beconcatenated and stored together in a single field.

    The blocks of data can contain different types of data:

    Binary data

    To add binary data, pass in a pointer to the data, and the length of thedata.

    String data

    1. If the string data is already NULL-terminated, pass in a pointer to thedata, and the value DB_TEXT for the length. The data will be copied,along with the terminating NULL.

    2. If the string is not already NULL-terminated, pass in a pointer to thedata, and the length of the string to be added, multiplied by 1. Thedata will be copied, and a NULL-terminator will be added to thecopied string.

    3. If the data pointer is NULL and the length is non-zero, space will beallocated in the record to hold the specified length of data, but nodata will be copied into the allocated space. If the length is negative,a NULL will be appended to the allocated space. If the length is 0, orDB_TEXT, no space will be allocated.

    Note If the data pointer is not NULL and the length is 0, a single NULLcharacter will be copied.

  • 8/8/2019 Database Mobitex

    49/184

    Database API DatabaseRecord class 49

    Developers Guide BlackBerry

    DatabaseRecord::append_to_field

    Provides the ability to append data to an existing field in adatabase record

    bool append_to_field (DbFieldHandle field_handle,

    const void * data_ptr,

    int data_length = DB_TEXT,

    void * * buffer_pptr = NULL)

    Parameters

    field_handle

    The handle of the field to be updated in the database record

    data_ptr

    A pointer to the data to be appended to the field

    data_length

    The length of the data to be appended to the field

    buffer_pptr

    A pointer to a pointer that will be set to the start of the data appended tothe record after the operation is complete

    Return value

    TRUE if the field data could be appended and FALSE otherwise

    Remarks

    The length of the data to be appended is specified the same way as inadd_field. If the specified length is negative, or DB_TEXT, anyterminating NULL already in the buffer will be removed before the newtext is appended.

  • 8/8/2019 Database Mobitex

    50/184

    50 Database API DatabaseRecord class

    Developers Guide BlackBerry

    DatabaseRecord::DatabaseRecord

    Constructs a DatabaseRecord object

    Form 1: DatabaseRecord (Database & database)

    Form 2: DatabaseRecord (Database & database,DbRecordHandle db_record_handle)

    Parameters

    &database

    A reference to the database to which this record belongs

    db_record_handle

    This parameter specifies the record in the database. If the parameter isDB_NULL_HANDLE, a new blank record is constructed.

    Return value

    No return value

    Remarks:

    Form 1 creates a new record. Form 2 reconstructs a reference to anexisting record with the given DB_RECORD_HANDLE.

    Records are not committed to the database until save() is called.

    Also, applications may construct multiple DatabaseRecords using thesame db_record_handle. However, only the last one saved will bekept.

    DatabaseRecord::~DatabaseRecord

    Destroys a DatabaseRecord object

    ~DatabaseRecord()

    Return value

    No return value

  • 8/8/2019 Database Mobitex

    51/184

    Database API DatabaseRecord class 51

    Developers Guide BlackBerry

    DatabaseRecord::delete_field

    Provides the ability to delete a field within a record, asreferenced by the given field handle

    bool delete_field (DbFieldHandle field_handle)

    Parameters

    field_handle

    The handle of the field to be deleted from the database record

    Return value

    TRUE if the field could be deleted and FALSE otherwise

    Remarks

    If no field has the specified tag, this member does nothing

    DatabaseRecord::delete_fields

    Provides the ability to delete all fields in the record that matchthe given field_tag

    bool delete_fields (DbFieldTag field_tag)

    Parameters

    field_tag

    The value of the tag of the fields to be deleted from this database record

    Return value

    No return value

    Remarks

    If no field has the specified tag, this member does nothing.

  • 8/8/2019 Database Mobitex

    52/184

    52 Database API DatabaseRecord class

    Developers Guide BlackBerry

    DatabaseRecord::error

    DatabaseRecord::error indicates whether an error occurredduring construction of a DatabaseRecord

    bool error() const

    Return value

    TRUE if an error occurred and FALSE otherwise

    Remarks

    Usually, an error indicates an out of memory condition. Since aconstructor cannot return an error code, this extra function is required toindicate failure. To be safe, after the record is constructed, the applicationshould verify that there was no error during construction.

    DatabaseRecord::get_data_length

    Provides the length of the entire DatabaseRecord object,including all field data lengths

    virtual int get_data_length()

    Return value

    The length of the data within the database record

    Remarks

    The length includes the length of all data fields (including NULL-terminators) plus the overhead for record and field headers.

  • 8/8/2019 Database Mobitex

    53/184

    Database API DatabaseRecord class 53

    Developers Guide BlackBerry

    DatabaseRecord::get_field_data_length

    Provides the length of the given field within the DatabaseRecordobject

    int get_field_data_length (DbFieldHandle field_handle)

    Parameters

    field_handle

    The value of the field handle in the database record

    Return value

    The length, in bytes, of the data associated with the field referenced bythe field_handle.

    Remarks

    The length includes any NULL-terminators in the field.

    DatabaseRecord::get_field_data_ptr

    Provides a pointer to the data for the given field within theDatabaseRecord object

    void * get_field_data_ptr (DbFieldHandle field_handle)

    Parameters

    field_handle

    The value of the field handle in the database record

    Return value

    This function has a return value of a pointer to the data portion of a field.May be NULL if the field_handle is not valid.

    Remarks

    Take care when writing through this pointer, since it may be pointinginto flash memory. The record must be loaded into RAM first (seeload()), before it is modified.

  • 8/8/2019 Database Mobitex

    54/184

    54 Database API DatabaseRecord class

    Developers Guide BlackBerry

    DatabaseRecord::get_field_tag

    Provides the tag (data type) of the given field

    DbFieldTag get_field_tag (DbFieldHandle field_handle)

    Parametersfield_handle

    The value of the field handle in the database record

    Return value

    The tag associated with the field handle, or DB_INVALID_FIELD_TAG ifthe field handle is invalid

    DatabaseRecord::get_first_field_handle

    Provides a handle to the first field in the DatabaseRecordobject, or the first field of the given data type

    Form 1: DbFieldHandle get_first_field_handle()

    Form 2: DbFieldHandle get_first_field_handle (DbFieldTag

    field_tag)

    Parameters

    field_tag

    The value of the field tag to be searched for

    Return value

    This function has a return value of the field handle of the first field in therecord, or in the case of a tag, the first field that matches the given fieldtag. If the record has no fields, DB_INVALID_FIELD_HANDLE is returned.

    Examples:

    Form 1:

    DatabaseRecord address( AddressBook,

    address_record_handle );

    DbFieldHandle email_field_handle =

    address.get_first_field_handle();

    While ( email_field_handle !=

    DB_INVALID_FIELD_HANDLE ) {

  • 8/8/2019 Database Mobitex

    55/184

    Database API DatabaseRecord class 55

    Developers Guide BlackBerry

    // do some field processing

    // get next field

    email_field_handle =

    address.get_next_field_handle(

    email_field_handle );

    }

    Form 2:

    DatabaseRecord address( AddressBook,

    address_record_handle );

    DbFieldHandle email_field_handle =

    address.get_first_field_handle( EMAIL );

    While ( email_field_handle !=

    DB_INVALID_FIELD_HANDLE ) {

    // do some Email field processing

    // get next Email field

    email_field_handle =

    address.get_next_field_handle(

    email_field_handle, EMAIL );

    }

    DatabaseRecord::get_next_field_handle

    Provides a handle to the next field, or the next field of the givendata type

    Form 1: DbFieldHandle get_next_field_handle

    (DbFieldHandle field_handle)

    Form 2: DbFieldHandle get_next_field_handle

    (DbFieldHandle field_handle,

    DbFieldTag field_tag)

    Parameters

    field_handleThe value of the field handle in the database record after which to startsearching

    field_tag

    The value of the field tag to be searched for

  • 8/8/2019 Database Mobitex

    56/184

    56 Database API DatabaseRecord class

    Developers Guide BlackBerry

    Return value

    This function has a return value of the field handle in the record after thegiven field handle. If a field tag is specified, the member returns the firstfield that matches the given field tag. If the record has no more fields, orno more field that match the given field tag,

    DB_INVALID_FIELD_HANDLE is returned.

    Examples:

    Form 1

    DatabaseRecord address( AddressBook,

    address_record_handle );

    DbFieldHandle email_field_handle =

    address.get_first_field_handle();

    While ( email_field_handle != DB_INVALID_FIELD_HANDLE ) {

    // do some field processing

    // get next field

    email_field_handle =

    address.get_next_field_handle( email_field_handle );

    }

    Form 2

    DatabaseRecord address( AddressBook,

    address_record_handle );

    DbFieldHandle email_field_handle =address.get_first_field_handle( EMAIL );

    While ( email_field_handle != DB_INVALID_FIELD_HANDLE ) {

    // do some Email field processing

    // get next Email field

    email_field_handle =

    address.get_next_field_handle( email_field_handle, EMAIL );

    }

  • 8/8/2019 Database Mobitex

    57/184

    Database API DatabaseRecord class 57

    Developers Guide BlackBerry

    DatabaseRecord::get_num_fields

    Provides the number of data fields in the DatabaseRecord

    int get_num_fields() const

    Return valueThe number of fields in the record

    DatabaseRecord::load

    Attempts to load the record data into RAM

    virtual bool load()

    Return valueThis function has a return value of TRUE if the record data could beloaded into RAM, otherwise returns FALSE. A failure normally indicatesthat there was insufficient RAM available to load the entire record.

    DatabaseRecord::prepend_to_field

    Provides the ability to prepend data to an existing field in a

    database recordbool prepend_to_field (DbFieldHandle field_handle,

    const void * data_ptr,

    int data_length = DB_TEXT)

    Parameters

    field_handle

    The handle of the field to be updated in the database record

    data_ptr

    A pointer to the data to be prepended to the field

    data_length

    The length of the data to be prepended to the field

  • 8/8/2019 Database Mobitex

    58/184

    58 Database API DatabaseRecord class

    Developers Guide BlackBerry

    Return value

    TRUE if the field data could be prepended and FALSE otherwise

    Remarks

    The length of the data to be prepended is specified the same way as inadd_field. If the specified length includes a NULL-terminator, the NULLwill be added to the field as well. To prepend a NULL-terminated stringto a field without including the NULL, pass in the strlen() of the stringfor data_length.

    DatabaseRecord::reconstruct

    Allows an application to reuse an existing DatabaseRecord

    object, but change the record to which it refers

    virtual bool reconstruct (

    DbRecordHandle init_db_record_handle)

    Parameters

    init_db_record_handle

    The handle of the record to be used

    Return value

    No return value

    Remarks

    If init_db_record_handle is DB_NULL_HANDLE, reinitialize() iscalled, and a new, blank record is created.

    DatabaseRecord::reinitialize

    Reinitializes the DatabaseRecord object to a new, blank record

    virtual bool reinitialize()

    Return value

    Returns TRUE if the operation succeeded, otherwise returns FALSE.

  • 8/8/2019 Database Mobitex

    59/184

    Database API DatabaseRecord class 59

    Developers Guide BlackBerry

    DatabaseRecord::replace_field_data

    Provides the ability to replace a portion of the data in an existingfield in a database record

    bool replace_field_data (DbFieldHandle field_handle,

    int offset,

    const void * data_ptr,

    int data_length = DB_TEXT,

    void ** buffer_pptr=NULL)

    Parameters

    field_handle

    The handle of the field to be updated in the database record

    offset

    The 0-based offset from the beginning of the field where the new datawill replace the existing data, if any

    *data_ptr

    A pointer to the data that will be written over the existing data

    data_length

    The length of the data that will be written over the existing data

    buffer_pptr

    A pointer to a pointer that will be set to the start of the replaced dataafter the operation is complete

    Return value

    TRUE if the field data could be replaced and FALSE otherwise

    Remarks

    The length of the data to be replaced is specified in the same way as inadd_field

    . Any data in the record at the specified offset for thespecified length will be overwritten with the new data.

  • 8/8/2019 Database Mobitex

    60/184

    60 Database API DatabaseRecord class

    Developers Guide BlackBerry

    DatabaseRecord::save

    Commits the data record to Flash memory. All views connectedto the database are updated

    virtual DbRecordHandle save()

    Return value

    Returns the handle of the saved record, or DB_NULL_HANDLE if therecord couldnt be saved.If a record cannot be saved it is usually becausethere was insufficient space in the file system for the entire record.

    DatabaseRecord::set_field_tag

    Used to change the tag of the field referenced by thefield_handle

    bool set_field_tag (DbFieldHandle field_handle,

    DbFieldTag field_tag)

    Parameters

    field_handle

    The value of the field handle in the database record

    field_tagThe new value of the field

    Return value

    TRUE if the field tag could be set and FALSE otherwise

  • 8/8/2019 Database Mobitex

    61/184

    Database API DatabaseRecord class 61

    Developers Guide BlackBerry

    DatabaseRecord::update_field

    Provides the ability to update an existing field in a databaserecord

    Form 1: DbFieldHandle update_field (

    DbFieldHandle field_handle,

    const void * data1_ptr,

    const void * data2_ptr = NULL,

    const void * data3_ptr = NULL,

    int data1_length = DB_TEXT,

    int data2_length = DB_TEXT,

    int data3_length = DB_TEXT)

    Form 2: DbFieldHandle update_field (

    DbFieldHandle field_handle,

    const void * data1_ptr,

    int data1_length,const void * data2_ptr = NULL,

    int data2_length = DB_TEXT,

    const void * data3_ptr = NULL,

    int data3_length = DB_TEXT)

    Form 3: DbFieldHandle update_field (

    DbFieldHandle field_handle,

    DbFieldTag field_tag,

    const void * data1_ptr,

    const void * data2_ptr = NULL,

    const void *data3_ptr = NULL,int data1_length = DB_TEXT,

    int data2_length = DB_TEXT,

    int data3_length = DB_TEXT)

    Form 4: DbFieldHandle update_field

    (DbFieldHandle field_handle,

    DbFieldTag field_tag,

    const void * data1_ptr,

    int data1_length,

    const void * data2_ptr = NULL,

    int data2_length = DB_TEXT,

    const void * data3_ptr = NULL,

    int data3_length = DB_TEXT)

    Parameters

    field_handle

    The handle of the field to be updated in the database record

  • 8/8/2019 Database Mobitex

    62/184

    62 Database API DatabaseRecord class

    Developers Guide BlackBerry

    field_tag

    The value to be set in the field tag of the database record

    data1_ptr

    A pointer to the first block of data to be added

    data2_ptr

    A pointer to the second block of data to be added

    data3_ptr

    A pointer to the third block of data to be added

    data1_length

    The length of the first block of data to be added

    data2_length

    The length of the second block of data to be added

    data3_length

    The length of the third block of data to be added

    Return value

    This function has a return value of the field handle of the updated recordfield. On failure, this member returns DB_INVALID_FIELD_HANDLE.

    Remarks

    The data for the field may be specified by up to three blocks of data. Thisis for convenience only, and the specified blocks of data will beconcatenated and stored together in a single field.

    The blocks of data can contain different types of data:

    Binary data

    To add binary data, pass in a pointer to the data, and the length of thedata.

    String data

    1. If the string data is already NULL-terminated, pass in a pointer to thedata, and the value DB_TEXT for the length. The data will be copied,along with the terminating NULL.

  • 8/8/2019 Database Mobitex

    63/184

    Database API DatabaseRecord class 63

    Developers Guide BlackBerry

    2. If the string is not already NULL-terminated, pass in a pointer to thedata, and the length of the string to be added, multiplied by 1. Thedata will be copied, and a NULL-terminator will be added to thecopied string.

    3. If the data pointer is NULL and the length is non-zero, space will beallocated in the record to hold the specified length of data, but nodata will be copied into the allocated space. If the length is negative,a NULL will be appended to the allocated space. If the length is 0, orDB_TEXT, no space will be allocated.

    Note If the data pointer is not NULL and the length is 0, a single NULLcharacter will be copied.

  • 8/8/2019 Database Mobitex

    64/184

    64 Database API DatabaseRecord class

    Developers Guide BlackBerry

    DatabaseRecord members forBackup/Restore

    Note The DatabaseRecord class has member functions that are

    specifically for backup and restore operations. You do not need touse these functions to implement special backup/restore behaviour.They are listed here for your information.

    DatabaseRecord::read

    Copies formatted data from the DataBuffer into the data areaassociated with the DatabaseRecord

    virtual bool read (DataBuffer & data_buffer)

    Parameters

    &data_buffer

    A reference to a stream of data

    Return value

    TRUE if DatabaseRecord data could be read from the DataBuffer orFALSE if the data in the buffer was not properly formatted

    DatabaseRecord::write

    Places a formatted copy of the data into the DataBuffer

    virtual bool write (DataBuffer & data_buffer)

    Parameters

    data_buffer

    A pointer to a data stream where the objects data should be placed

    Return value

    TRUE if the data of the object could be placed in the DataBuffer orFALSE if not enough memory could be allocated in the DataBuffer tohold the object data

  • 8/8/2019 Database Mobitex

    65/184

    Database API DatabaseRecord class 65

    Developers Guide BlackBerry

    DatabaseRecord::is_field_writeable

    An application-supplied function that is called during backup

    virtual bool is_field_writeable (

    DbFieldHandle field_handle,

    FieldTag field_tag)

    Parameters

    field_handle

    The handle of the field to be tested

    field_tag

    The tag of the field to be tested

    Return valueTRUE if the field can be backed up and FALSE otherwise

    Remarks

    The application can indicate that certain fields should not be backed up.The default implementation of this function backs up all field because itreturns TRUE.

  • 8/8/2019 Database Mobitex

    66/184

    66 Database API Database class

    Developers Guide BlackBerry

    Database class

    The Database class is a simple database that can store records. Each

    record can contain a variable number of variable sized fields. Records arereferred to by DbRecordHandles. A Database may be automaticallybacked up and restored.

    The following is an alphabetical list of Database class members.

    _Database::~Database ................................................................69_Database::backup_restore_completed...................................77_Database::backup_restore_started .........................................77_Database::check_database .......................................................68_Database::clear_backup_restore_dirty_flag..........................78

    _Database::Database ..................................................................68_Database::delete_all_records...................................................69_Database::delete_record...........................................................70_Database::delete_stale_records...............................................70_Database::deregister_view ......................................................83_Database::find_record..............................................................72_Database::get_backup_restore_dirty_flag.............................78_Database::get_backup_restore_object_ptr.............................78_Database::get_database_name................................................72_Database::get_database_size...................................................72

    _Database::get_first_record.......................................................86_Database::get_next_database_ptr...........................................79_Database::get_next_db_record_id ..........................................73_Database::get_next_record ......................................................86_Database::get_nth_record........................................................73_Database::get_num_records....................................................73_Database::get_previous_database_ptr...................................80_Database::incompatible_record_version ...............................74_Database::is_backup_restore_in_progress ............................80_Database::is_deleting_stale_records ......................................75

    _Database::is_member_record..................................................75_Database::progress_notify.......................................................75_Database::register_view...........................................................83_Database::reload_view.............................................................84_Database::reserve_record_handle ..........................................76_Database::save_record .............................................................82_Database::save_views ..............................................................84

  • 8/8/2019 Database Mobitex

    67/184

    Database API Database class 67

    Developers Guide BlackBerry

    _Database::set_backup_restore_dirty_flag .............................81_Database::set_backup_restore_object_ptr .............................81_get_database_ptr ......................................................................79_get_first_database_ptr .............................................................79_get_num_databases..................................................................80

  • 8/8/2019 Database Mobitex

    68/184

    68 Database API Database class

    Developers Guide BlackBerry

    Database::check_database

    Verifies that each record in the database is of the correctversion

    virtual void check_database( )

    Returns:

    No return value

    Remarks

    This checks each record's version number to see if it matches the versionspecified in the constructor of the database. If it does not match, thevirtual function Database::incompatible_record_version() willbe called, and the application will have a chance to resolve the version

    conflict.

    Database::Database

    The constructor for the Database object

    Database (const char * init_name,

    DatabaseProgressNotify *

    init_progress_notify_ptr = NULL,

    byte init_current_data_version=0,

    int max_reserve_record_count=100,

    int default_record_length=100)

    Parameters

    init_name

    This parameter is a name for the database. Since this string may be usedby the Backup/Restore tool, it is recommended that the string shoulddescribe the database contents, for example Address Book.

    init_progress_notify_ptrA pointer to a DatabaseProgressNotify object that he database canuse during intensive operations to indicate to the user that backgroundprocessing is taking place.

    init_current_data_version

    This parameter is the version number of the data that the database

  • 8/8/2019 Database Mobitex

    69/184

    Database API Database class 69

    Developers Guide BlackBerry

    expects to store. If an application tries to load a record with a differentversion number. incompatible_record_version() will be called andthe database will be asked to resolve the conflict.

    default_record_length

    This parameter is an estimated average size of the records that will bestored by the database. Enough flash space will be reserved formax_reserve_record_count records, default_record_length byteslong on average.

    Return value

    No return value

    Database::~DatabaseThis is the Database object destructor.

    ~Database()

    Return value

    No return value

    Database::delete_all_recordsDeletes all records in the database

    virtual void delete_all_records()

    Return value

    No return value

  • 8/8/2019 Database Mobitex

    70/184

    70 Database API Database class

    Developers Guide BlackBerry

    Database::delete_record

    Deletes a specific record from the database

    virtual bool delete_record (

    DbRecordHandle db_record_handle)

    Parameters

    db_record_handle

    The handle of the record to be deleted

    Return value

    TRUE if the record was deleted successfully and FALSE. otherwise

    RemarksThe record is deleted if the handle can be deleted from all views attachedto the database.

    Database::delete_stale_records

    Called by the database library when the device is running lowon flash space

    virtual void delete_stale_records

    (unsigned int desired_block_size,

    unsigned int desired_free_space,

    unsigned int desired_handle_count)

    Parameters

    desired_block_size

    Indicates the minimum size of a contiguous block of flash that thedatabase library would like to have available

    desired_free_space

    Indicates the minimum amount of flash that the database library wouldlike to have available

    desired_handle_count

    Indicates the minimum number of unused handles that the databaselibrary would like to have available

  • 8/8/2019 Database Mobitex

    71/184

    Database API Database class 71

    Developers Guide BlackBerry

    Return value

    No return value

    Remarks

    This function will be called by the database library if the device isrunning low on flash space. If the database contains records that cansafely be deleted (for example, old messages that have not been saved) itshould delete them in order to free up flash space for other applications.The default implementation assumes that no records in the database canbe deleted, and so it does nothing.

    Example

    void

    MyDatabase::

    delete_stale_records( ){

    DbRecordHandle db_record_handle =

    get_first_record();

    while( ( db_record_handle != DB_NULL_HANDLE )

    && ( DbMaxNewRecSize( NORMAL ) & get_array()

    Return value

    Returns a reference to the handle array of the view. The handle array isan instance of a BigDynamicArray< DbRecordHandle > template class.

  • 8/8/2019 Database Mobitex

    105/184

    Databas