hoocy 发表于 2013-1-30 01:19:36

[官方Demo]BlackBerry SQL与 TreeField 官方实例

SQLiteDemo.java
 
/* * SQLiteDemo.java * * Copyright � 1998-2010 Research In Motion Ltd. ** Note: For the sake of simplicity, this sample application may not leverage * resource bundles and resource strings.However, it is STRONGLY recommended * that application developers make use of the localization features available * within the BlackBerry development platform to ensure a seamless application * experience across a variety of languages and geographies.For more information * on localizing your application, please refer to the BlackBerry Java Development * Environment Development Guide associated with this release. */package com.rim.samples.device.sqlitedemo;import java.io.*;import java.util.*;import javax.microedition.io .*;import javax.microedition.io.file.*;import net.rim.device.api.database.Database;import net.rim.device.api.database.DatabaseException;import net.rim.device.api.database.DatabaseFactory;import net.rim.device.api.database.DatabaseSecurityOptions;import net.rim.device.api.io.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;/** * This sample application demonstrates the use of a SQLite database and the * 'net.rim.device.api.database package'. A pre-configured database is included * with the project and will be copied to the default root location (provided an * SDCard is available) if a database does not already exist at that location. * The default root for SQLite databases is 'file:///SDCard/databases/*project-name*'. * Certain BlackBerry Smartphone devices are capable of creating databases in eMMC * memory.However, using eMMC memory to store large databases is not recommended.   * This sample is a business directory application which uses * the SQLite back end database for persistent storage of its data. The database * contains a DirectoryItems table and an associated table, Category. The * DirectoryItems table contains a foreign key constraint on its category_id * field which references the corresponding field in the Category table. * The applications's user interface consists of a tree field which displays * categories as nodes and directory items as child nodes. The application allows * for the displaying, editing, adding, saving and deleting of items. Categories * can also be added or deleted. Deleting a category will result in all * directory items belonging to the category being deleted as well. ** The database created by this application is encrypted and access is controlled * by a code signing key. You will need to use the BlackBerry Signing Authority * Admin Tool to create a public/private key pair with the name "XYZ" (See the * BlackBerry Signing Authority Tool Administrator Guide for more information). * Replace the XYZ public key contained in this project with the XYZ public key * created with the BlackBerry Signing Authority Admin Tool. Build the project * and then use the BlackBerry Signing Authority Tool to sign the resulting * cod file with the XYZ private key. */public final class SQLiteDemo extends UiApplication{    private static String DB_NAME = "SQLiteDemoDirectory";         /**   * Entry point for this application   * @param args Command line arguments (not used)   * @throws Exception   */    public static void main(String[] args) throws Exception    {      // Create a new instance of the application and make the currently      // running thread the application's event dispatch thread.      SQLiteDemo app = new SQLiteDemo();      app.enterEventDispatcher();    }         /**   * Creates a new SQLiteDemo object   * @throws Exception   */    public SQLiteDemo() throws Exception    {               // Determine if an SDCard is present         boolean sdCardPresent = false;      String root = null;      Enumeration e = FileSystemRegistry.listRoots();      while (e.hasMoreElements())      {            root = (String)e.nextElement();            if(root.equalsIgnoreCase("sdcard/"))            {                sdCardPresent = true;            }             }                  if(!sdCardPresent)      {            UiApplication.getUiApplication().invokeLater(new Runnable()            {                public void run()                {                  Dialog.alert("This application requires an SD card to be present. Exiting application...");                  System.exit(0);                            }             });                }                  else      {            String dbLocation = "/SDCard/databases/SQLite Demo/";                         // Create URI                        URI uri = URI.create(dbLocation + DB_NAME);                           // Open or create a plain text database.This will create the            // directory and file defined by the URI (if they do not already exist).            Database db = DatabaseFactory.openOrCreate(uri, new DatabaseSecurityOptions(false));                        // Close the database in case it is blank and we need to write to the file            db.close();                        // Open a connection to the database file                  FileConnection fileConnection = (FileConnection)Connector.open("file://" + dbLocation + DB_NAME);                            // If the file is blank, copy the pre-defined database from this            // module to the SDCard.            if(fileConnection.exists() && fileConnection.fileSize() == 0)            {                                    readAndWriteDatabaseFile(fileConnection);                     }                                 // Retrieve the code signing key for the XYZ key file            CodeSigningKey codeSigningKey = CodeSigningKey.get(CodeModuleManager.getModuleHandle( "SQLiteDemo" ), "XYZ");                        try            {                // Encrypt and protect the database.If the database is already                // encrypted, the method will exit gracefully.               DatabaseFactory.encrypt(uri, new DatabaseSecurityOptions(codeSigningKey));            }            catch(DatabaseException dbe)            {                errorDialog("Encryption failed - " + dbe.toString());                     }                        // Open the database                        db = DatabaseFactory.open(uri);                        // Create a new main screen and push it onto the display stack                  SQLiteDemoScreen screen = new SQLiteDemoScreen(new SQLManager(db));                  pushScreen(screen);                                  }    }               /**      * Copies the pre-defined database from this module to the      * location specified by the fileConnection argument.      * @param fileConnection File connection to the database location      */    public void readAndWriteDatabaseFile(FileConnection fileConnection) throws IOException    {                OutputStream outputStream = null;      InputStream inputStream = null;                                    // Open an input stream to the pre-defined encrypted database bundled      // within this module.      inputStream = getClass().getResourceAsStream("/" + DB_NAME);               // Open an output stream to the newly created file      outputStream = (OutputStream)fileConnection.openOutputStream();                                                       // Read data from the input stream and write the data to the      // output stream.                  byte[] data = new byte;      int length = 0;      while (-1 != (length = inputStream.read(data)))      {            outputStream.write(data, 0, length);                        }                     // Close the connections      if(fileConnection != null)      {            fileConnection.close();      }      if(outputStream != null)      {            outputStream.close();      }         if(inputStream != null)      {            inputStream.close();      }                }            /**   * Presents a dialog to the user with a given message   * @param message The text to display   */    public static void errorDialog(final String message)    {      UiApplication.getUiApplication().invokeLater(new Runnable()      {            public void run()            {                Dialog.alert(message);            }         });    }}  
 
ItemScreen.java
 
/* * ItemScreen.java * * Copyright � 1998-2010 Research In Motion Ltd. ** Note: For the sake of simplicity, this sample application may not leverage * resource bundles and resource strings.However, it is STRONGLY recommended * that application developers make use of the localization features available * within the BlackBerry development platform to ensure a seamless application * experience across a variety of languages and geographies.For more information * on localizing your application, please refer to the BlackBerry Java Development * Environment Development Guide associated with this release. */package com.rim.samples.device.sqlitedemo;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;/** * A MainScreen class used to display and edit directory item details */public final class ItemScreen extends MainScreen{    private DirectoryItem _item;    private EditField _nameField;    private EditField _locationField;    private EditField _phoneField;    private SQLManager _sqlManager;    private boolean _newItem;      /**   * Constructs a new ItemScreen object   * @param item The DirectoryItem object to be displayed/edited   * @param sqlManager A sqlManager instance used to perform database operations   * @param newItem True if this screen is displaying a new, blank directory item.False if this screen is displaying an existing directory item.   */    public ItemScreen(DirectoryItem item, SQLManager sqlManager, boolean newItem)    {                _item = item;      _sqlManager = sqlManager;      _newItem = newItem;                // Initialize UI components      setTitle("Item Screen");      _nameField = new EditField("Name: ", _item.getName());      _locationField = new EditField("Address: ", _item.getLocation());      _phoneField = new EditField("Phone: ", _item.getPhone(), 20, BasicEditField.FILTER_PHONE);      add(_nameField);      add(_locationField);      add(_phoneField);                }               /**   * @see MainScreen#makeMenu(Menu, int)   */    protected void makeMenu(Menu menu, int instance)    {      menu.add(new MenuItem("Save", 0x00010000, 0)      {            public void run()            {                        onSave();                close();                           }      });      }            /**   * Updates the DirectoryItem object being displayed with any changes made   * by the user and saves the changes to the database.   *       * @see net.rim.device.api.ui.Screen#onSave()   */    protected boolean onSave()    {      // Item name is mandatory as it will be used as a node description by the TreeField         if(!(_nameField.getText().equals("")))      {            String name = _item.getName();            String location = _item.getLocation();            String phone = _item.getPhone();                        boolean edited = false;                  // Check whether fields have been edited                     if(_nameField.isDirty())            {                name = _nameField.getText();                _item.setName(name);                edited = true;            }                        if(_locationField.isDirty())            {                location = _locationField.getText();                              _item.setLocation(location);                edited = true;            }                        if(_phoneField.isDirty())            {                phone = _phoneField.getText();                _item.setPhone(phone);                edited = true;            }                              if(_newItem)            {                // Add a new item to the database               int id = _sqlManager.addItem(name, location, phone, _item.getCategoryId());                if(id > -1)                {                  _item.setId(id);                }                }             else            {                if(edited)                {                  // Update the existing database record                  _sqlManager.updateItem(_item.getId(), name, location, phone);                }            }                                    return true;      }      else      {            Dialog.alert("Directory entry must have a name");            _nameField.setFocus();            return false;      }            } } 
 
 
SQLManager.java
 
/* * SQLManager.java * * Copyright �1998-2010 Research In Motion Ltd. ** Note: For the sake of simplicity, this sample application may not leverage * resource bundles and resource strings.However, it is STRONGLY recommended * that application developers make use of the localization features available * within the BlackBerry development platform to ensure a seamless application * experience across a variety of languages and geographies.For more information * on localizing your application, please refer to the BlackBerry Java Development * Environment Development Guide associated with this release. */package com.rim.samples.device.sqlitedemo;import java.util.Vector;import net.rim.device.api.database.Cursor;import net.rim.device.api.database.DataTypeException;import net.rim.device.api.database.Database;import net.rim.device.api.database.DatabaseException;import net.rim.device.api.database.Row;import net.rim.device.api.database.Statement;import net.rim.device.api.util.IntHashtable;/** * A class to handle SQLite database logic */public class SQLManager{    private Database _db;            /**   * Constructs a new SQLManager object   * @param db <description>   */    public SQLManager(Database db)    {      _db = db;    }            /**   * Adds a new category to the Category database table   * @param name The name of the Category to be added   * @return A new Category object   */    Category addCategory(String name)    {                Category category = null;      try      {            // INSERT a row into the Category table for the new category            Statement statement = _db.createStatement("INSERT INTO Category VALUES(null, ?)");                                 statement.prepare();                        statement.bind(1, name);            statement.execute();             statement.close();                         // Query the database for the auto-generated ID of the category just added            // and create a new Category object.            statement = _db.createStatement("SELECT category_id FROM Category WHERE category_name = ?");             statement.prepare();            statement.bind(1, name);                                              Cursor cursor = statement.getCursor();                                    if(cursor.next())            {                Row row = cursor.getRow();                int id = row.getInteger(0);                           category = new Category(id, name);                                          }                           cursor.close();            statement.close();      }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());      }            catch(DataTypeException dte)      {            SQLiteDemo.errorDialog(dte.toString());      }                return category;    }            /**   * Adds an item to the Items table in the database   * @param name The name of the business represented by the directory item to be added   * @param location The street address of the business represented by the directory item to be added   * @param phone The phone number for the business represented by the directory item to be added          * @param categoryID The category to which the directory item to be added belongs   * @return The id of the new directory item   */    int addItem(String name, String location, String phone, int categoryID)    {            long id = -1;                try      {            // Insert a new record in the DirectoryItems table                      Statement statement = _db.createStatement("INSERT INTO DirectoryItems VALUES(null, ?, ?, ?, ?)");             statement.prepare();                                    statement.bind(1, categoryID);            statement.bind(2, name);            statement.bind(3, location);            statement.bind(4, phone);                              statement.execute();            statement.close();                  // Retrieve the auto-generated ID of the item just added            id = _db.lastInsertedRowID();                  }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());         }                         return (int)id;      }            /**   * Updates an existing record in the DirectoryItems table   * @param id The id of the item to update   * @param name The text with which to update the name field   * @param location The text with which to update the location field   * @param phone The text with which to update the phone field   */    void updateItem(int id, String name, String location, String phone)    {      try      {                      // Update the record in the DirectoryItems table for the given id            Statement statement = _db.createStatement("UPDATE DirectoryItems SET item_name = ?, location = ?, phone = ? WHERE id = ?");             statement.prepare();                            statement.bind(1, name);            statement.bind(2, location);            statement.bind(3, phone);            statement.bind(4, id);                              statement.execute();                                                       statement.close();      }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());         }                  }            /**   * Deletes a category from the Category table and all corresponding records   * in the DirectoryItems table.   * @param id The id of the category to delete   */    void deleteCategory(int id)    {      try      {            // Delete the record in the Category database table            // corresponding to the highlighted category.            Statement statement = _db.createStatement("DELETE FROM Category WHERE category_id = ?");             statement.prepare();                        statement.bind(1, id);            statement.execute();            statement.close();                        // Delete all items in the DirectoryItems database            // table belonging to the highlighted category.                        statement = _db.createStatement("DELETE FROM DirectoryItems WHERE category_id = ?");             statement.prepare();            statement.bind(1, id);                        statement.execute();            statement.close();      }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());      }            }            /**   * Deletes a directory item record from the database   * @param id The id of the directory item to delete   */    void deleteItem(int id)    {         try      {                  // Delete the record in the DirectoryItems table for the given id            Statement statement = _db.createStatement("DELETE FROM DirectoryItems WHERE id = ?");                                     statement.prepare();                        statement.bind(1, id);            statement.execute();            statement.close();                        }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());      }            }            /**   * Retrieves all records in the Category database table and returns a hash table      * of Category objects.   * @return A hash table of Category objects, one for each record in the Category table   */    IntHashtable getCategories()    {                IntHashtable categories = new IntHashtable();      try      {            // Read in all records from the Category table            Statement statement = _db.createStatement("SELECT * FROM Category");             statement.prepare();            Cursor cursor = statement.getCursor();                                    Row row;            int id;            String name;            Category category;                                             // Iterate through the result set.For each row, create a new            // Category object and add it to the hash table.             while(cursor.next())            {                row = cursor.getRow();                id = row.getInteger(0);                name = row.getString(1);                              category = new Category(id, name);                categories.put(id, category);                            }            statement.close();            cursor.close();      }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());      }      catch(DataTypeException dte)      {            SQLiteDemo.errorDialog(dte.toString());      }                return categories;    }            /**   * Retrieves all records in the DirectoryItems database table and returns   * a vector of DirectoryItem objects.   * @return A vector of DirectoryItem objects, one for each record in the DirectoryItem table   */    Vector getItems()    {      Vector directoryItems = new Vector();                try      {                      // Read in all records from the DirectoryItems table            Statement statement = _db.createStatement("SELECT * FROM DirectoryItems");             statement.prepare();            Cursor cursor = statement.getCursor();                        // Iterate through the the result set.For each row, add a            // new DirectoryItem object to the vector.            while(cursor.next())            {                                    Row row = cursor.getRow();                              int id = row.getInteger(0);                int categoryId = row.getInteger(1);                String name = row.getString(2);                String location = row.getString(3);                String phone = row.getString(4);                                                                                                 DirectoryItem item = new DirectoryItem(id, name, location, phone, categoryId);                directoryItems.addElement(item);                                              }            statement.close();            cursor.close();      }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());      }         catch(DataTypeException dte)      {            SQLiteDemo.errorDialog(dte.toString());      }                  return directoryItems;            }            /**   * Closes the database   */    void closeDB()    {                try      {                        _db.close();      }      catch(DatabaseException dbe)      {            SQLiteDemo.errorDialog(dbe.toString());      }    }} 
 
SQLiteDemoScreen.java
/* * SQLiteDemoScreen.java * * Copyright � 1998-2010 Research In Motion Ltd. ** Note: For the sake of simplicity, this sample application may not leverage * resource bundles and resource strings.However, it is STRONGLY recommended * that application developers make use of the localization features available * within the BlackBerry development platform to ensure a seamless application * experience across a variety of languages and geographies.For more information * on localizing your application, please refer to the BlackBerry Java Development * Environment Development Guide associated with this release. */package com.rim.samples.device.sqlitedemo;import java.util.*;import net.rim.device.api.system.*;import net.rim.device.api.ui.*;import net.rim.device.api.ui.component.*;import net.rim.device.api.ui.container.*;import net.rim.device.api.util.*;/** * The main screen for the SQLiteDemo sample application */public final class SQLiteDemoScreen extends MainScreen implements TreeFieldCallback    {       private TreeField _treeField;            private IntHashtable _categoriesHashtable;    private Vector _directoryItems;    private SQLManager _sqlManager;               /**   * Constructs a new SQLiteDemoScreen   * @param sqlManager A sqlManager instance used to perform database operations   */      public SQLiteDemoScreen(SQLManager sqlManager)      {      super(Screen.DEFAULT_CLOSE);                        _sqlManager = sqlManager;                     // Initialize UI components      setTitle("SQLite Demo");      _treeField = new TreeField(this, Field.FOCUSABLE);               _treeField.setDefaultExpanded( false );      add( _treeField );                      // Populate the tree field and vectors with categories and items      populateCategories();                populateItems();                     }             /**   * Obtains the category hash table from the SQLManager and adds a node   * for each category to the tree field.   */    private void populateCategories()    {                _categoriesHashtable = _sqlManager.getCategories();                  IntEnumeration enumeration = _categoriesHashtable.keys();                        int key;      Category category;      int categoryNode;      while(enumeration.hasMoreElements())      {            key = enumeration.nextElement();            category = (Category)_categoriesHashtable.get(key);                                          categoryNode = _treeField.addChildNode(0, category);                            category.setNode(categoryNode);                      }         }      /**   * Obtains the DirectoryItems vector and adds a node for each item to the   * respective category node in the tree field.   */    private void populateItems()    {         _directoryItems = _sqlManager.getItems();                   DirectoryItem directoryItem;      Category category;      int categoryNode;      int itemNode;                // For each directory item, obtain the corresponding Category object from      // the hash table, then add a child node to the respective category node      // in the tree field.      for(int i = _directoryItems.size() - 1; i >= 0; --i)      {            directoryItem = (DirectoryItem)_directoryItems.elementAt(i);             category = (Category)_categoriesHashtable.get(directoryItem.getCategoryId());            categoryNode = category.getNode();            itemNode = _treeField.addChildNode(categoryNode, directoryItem.getName());             directoryItem.setNode(itemNode);                                                                      }                      }               /**   * Pushes a modal screen to display an existing directory item's details   * @param currentNode The currently highlighted node in the tree field   */         private void displayItem(int currentNode)    {             DirectoryItem item;                // Loop through the DirectoryItems vector until the object is found which      // corresponds to the currently highlighted node.      for(int i = _directoryItems.size() -1; i >= 0; --i)      {            item = (DirectoryItem)_directoryItems.elementAt(i);            if(item.getNode() == currentNode)            {                DirectoryItem itemCopy = new DirectoryItem(item);                                          UiApplication app = UiApplication.getUiApplication();                app.pushModalScreen(new ItemScreen(item, _sqlManager, false));                                    // Check whether the item was changed by the user                if(!itemCopy.equals(item))                              {                  _treeField.setCookie(currentNode, item.getName());// Item was edited, update the cookie for the current node                                 }                break;                        }      }         }         /**   * @see Screen#keyChar(char, int, int)         */    protected boolean keyChar(char key, int status, int time)    {         // Intercept the ENTER key.         if (key == Characters.ENTER)      {            int currentNode = _treeField.getCurrentNode();                  if(_treeField.getCookie(currentNode) instanceof String)            {                displayItem(currentNode);            }            return true;                  }                   return super.keyChar(key, status, time);    }            /**   * @see net.rim.device.api.ui.Screen#invokeAction(int)   */    protected boolean invokeAction(int action)    {                if(action == ACTION_INVOKE) // Trackball click      {            int currentNode = _treeField.getCurrentNode();                if(_treeField.getCookie(currentNode) instanceof String)            {                displayItem(currentNode);            }                            return true; // We've consumed the event                }            returnsuper.invokeAction(action);    }          /**   * @see Screen#onClose()   */    public boolean onClose()    {            _sqlManager.closeDB();                return super.onClose();    }      /**   * @see TreeFieldCallback#drawTreeItem(TreeField, Graphics, int, int, int, int)         */    public void drawTreeItem(TreeField treeField, Graphics graphics, int node, int y, int width, int indent)   {      if( treeField == _treeField )         {                  Object cookie = _treeField.getCookie(node);                                           if(cookie instanceof String)             {                String text = (String)cookie;                graphics.drawText(text, indent, y, Graphics.ELLIPSIS, width);            }                        if(cookie instanceof Category)             {                Category category = (Category)cookie;                String text = category.getName();                graphics.drawText(text, indent, y, Graphics.ELLIPSIS, width);            }      }            }            /**   * @see MainScreen#makeMenu(Menu, int)      */    protected void makeMenu(Menu menu, int context)    {               // Get the cookie for the current node      int currentNode = _treeField.getCurrentNode();                      if(currentNode >= 0)      {            Object cookie = _treeField.getCookie(currentNode);                        if(cookie instanceof Category)            {                // Currently highlighted node is a category node, allow user to add                // an item to or delete the category.                Category category = (Category)cookie;                        menu.add(new AddItem(category.getId(), category.getName(), currentNode));                  MenuItem separator = MenuItem.separator(0);                menu.add(separator);                menu.add(new DeleteCategory(category));                              // Add menu item to add a new category                menu.add(new AddCategory());                                 }            else if(cookie instanceof String)            {                // Currently highlighted node is an item node, allow user to add                // an item to the parent category or delete the highlighted item.                int parentNode = _treeField.getParent(currentNode);                Object parentCookie = _treeField.getCookie(parentNode);                Category parentCategory = (Category)parentCookie;                   menu.add(new OpenItem());                     menu.add(new AddItem(parentCategory.getId(), parentCategory.getName(), parentNode));                              menu.add(new DeleteItem(currentNode));                              // Add menu item to add a new category                MenuItem addCategory = new AddCategory();                addCategory.setOrdinal(0x10000); // Inserts separator               menu.add(addCategory);                                                 }                  }         else      {            // Tree field is empty, start by allowing the addition of a new category            menu.add(new AddCategory());                }                        super.makeMenu(menu, context);    }                /**   * A MenuItem class to add a new directory item to an existing category      */    private final class AddItem extends MenuItem    {                private int _categoryId;      private String _categoryName;      private int _categoryNode;                /**         * Constructs a MenuItem object to add a new directory item to an existing category          * @param categoryId The ID for the category to which the directory item will be added to         * @param categoryName The name of the category to which the directory item will be added to         * @param categoryNode The currently highlighted node, corresponding to the category to which the directory item will be added to         */      private AddItem(int categoryId, String categoryName, int categoryNode)                {            super("", 0, 0);            _categoryId = categoryId;            _categoryName= categoryName;            _categoryNode = categoryNode;                  }                        /**         * Runs when the menu item is invoked by an end user.Pushes a modal         * screen which displays a new, blank directory item.         */      public void run()      {                   SQLiteDemo app = (SQLiteDemo)UiApplication.getUiApplication();            DirectoryItem item = new DirectoryItem(_categoryId);            DirectoryItem itemCopy = new DirectoryItem(item);                                                         app.pushModalScreen(new ItemScreen(item, _sqlManager, true));                        if(!itemCopy.equals(item))                            {                               // Item was saved                int itemNode = _treeField.addChildNode(_categoryNode, item.getName());                              item.setNode(itemNode);                _directoryItems.addElement(item);            }                  }                /**         * @see Object#toString()                  */      public String toString()      {                        return "Add Item to " + _categoryName;      }    }      /**   * A MenuItem class to open a directory item      */    private final class OpenItem extends MenuItem    {      private OpenItem()      {            super("Open Item", 0, 0);                  }                public void run()      {            int currentNode = _treeField.getCurrentNode();                if(_treeField.getCookie(currentNode) instanceof String)            {                displayItem(currentNode);            }                  }                   }                  /**   * A MenuItem class to delete a directory item      */    private final class DeleteItem extends MenuItem    {                private int _currentNode;                        /**         * Constructs a MenuItem object to delete a directory item          * @param currentNode The currently highlighted node, corresponding to the item which should be deleted                  */      private DeleteItem(int currentNode)                {            super("", 0, 0);            _currentNode = currentNode;                  }                        /**         * Runs when the menu item is invoked by an end user.         */      public void run()      {            DirectoryItem item;                        // Loop through the DirectoryItems vector until the object is found which            // corresponds to the currently highlighted node.            for(int i = _directoryItems.size() -1; i >= 0; --i)            {                item = (DirectoryItem)_directoryItems.elementAt(i);                              if(item.getNode() == _currentNode)                {                  // Delete the item from the DirectoryItems vector and the tree field                  _directoryItems.removeElementAt(i);                  _treeField.deleteSubtree(_currentNode);                                    // Delete the item from the database                  _sqlManager.deleteItem(item.getId());                                  }            }                              }                        /**         * @see Object#toString()          */      public String toString()      {                        return "Delete Item";         }    }            /**   * A Dialog subclass which allows an end user to add a new category to   * the application.   */    private final static class AddCategoryDialog extends Dialog    {      EditField _editField;               /**         * Default Constructor         */      public AddCategoryDialog()      {            super(Dialog.D_OK_CANCEL, "Add Category", Dialog.OK, null, Dialog.GLOBAL_STATUS);            _editField = new EditField("Name: ", "");            add(_editField);      }                /**         * Returns the text entered by the user         * @return The text entered by the user         */      String getText()      {            return _editField.getText();      }         }         /**   * A MenuItem class to add a new category to the application and the database.   */    private final class AddCategory extends MenuItem    {            /**         * Default constructor         */      private AddCategory()      {            super("Add Category", 0, 0);                  }                /**         * Runs when the menu item is invoked by the end user.Inserts a new         * entry into the Category database table and adds a new Category object         * to the respective vector.         */      public void run()      {                   AddCategoryDialog dialog = new AddCategoryDialog();            if (dialog.doModal() == Dialog.OK)            {                String name = dialog.getText();                                                         // Add a new category to the database                           Category category = _sqlManager.addCategory(name);                                                          if(category != null)                {                                       int categoryNode = _treeField.addChildNode(0, category);                                          _treeField.setCurrentNode(categoryNode);                                  category.setNode(categoryNode);               }                                                                                                                   }                           }          }         /**   * A MenuItem class to delete a category from the application and from the database   */    private final class DeleteCategory extends MenuItem    {      private Category _category;                /**         * Constructs a new DeleteCategory object to delete a category from the         * application and from the database.         * @param category The Category object to be deleted         */      private DeleteCategory(Category category)      {            super("Delete Category", 0, 0);               _category = category;                }                        /**         * Runs when this menu item is invoked by an end user.         */      public void run()      {                   // Remove category from the tree field                                    _treeField.deleteSubtree(_category.getNode());                        int id = _category.getId();                        // Delete the category from the database            _sqlManager.deleteCategory(id);                        DirectoryItem item;                        // Loop through the DirectoryItems vector and delete all            // objects having a category ID corresponding to the            // highlighted category.            for(int j = _directoryItems.size() - 1; j >= 0; --j)            {                item = (DirectoryItem)_directoryItems.elementAt(j);                if(item.getCategoryId() == id)                {                  _directoryItems.removeElementAt(j);                }            }                        }                /**         * @see Object#toString()          */      public String toString()      {            return "Delete " + _category.getName();      }          }}  
DirectoryItem.java
 
/* * DirectoryItem.java * * Copyright � 1998-2010 Research In Motion Ltd. ** Note: For the sake of simplicity, this sample application may not leverage * resource bundles and resource strings.However, it is STRONGLY recommended * that application developers make use of the localization features available * within the BlackBerry development platform to ensure a seamless application * experience across a variety of languages and geographies.For more information * on localizing your application, please refer to the BlackBerry Java Development * Environment Development Guide associated with this release. */package com.rim.samples.device.sqlitedemo;/** * Class to represent a directory item */public final class DirectoryItem{    private String _name;    private String _location;    private String _phone;    private int _categoryId;    private int _id;       private int _node;         /**   * This constructor is called when the application starts and item   * records are read from the database.This application maintains   * a Vector of DirectoryItem objects, one for each item record in the   * database.      * @param id The unique ID for the directory item   * @param name The name of the business represented by the directory item   * @param location The street address of the business represented by the directory item   * @param phone The phone number for the business represented by the directory item   * @param categoryId The category to which the directory item belongs   * @param node The tree field node number that maps to this directory item   */      public DirectoryItem(int id, String name, String location, String phone, int categoryId)    {      _id = id;      _name = name;      _location = location;      _phone = phone;      _categoryId = categoryId;                  }         /**   * This constructor is used to create a copy of an existing DirectoryItem   * object for the purpose of determining whether the original object has   * been edited in the item screen.   * @param item The original DirectoryItem to copy   */    DirectoryItem(DirectoryItem item)    {      _name = item.getName();      _location = item.getLocation();      _phone = item.getPhone();                  }      /**   * This constructor is called when a user wishes to add a new item   * to a given category.   * @param categoryId The id for the category to which the new item will be added   */    DirectoryItem(int categoryId)    {      _categoryId = categoryId;                _name = "";      _location = "";      _phone = "";            }      /**   * @see Object#equals(Object)   */    public boolean equals(Object obj)    {      if(obj == this)      {            return true;      }                boolean equal = false;                if(obj instanceof DirectoryItem)      {            DirectoryItem item = (DirectoryItem)obj;            equal =(item.getName().equals(_name) && item.getLocation().equals(_location) && item.getPhone().equals(_phone));                     }      return equal;         }      /**   * Returns the unique ID for the directory item   * @return The unique ID associated with this DirectoryItem object   */    int getId()    {      return _id;    }      /**   * Returns the name of the business represented by the directory item   * @return The name of the business represented by this DirectoryItem object   */    String getName()    {      return _name;    }      /**   * Returns the street address of the business represented by the directory item   * @return The street address of the business represented by this DirectoryItem object   */    String getLocation()    {      return _location;    }      /**   * Returns the phone number for the business represented by the directory item   * @return The phone number for the business represented by this DirectoryItem object   */    String getPhone()    {      return _phone;    }      /**   * Returns the ID of the category to which the directory item belongs   * @return The ID of the category to which this DirectoryItem object belongs   */    int getCategoryId()    {      return _categoryId;    }         /**   * Returns the tree field node number that maps to this directory item   * @return The tree field node number that maps to this DirectoryItem object   */    int getNode()    {      return _node;    }          /**   * Sets the name of the business represented by the directory item   * @param name The text to set as the name of the business represented by this DirectoryItem object   */    void setName(String name)    {      _name = name;    }      /**   * Sets the street address of the business represented by this directory item      * @param location The text to set as the street address of the business represented by this DirectoryItem object   */    void setLocation(String location)    {      _location = location;    }      /**   * Sets the phone number for the business represented by this directory item object   * @param phone The text to set as the phone number for the business represented by this DirectoryItem object   */    void setPhone(String phone)    {      _phone = phone;    }            /**   * Sets the tree field node number that maps to this directory item   * @param node The tree field node number that maps to this DirectoryItem object   */    void setNode(int node)    {      _node = node;    }            /**   * Sets the unique ID for the directory item as generated by the database   * @param id The unique ID for the directory item as generated by the database   */    void setId(int id)    {      _id = id;    }}      
Category.java
 
/* * Category.java * * Copyright � 1998-2010 Research In Motion Ltd. ** Note: For the sake of simplicity, this sample application may not leverage * resource bundles and resource strings.However, it is STRONGLY recommended * that application developers make use of the localization features available * within the BlackBerry development platform to ensure a seamless application * experience across a variety of languages and geographies.For more information * on localizing your application, please refer to the BlackBerry Java Development * Environment Development Guide associated with this release. */package com.rim.samples.device.sqlitedemo;/** * Class to represent a directory category */public final class Category {    int _id;    String _name;    int _node;      /**   * Constructs a Category object   * @param id The unique identifier associated with the category   * @param name The descriptive name of the category   */    public Category(int id, String name)    {      _id = id;      _name = name;            }            /**   * Returns the unique identifier associated with the category   * @return The unique identifier associated with this Category object   */    int getId()      {      return _id;            }      /**   * Returns the descriptive name of the category   * @return The descriptive name of this Category object   */            String getName()    {      return _name;    }      /**   * Returns the tree field node number that maps to the category   * @return The tree field node number that maps to this Category object   */    int getNode()    {      return _node;    }      /**   * Sets the tree field node number that maps to the category   * @param node The tree field node number that maps to this Category object   */    void setNode(int node)    {      _node = node;            }} 
 
 
http://dl.iteye.com/upload/attachment/271398/43c580cb-8431-3c92-93ad-2c834b21948b.jpg
页: [1]
查看完整版本: [官方Demo]BlackBerry SQL与 TreeField 官方实例