In this lesson, you write code to create and connect to an UltraLiteJ database. The code to create a new database is defined in a singleton class called DataAccess, and is invoked from the HomeScreen constructor. Using a singleton class ensures that only one database connection is open at a time. While UltraLiteJ supports multiple connections, it is a common design pattern to use a single connection.
Here is a complete, updated HomeScreen class. The DataAccess object is held as a class-level variable, so that it can be accessed from other parts of the code.
class HomeScreen extends MainScreen {
HomeScreen() {
// Set the window title
LabelField applicationTitle = new LabelField("Hello BlackBerry");
setTitle(applicationTitle);
// Add a label to show application status
_statusLabel = new LabelField( "Status: Started");
add( _statusLabel );
// Create database and connect
try{
_da = DataAccess.getDataAccess();
_statusLabel.setText("Status: Connected");
}
catch( Exception ex)
{
_statusLabel.setText("Exception: " + ex.toString() );
}
}
private LabelField _statusLabel;
private DataAccess _da;
} |
package myapp;
import ianywhere.ultralitej.*;
import java.util.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
class DataAccess {
DataAccess() { }
public static synchronized DataAccess getDataAccess(boolean reset)
throws Exception
{
if( _da == null ){
_da = new DataAccess();
ConfigObjectStore _config =
DatabaseManager.createConfigurationObjectStore("HelloDB");
if(reset)
{
_conn = DatabaseManager.createDatabase( _config );
}
else
{
try{
_conn = DatabaseManager.connect( _config );
}
catch( ULjException uex1) {
if( uex1.getErrorCode() !=
ULjException.SQLE_ULTRALITE_DATABASE_NOT_FOUND ) {
System.out.println( "Exception: " +
uex1.toString() );
Dialog.alert( "Exception: " + uex1.toString() +
". Recreating database..." );
}
_conn = DatabaseManager.createDatabase( _config );
}
}
_da.createDatabaseSchema();
}
return _da;
}
private static Connection _conn;
private static DataAccess _da;
} |
This class imports the ianywhere.ultralitej package from the UltraLiteJ.jar file. The steps to create or connect to a database are:
If the connection attempt fails, create the database. The createDatabase method then returns an open connection.
You should see a status message indicating that the application successfully connected to the database.
| Send feedback about this page via email or DocCommentXchange | Copyright © 2008, iAnywhere Solutions, Inc. - SQL Anywhere 11.0.0 |