Sunday, August 30, 2009

Code Signing

Quote from Knowbedge Article about code Signing:
"Research In Motion (RIM) must track the use of sensitive application programming interfaces (APIs) in the
BlackBerry JDE for security and export control reasons. In the API reference documentation, sensitive classes or
methods are indicated by a lock icon or are noted as signed. If you use these controlled classes or methods in your
applications, your application must be signed with a key or a signature provided by RIM before you can load the
application .cod files onto the BlackBerry smartphone."
For Buying Code signing keys Go Here. You have to spend 20 USD to buy the key.

Some Other Reference link from KB Article.
What Is - Code signing and obtaining signature keys
Register Signing Keys
How To - sign a .cod file 
 
Also Have a look at this Article. Here signing steps explained clearly. 
 
Once you have the key you can sign as many application as you want.
And just in case if you lost the keys RIM resend you the keys to your mail address by disabling your previous keys. For that you have to send a mail to devsupport@rim.com requesting the keys and regarding your issue about key lost. The normally respond within 2-3 business days.

Legally you cannot use the keys more than one PC.
But Practically you can use the keys in any PC. For this:
a. Preserve the following files:
i.   sigtool.db
ii.  sigtool.csk
iii. sigtool.set
b. Copy these files in the JDE bin directory. (ex: C:\Program Files\Research In Motion\BlackBerry JDE 4.3.0\bin)


Clickable BitmapField



For making BitmapField clickable
------------------------------------------------

Bitmap image = Bitmap.createBitmapFromResource("button.png");
BitmapField imageButton = new BitmapField(image, BitmapField.FOCUSABLE)
{
private XYRect xyrect=new XYRect();
protected boolean navigationClick(int status, int time)
{
// This is method will invoke after clicking the image
// System.out.println("Image Clicked");
return true;
}
};

Align Field in Center



For aligning ButtonField in a HorizontalFieldManager
---------------------------------------------------------------------------

HorizontalFieldManager hfm = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
ButtonField button = new ButtonField("Button",DrawStyle.HCENTER);
hfm.add(button);


For aligning LabelFIeld Center
---------------------------------------------------------------------------

LabelField labelField = new LabelField("Center Label", LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER);



Drawing a Circle



There is no direct api in the graphics class to draw circle.
So for creating circle have to use eclipse or arc.

Circle Property
---------------------
1. Center point of the circle (x, y)
2. Radius r

Now circle can be drawn in the following ways
------------------------------------------------------------------


Graphics.drawEclipse(x, y, x + r, y, x, y + r, 0, 360);


Graphics.fillArc(x, y, r, r, 0, 360);
Graphics.drawArc(x, y, r, r, 0, 360);

Clickable LabelField act like Link (Href Field )


The example of a LabelField which act like html link.

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.system.Characters;


public class HrefField extends Field {

private String content;
private Font fieldFont;
private int fieldWidth;
private int fieldHeight;
private boolean active = false;
private int backgroundColour = 0xffffff;
//private int textColour = 0x333333;
private int textColour = 0x0000ff;
private int maskColour = 0xBBBBBB;

private int buttonId;
private String buttonName;

public HrefField(String content)
{
super(Field.FOCUSABLE);
this.content = content;
fieldFont = defaultFont();
fieldWidth = fieldFont.getAdvance(content)+2;
fieldHeight = fieldFont.getHeight() + 3;
}

public void setColours(int backgroundColour, int textColour, int maskColour)
{
this.backgroundColour = backgroundColour;
this.textColour = textColour;
this.maskColour = maskColour;
invalidate();
}

public void setBackgroundColour(int backgroundColour)
{
this.backgroundColour = backgroundColour;
invalidate();
}

public void setTextColour(int textColour)
{
this.textColour = textColour;
invalidate();
}

public void setMaskColour(int maskColour)
{
this.maskColour = maskColour;
invalidate();
}

public void setFont(Font fieldFont)
{
this.fieldFont = fieldFont;
}

public int getPreferredWidth()
{
return fieldWidth;
}

public int getPreferredHeight()
{
return fieldHeight;
}

protected void layout(int arg0, int arg1)
{
setExtent(getPreferredWidth(), getPreferredHeight());
}

protected void paint(Graphics graphics)
{

if (active)
{
graphics.setColor(maskColour);
graphics.fillRect(0, 0, fieldWidth, fieldHeight);
}
else
{
graphics.setColor(backgroundColour);
graphics.fillRect(0, 0, fieldWidth, fieldHeight);
}

graphics.setColor(textColour);
graphics.setFont(fieldFont);
graphics.drawText(content, 1, 1);
graphics.drawLine(1, fieldHeight-2, fieldWidth-2, fieldHeight-2);
}

protected boolean navigationClick(int status, int time)
{
fieldChangeNotify(1);
return true;
}

public void setButtonId(int buttonId)
{
this.buttonId = buttonId;
}

public void setButtonName(String buttonName)
{
this.buttonName = buttonName;
}

public int getButtonId()
{
return buttonId;
}
public String getButtonName()
{
return buttonName;
}
public boolean keyChar(char key, int status, int time)
{
if (key == Characters.ENTER)
{
fieldChangeNotify(0);
return true;
}

return false;
}


protected void onFocus(int direction)
{
active = true;
invalidate();
}

protected void onUnfocus()
{
active = false;
invalidate();
}

public static Font defaultFont()
{
return Font.getDefault();
}
}



Ignore Click Event outside of a Field in Storm



In Storm sometimes click event in invoked by clicking outside of a focusable field.
To solve this just add the following code to the MainScreen or a Manager.


protected boolean touchEvent(TouchEvent message)
{
int event = message.getEvent();
if (event == TouchEvent.CLICK || event == TouchEvent.UNCLICK)
{
// Ignore clcik events that happen outside any fields
if (getFieldAtLocation(message.getX(1), message.getY(1)) == -1)
return true; // kill the event
}
return super.touchEvent(message);
}

// The regular getFieldAtLocation returns wrong values
//in open spaces in complex managers, so we override it
public int getFieldAtLocation(int x, int y)
{
XYRect rect = new XYRect();
int index = getFieldCount() -1;
while (index >= 0)
{
getField(index).getExtent(rect);
if (rect.contains(x, y))
break;
--index;
}
return index;
}



Knowledge Base Article Links



Some Knowledge Base Article Links.



1. Application Deployment
#########################

Genaral Topics
--------------
How To - Define the position of an application icon on the BlackBerry smartphone Home screen How To - Handle stored data when removing an application
How To - Load applications onto a BlackBerry smartphone
Support - A module with that name already exists in the application
Support - Application installation errors
Support - BlackBerry MDS Runtime 1.1.2 with BlackBerry Device Software 4.3.0 stops responding when an application calls from the on_init script
Support - MIDlet has verification error at offset
Support - Module net_rim_bbapi_mail not found
Support - Protocol not found- null error
Support - Unable to activate custom theme or theme not listed
Support - Version 4.0 applications do not run on the device
What Is - Indications of insufficient space to install an application on the BlackBerry device
What Is - JVM error codes
What Is - JVM error codes for BlackBerry Device Software 4.2 and later


OTA Download
------------
How To - Programmatically read the attributes of a JAD file
Support - 907 Invalid Jar Error when installing an application wirelessly
Support - Warning - This application does not contain a signature. It might not be from a trusted source.
What Is - The file size limit for wireless downloads
What Is - The required MIME types for a web server to serve BlackBerry applications


Desktop Loading
---------------
How To - Configure ALX files to make an application 'required'
How To - Create a single ALX file to install multiple versions of an application
How To - Install the BlackBerry API update via Desktop Manager or wirelessly
How To - Remove wirelessly downloaded applications
How To - Update the registry to deploy Java applications using Desktop Manager
Support - Handheld displays net_rim_xml not found error
Support - Invalid digital signature errors when installing an application
Support - No system software was found for your device
Support - Unspecified error encountered [J-0x00000011] when upgrading a third-party application
What Is - An .alx file


Enterprise server application push
-----------------------------------
How To - Deploy an icon to the BlackBerry smartphone for a web application or URL


Blackberry Application Web Loader
-----------------------------------
Support - The BlackBerry Application Web Loader is unable to create a local copy of files


2. Java APIs & Samples
#######################

Memory Management
-----------------
How To - Download large files using the BlackBerry Mobile Data System
How to - Prevent a memory leak when implementing an ApplicationMenuItem
Sample Code ---- Object Groups - Why and How to Use Them
What Is - File storage limits in the Content Store
What Is - Object Grouping - Using resources effectively

Mail
------
How To - Retrieve the default email address for the device
How To - Access HTML email messages
How To - Capture the contents of email and PIN messages before sending
How To - Create a custom Attachment Handler on the BlackBerry device
How To - Create an Attachment
How To - Create and send messages
How To - Display a PopupScreen from a SendListener
How To - Implement the ViewListener interface
How To - Programmatically send a PIN message
How To - Retrieve More of a Message
How To - Send a message from a non-default email address
Support - Error when sending a PIN message - MessagingExceptionPin message not sent. Do not have the permissions to send the message.
Support - Transport.more fails to retrieve all of a message
What Is - Application is not notified when new messages arrive


Invoking Blackberry Application
-------------------------------
How To - Invoke applications
How to - Make a running UI application go to the background and resume in the foreground
How To - Open a file in a Documents To Go application
What Is - Application does not provide invocation feedback

GPS
----
How To - Add an ApplicationMenuItem to BlackBerry Map
How To - Configure a Bluetooth GPS Receiver for use with the Location API
How To - Define criteria to retrieve a GPS fix
How To - Detect when GPS is no longer available and when to reset the LocationProvider
How To - Invoke BlackBerry Maps
How To - Manage simultaneous GPS and phone usage on the BlackBerry 8703e and the 7130e smartphones
Support - Cellsite fix prevents acquiring autonomous GPS fixes
Support - Incorrect network time
Support - Invoking BlackBerry Maps throws unexpected runtime exception
What Is - Best practices for designing GPS applications for BlackBerry smartphones operating on CDMA networks
What Is - BlackBerry Maps location document format
What Is - The BlackBerry smartphone models and their corresponding GPS capabilities
What Is - Verizon GPSSettings signing requirement


Cryptography APIs and Security
------------------------------
How To - Save requested application permissions in the Application Permissions screen
How To - Create a Unique long from a String
How to - Use Advanced Encryption
How to - Use Basic Encryption
How To - Use Content Protection


Browser API
-----------

How To - Change the RenderingOptions of a RenderingSession
How To - Create a Fixed Size BrowserField
How To - Create a web icon
How to - Create a web signal registration application
How To - Enable cookies in BrowserField
How To - Invoke a non-default browser session
How To - Invoke the browser
How To - Invoke the browser with raw HTML
How To - Invoke the default browser
How To - Perform a browser push over SSL
What Is - A ControlledAccessException is thrown when using the HttpFilterRegistry
What Is - The Push notification format

Bluetooth - USB - Serial
-------------------------
How To - Run the BlackBerry Serial Port Demo
How To - Use the Bluetooth classes
How To - Use the ServiceRouting API
Support - IOException thrown when opening a server-side Bluetooth connection
What Is - Bluetooth support on BlackBerry devices


Audio & Video
--------------
How To - Invoke the media application
How To - Obtain the media playback time from a media application
How To - Play audio in an application
How To - Play video within a BlackBerry smartphone application
How To - Record audio on a BlackBerry smartphone
How To - Specify Audio Path Routing
How To - Support streaming audio to the media application
How To - Take a snapshot using the built-in camera of a BlackBerry smartphone
Known Issue - Delay in playing audio when streaming to a Bluetooth headset
Support - Alert.startBuzzer() does not work
Support - Playing audio in an application pauses the Media application on BlackBerry smartphones running on the CDMA network
What Is - Media application error codes
What Is - setMediaTime does not work for AMR files
What Is - Supported audio formats


Menu Item and Options
-----------------------
How To - Add a custom menu item to an existing BlackBerry application
How To - Add application options to the BlackBerry Options
How To - Handle ApplicationMenuItem Invocation


MIDP & CLDC APIs
----------------
How To - Access images in a MIDP application
How To - Capture volume keys in a MIDlet
How To - Create a MIDlet that uses custom animation
How To - Create an auto-start MIDlet using the PushRegistry
How To - Establish an HTTP connection
How To - Implement basic HTTP authentication
How To - Register a MIDlet with the PushRegistry
How To - Use RMS storage efficiently in BlackBerry applications
Support - Classname does not exist in the current application package
Support - Verification error using javax.microedition.rms.RecordStore on BlackBerry Device Software 3.8 and 4.0
What Is - Cannot run a MIDP 2.0 application in BlackBerry Device Software 4.0


Micellaneous
------------
How To - Access and Obtain Service Books on a device
How To - Capture Signature on the BlackBerry Storm
How to - Create a singleton using the RuntimeStore
How To - Detect Alt and Shift key clicks
How To - Determine if a BlackBerry smartphone supports Wi-Fi capabilities
How to - Display custom messages in the request permission dialog
How To - Format the electronic serial number (ESN)
How To - Get time zone offsets with DST
How To - Implement a Comparator to compare objects
How To - Implement a string splitter based on a given string delimiter
How To - Interpret wireless network signal levels How To - Write safe initialization code
Known Issue - The RadioStatusListener.mobilityManagementEvent method is not invoked
Support - Preventing verification errors
What is - Event injection
What Is - New and Deprecated APIs in BlackBerry Java Development Environment 4.0
What Is - New and Deprecated APIs in BlackBerry Java Development Environment 4.1
What Is - New and Deprecated APIs in BlackBerry Java Development Environment 4.2


Networking
----------
How to - Determine the country code of the current mobile subscriber How To - Determine the MCC and MNC of the current network


Persistence
-----------
How To - Programmatically determine if a microSD card has been inserted

Phone
-----
How To - Implement the PhoneListener interface
How To - Log Phone Calls
Support - The getDevicePhone method returns null


PIM-PDAP
--------
How To - Access Address Book contacts
How To - Add a PIM item to a custom category
How To - Create an Event within the Calendar application
How To - Launch the Address Book and return a contact
How To - Use Remote Address Lookup through coding Support - Application stops receiving event notifications when using the PIMListListener API


SVG Content
-----------
How to - Use Plazmic Content Developer's Kit in your BlackBerry Application
Known Issue - Irregular focus behaviour on first hotspot when loading PME content
Known Issue - Losing the anchor when rendering SVG images in MIDlets
What Is - Browser fails to retrieve resources using relative URLs in PME content


Synchronization APIs
--------------------
How To - Backup and restore small amounts of data using SyncItem
How To - Compile the Desktop Add-In sample
How To - Save data with RMS
How To - Store persistent data on the BlackBerry smartphone


System Classes
--------------
How To - Add plain text or binary files to an application
How To - Allow an application to restart itself
How to - Capture power change events
How to - Code time-sensitive applications
How To - Detect if the BlackBerry smartphone is holstered or flipped
How To - Display a GUI when the BlackBerry device starts up
How To - Enable the backlight and prevent the screen from turning off
How To - Launch a third-party application from another third-party application
How To - Obtain the operating system version of a BlackBerry wireless device
How to - Programmatically install and upgrade applications
How To - Retrieve the BlackBerry Device Software version
Support - An unsupported API was called by the JVM RadioGetGprsState
Support - getObjectSize and getAllocated return 0
What Is - Global Events and Global Event Listeners
What Is - Supported System.getProperty keys
What Is - System Global Events
What Is - The reason a reset is required when upgrading an application



Voice Notes
----------
How To - Use the Voice Notes APIs
Samples --- VoiceNotesDemo Sample Code


XML
---
How To - Control the behavior of white space when parsing an XML document
How To - Use the XML Parser


User Interface
--------------

Fields
======
How To - Add a TreeField to a device screen
How To - Apply a phone number filter to an AutoTextEdit field
How To - Change the text color of a field
How To - Create a colour ListField
How To - Create a custom field using attributes of other UI objects
How To - Create a custom width for a ListField
How To - Create a ListField with check boxes
How To - Create a Scrollable Image Field
How To - Create custom fields
How To - Determine the number of visible items on the BlackBerry device screen
How To - Display a progress bar in handheld applications
How To - Display an animated GIF
How To - Display dates and times in handheld applications
How To - Format text in a RichTextField
How to - Make list items appear on a screen
How To - Show focus changes using BitmapField
How to - Use an image in an application
How To - Use the paint() method to draw objects to the screen
How To - Work around ListField painting issue in early versions of BlackBerry Device Software version 4.2.2
Support - A Field's font is displayed incorrectly when set in the paint method
Support - Error starting [Application Name].Symbol'DateField.[init] not found
Support - NullPointerException is thrown when the isEditable and fieldChangeNotify methods of EditField are overridden
Support - The Custom Field is not drawing properly



Managers
========
How To - Create a custom layout manager for a screen
How To - Create a screen with stationary headings
How To - Create tabbed view screens
How To - Manage bitmaps in an application using field managers
How to - Perform double buffering using the BlackBerry UI
How To - Place multiple UI fields on one line
How to - Use the User Interface API to create an editable table
Support - My scrollable manager is not scrolling



Screens
=======
How to - Change the background color of a screen
How To - Clear the status of a MainScreen
How To - Create a custom Dialog
How To - Create a File Selection Popup Screen
How To - Create a splash screen
How To - Have Your Application Perform an Action after a Global Alert
How to - listen for a dialog closed event
How To - Obtain the Height and Width of a Screen
How To - Prevent a UiApplication from being listed in the application switcher
How To - Properly Push and Pop Global Screens
How to - Protect BlackBerry applications with a password screen
How To - Remove the default "Close" or "Hide" MenuItems from a Screen
How to - Update a screen on the Main Event Thread
How To - Use a Backdoor Sequence



General
=======
How To - Add Copy, Paste, and other context-specific items to a menu
How To - Alert a user from a Background application
How To - Capture and save a screen shot
How To - Change fonts in a BlackBerry application
How To - Control the screen orientation
How To - Create an icon for an application
How To - Define a rollover icon for an application
How To - Detect when an application or screen moves to the foreground or background
How To - Distinguish between a full menu and a primary actions menu
How to - Leverage pattern matching in BlackBerry smartphone applications to provide an integrated user experience
How to - Make your BlackBerry application more user-friendly
How to - Manage UI interactions
How To - Programmatically determine type of keyboard
How To - Use a background image in application screens
Known Issue - Screen.invalidate() does not cause a subsequent call to paint()
What Is - BlackBerry UI hierarchy
What Is - Image formats used in BlackBerry applications
What Is - Screen buffer size



3. Blackberry Administration API
################################
How To - Get started with the BlackBerry Administration API
What Is - Sample application demonstrating BlackBerry Administration API technology



4. Blackberry JDE
#################

Executing clean.bat does not delete third-party applications from the BlackBerry Smartphone Simulator
How To - Add a Certificate to DeviceKeyStore
How To - Add files to a project
How To - Compile a JAR file into a BlackBerry Library
How To - Compile a MIDlet into a COD file
How To - Compile an application
How To - Configure an application to start automatically when the device is turned on
How To - Configure multiple versions of BlackBerry JDE on the same computer
How To - Configure the BlackBerry Mobile Data Service Simulator to allow reliable push connections
How To - Connect the JDE to a specified simulator bundle
How To - Debug an application running on a live BlackBerry smartphone
How To - Detect a deadlock using the JDE
How to - Detect system availability on startup
How To - Determine the Current Network Name
How To - Enable a keyboard shortcut for an application
How To - Find memory leaks in code
How To - Gain access to the BlackBerry JDE
How To - Get started with the BlackBerry JDE
How To - Obfuscate code for a BlackBerry application
How To - Setup an alternate entry point for my application
How To - Update the Path environment variable
How To - Use Javaloader to take a screen shot
How To - Use the Coverage tool to provide code coverage when testing applications
How To - Use the Profiler tool to optimize application code
How To - Use the RAPC compiler
Support - BlackBerry Java Development Environment and supported locales
Support - BlackBerry JDE 3.7 IDE Fatal Error on startup
Support - BlackBerry JDE crashes when using the Objects view
Support - BlackBerry JDE fails to start
Support - BlackBerry JDE JAR files no longer function after WinRAR is installed
Support - BlackBerry JDE stops responding when viewing project properties
Support - Compiled application size is larger in BlackBerry JDE 4.3.0 or later
Support - Connection Timeout error when launching JDWP from Eclipse
Support - Error - com.sun.tools.javac.code.Symbol$CompletionFailure - file net\rim\device\internal\ui\Border.class not found
Support - Error cod data section too large
Support - Error when debugging - Cannot find RIMIDEWin32Util.dll. This is a required component of the IDE.
Support - How to fix BlackBerry JDE screen artifacts
Support - I/O Error CreateProcess
Support - I/O Error Import file not found appears when building an application
Support - Missing stack map at label
Support - Ordinal 11 could not be located in the dynamic link library DSound.dll
Support - Signing does not apply the RIM Runtime signature key
Support - Unable to Open Socket when running JDWP
Support - Vtable record size exceeds maximum record size
What Is - A library and how to use it
What Is - A stack trace
What Is - Appropriate version of the BlackBerry JDE
What Is - Control Flow Verification Information Too Large
What Is - Introduction to the BlackBerry JDE
What Is - 'javaw' error when starting the JDE after installation
What Is - Supported versions of Java for different BlackBerry JDE versions
What is - The Alias List for a project in the BlackBerry JDE
What Is - The debugger
What Is - The project size limit
What Is - Writing applications for the Java-based BlackBerry Wireless Handhelds in C and C++ native code

Saturday, August 29, 2009

Resize Image in Blackberry

Sometimes it is needed to resize an image.
Resizing an image to a smaller resolution may cause some distortion of the image.


Image can be programatically resize in many ways.


Approach 1
----------

private Bitmap getScaledBitmapImage(EncodedImage image, int width, int height)
{
// Handle null image
if (image == null)
{
return null;
}

//return bestFit(image.getBitmap(), width, height);

int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());

int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);

int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);

image = image.scaleImage32(scaleXFixed32, scaleYFixed32);

return image.getBitmap();
}



Approach 2
------------

public static Bitmap resizeBitmap(Bitmap image, int width, int height)
{
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();

// Need an array (for RGB, with the size of original image)
int rgb[] = new int[imageWidth * imageHeight];

// Get the RGB array of image into "rgb"
image.getARGB(rgb, 0, imageWidth, 0, 0, imageWidth, imageHeight);

// Call to our function and obtain rgb2
int rgb2[] = rescaleArray(rgb, imageWidth, imageHeight, width, height);

// Create an image with that RGB array
Bitmap temp2 = new Bitmap(width, height);

temp2.setARGB(rgb2, 0, width, 0, 0, width, height);

return temp2;
}

private static int[] rescaleArray(int[] ini, int x, int y, int x2, int y2)
{
int out[] = new int[x2*y2];
for (int yy = 0; yy < y2; yy++)
{
int dy = yy * y / y2;
for (int xx = 0; xx < x2; xx++)
{
int dx = xx * x / x2;
out[(x2 * yy) + xx] = ini[(x * dy) + dx];
}
}
return out;
}




Approach 3
----------

public static Bitmap bestFit(Bitmap image, int maxWidth, int maxHeight)
{
// getting image properties
int w = image.getWidth();
int h = image.getHeight();

// get the ratio
int ratiow = 100 * maxWidth / w;
int ratioh = 100 * maxHeight / h;

// this is to find the best ratio to
// resize the image without deformations
int ratio = Math.min(ratiow, ratioh);

// computing final desired dimensions
int desiredWidth = w * ratio / 100;
int desiredHeight = h * ratio / 100;

//resizing
return resizeBitmap(image, desiredWidth, desiredHeight);
}


907: Invalid Jar

During installing blackberry application through OTA this the following error message may occur.
“Invalid 907 COD: Unable to import ZIP file”.

To resolve this problem:
If the cod file size is more than 64K then Rename your big *.cod file to *.zip file and unzip it. Then there will be several smaller *.cod files. Now delete the *.zip file.

Also the details soltion of this error is described in this Knowledge Base Article.

OTA Installation of a Blackberry Application



After completing an application the next big step is to install the application OTA(over the air).

The Steps for OTA installation
------------------------------

1. For OTA the cod and jad files will be needed.

2. Sign your cod if required.

3. Now if cod file size is bigger than 64 kb then rename it to *.zip file and try
    to unzip.
    a. If it cannot be unzipped rename it to *.cod, there are no sibling files inside.
    b. If it can be unzipped, delete zip file after it is unzipped.
     Then you will have more than one cod like name.cod, name-1.cod, name-2.code, and so on.

4. Place jad file and all extracted cod files to a folder(for example : ota) on
    your web-site.

5. Now you have to set MIME types for the files.
    a) Inside the folder (ota) that contains jad and cods, create a file with name .htaccess
     please note a dot symbol before the name.
    b) And add the following content to this file and save it.
     AddType text/vnd.sun.j2me.app-descriptor jad
     AddType application/java-archive jar
     AddType application/vnd.rim.cod cod

6. Now you are ready to install the application through OTA.

7. Just hit the link of the jad file through the bb browser. It will automatically
    start install the application in the device.


Sunday, August 2, 2009

How to Add jar file in Blackberry



Something it is required to add third party application jar in your blackberry application.
For example you want to use KXML Parser to parse XML in your application.

Then go through the steps below to add the kxml jar to your application:
----------------------------------------------------------------------------------------
1.Preverify your jar file (just in case if it is not preverified). Follow the steps below for preverifying:
   a. Go to your JDE installation folder (C:\Program Files\Research In Motion\BlackBerry JDE 4.3.0\bin)
   b. Copy the jar file to bin folder.
   c. Now open your command prompt and change your current directory to your JDE installation directory.
   d. Now execute the following command:

   preverify -classpath "C:\Program Files\Research In Motion\BlackBerry JDE 4.3.0\lib\net_rim_api.jar" "your_jar_filename"


   e. In your bin directory(C:\Program Files\Research In Motion\BlackBerry JDE 4.3.0\bin) a folder named output will create.
   f. Preverified jar file resides here.

2.Now Add the preverified jar file to your project like normal java file (Right Click on the project -> All File to    Project...).
   If it not works with just adding then you have to add the jar as a library project.
   How_To_-_Compile_a_JAR_file_into_a_BlackBerry_Library


How to Animate GIF Image in Blackberry



For animating a gif image in bb screen follow the steps:
-------------------------------------------------------------------------------
1. Add the gif image (ex. myImage.gif) in the project (Right Click on the Project -> Add File to Project...).

2. Images added to a project are automatically converted into the Portable Network Graphics (PNG) format when
    the application is built into a .cod file.

3. This problem can be resolved by any of the following approach:
     a. rename the gif image as *.bin (myImage.bin) and then add in the project
     b. Project Properties -> Compile Tab -> Check Don't convert image files to PNG

4. Load the image into GIFEncodedImage
    GIFEncodedImage image;
    EncodedImage encodedImage = EncodedImage.getEncodedImageResource("myImage.bin");
    byte data[] = new byte[4000];
    data = encodedImage.getData();
    image =(GIFEncodedImage) EncodedImage.createEncodedImage(data,0,data.length);

5. Create a AnimatedGIFField using the GIFEncodedImage
    AnimatedGIFField animatedGIF = new AnimatedGIFField(image);

6. Finally add the field into the screen and get gif image animated.
    add(animatedGIF);


Tuesday, July 28, 2009

Writing Custom TextBox in Blackberry

Something it is required to write customized TextBox because using native API you cannot get the border, backgound color, backgroung image, left shift characters when text are more than one line without customizing.

In such type of cases you can create a Class extending Field
and the following things have to override:
* sublayout()
* paint()
* getPreferredWidth()
* getPreferredHeight()

The below Class demonstrate the above implementation:

import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.system.Characters;
import net.rim.device.api.math.Fixed32;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Font;

public class CustomTextBox extends Manager
{
/**
* Default margins
*/
private final static int DEFAULT_LEFT_MARGIN = 10;
private final static int DEFAULT_RIGHT_MARGIN = 10;
private final static int DEFAULT_TOP_MARGIN = 5;
private final static int DEFAULT_BOTTOM_MARGIN = 5;

/**
* Default paddings
*/
private final static int DEFAULT_LEFT_PADDING = 10;
private final static int DEFAULT_RIGHT_PADDING = 10;
private final static int DEFAULT_TOP_PADDING = 5;
private final static int DEFAULT_BOTTOM_PADDING = 5;

/**
* Margins around the text box
*/
private int topMargin = DEFAULT_TOP_MARGIN;
private int bottomMargin = DEFAULT_BOTTOM_MARGIN;
private int leftMargin = DEFAULT_LEFT_MARGIN;
private int rightMargin = DEFAULT_RIGHT_MARGIN;

/**
* Padding around the text box
*/
private int topPadding = DEFAULT_TOP_PADDING;
private int bottomPadding = DEFAULT_BOTTOM_PADDING;
private int leftPadding = DEFAULT_LEFT_PADDING;
private int rightPadding = DEFAULT_RIGHT_PADDING;

/**
* Amount of empty space horizontally around the text box
*/
private int totalHorizontalEmptySpace = leftMargin + leftPadding
+ rightPadding + rightMargin;

/**
* Amount of empty space vertically around the text box
*/
private int totalVerticalEmptySpace = topMargin + topPadding
+ bottomPadding + bottomMargin;

/**
* Minimum height of the text box required to display the text entered
*/
private int minHeight = getFont().getHeight() + totalVerticalEmptySpace;

/**
* Width of the text box
*/
private int width = Display.getWidth();

/**
* Height of the text box
*/
private int height = minHeight;

/**
* Background image for the text box
*/
private EncodedImage backgroundImage;

/**
* Bitmap version of the backgroundImage.
* Needed to reduce the calculation overhead incurred by
* scaling of the given image
* and derivation of Bitmap from the
* EncodedImage every time it is needed.
*/
private Bitmap bitmapBackgroundImage;

/**
* The core element of this text box
*/
private EditField editField;
//private BasicEditField editField;

//private String entireText;

public CustomTextBox()
{
// Let the super class initialize the core
super(0);

// An edit field is the sole field of this manager.
editField = new EditField();
//editField = new CustomEditField();
add(editField);
}

public CustomTextBox(EncodedImage backgroundImage)
{
this();
setBackgroundImage(backgroundImage);
}

public void setSize(int width, int height)
{
boolean isChanged = false;

if (width > 0 // Ignore invalid width
&& this.width != width)
{
this.width = width;
isChanged = true;
}

// Ignore the specified height if it is less
// than the minimum height required to display the text.
if (height > minHeight && height != this.height)
{
this.height = height;
isChanged = true;
}

// If width/height has been changed and background image
// is available, adapt it to the new dimension
if (isChanged == true && backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}

public void setWidth(int width)
{

if (width > 0 && width != this.width)
{
this.width = width;

// If background image is available, adapt it to the new width
if (backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
}

public void setHeight(int height)
{
// Ignore the specified height if it is
// less than the minimum height required to display the text.
if (height > minHeight)
{
this.height = height;

// If background image is available, adapt it to the new width
if (backgroundImage != null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}
}

public void setBackgroundImage(EncodedImage backgroundImage)
{
this.backgroundImage = backgroundImage;

// Consider the height of background image in
// calculating the height of the text box.
// setHeight() does not ensure that specified
// height will be in effect, of course, for valid reasons.
// So derivation of Bitmap image in the setHeight() method is not sure.
setHeight(backgroundImage.getHeight() + topMargin + bottomMargin);
if (bitmapBackgroundImage == null)
{
bitmapBackgroundImage = getScaledBitmapImage(backgroundImage,
this.width - (leftMargin+rightMargin),
this.height - (topMargin+bottomMargin));
}
}

/**
* Generate and return a Bitmap Image scaled according
* to the specified width and height.
*
* @param image EncodedImage object
* @param width Intended width of the returned Bitmap object
* @param height Intended height of the returned Bitmap object
* @return Bitmap object
*/
private Bitmap getScaledBitmapImage(EncodedImage image, int width, int height)
{
// Handle null image
if (image == null)
{
return null;
}

int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());

int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);

int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);

image = image.scaleImage32(scaleXFixed32, scaleYFixed32);

return image.getBitmap();
}


protected void sublayout(int width, int height)
{
// We have one and only child - the edit field.
// Place it at the appropriate place.
Field field = getField(0);
layoutChild(field, this.width - totalHorizontalEmptySpace,
this.height - totalVerticalEmptySpace);
setPositionChild(field, leftMargin+leftPadding, topMargin+topPadding);

setExtent(this.width, this.height);
}

public void setTopMargin(int topMargin)
{
this.topMargin = topMargin;
}

public void setBottomMargin(int bottomMargin)
{
this.bottomMargin = bottomMargin;
}


protected void paint(Graphics graphics)
{
// Draw background image if available, otherwise draw a rectangle
if (bitmapBackgroundImage == null)
{
//graphics.drawRect(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin));
graphics.drawRoundRect(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin), 5, 5);
}
else
{
graphics.drawBitmap(leftMargin, topMargin,
width - (leftMargin+rightMargin),
height - (topMargin+bottomMargin),
bitmapBackgroundImage, 0, 0);
}

// Determine the rightward text that can fit into the visible edit field

EditField ef = (EditField)getField(0);
String entireText = ef.getText();

boolean longText = false;
String textToDraw = "";
Font font = getFont();
int availableWidth = width - totalHorizontalEmptySpace;
if (font.getAdvance(entireText) <= availableWidth)
{
textToDraw = entireText;
}
else
{
int endIndex = entireText.length();
for (int beginIndex = 1; beginIndex < endIndex; beginIndex++)
{
textToDraw = entireText.substring(beginIndex);
if (font.getAdvance(textToDraw) <= availableWidth)
{
longText = true;
break;
}
}
}

if (longText == true)
{
// Force the edit field display only the truncated text
ef.setText(textToDraw);

// Now let the components draw themselves
super.paint(graphics);

// Return the text field its original text
ef.setText(entireText);
}
else
{
super.paint(graphics);
}
}

public int getPreferredWidth()
{
return width;
}

public int getPreferredHeight()
{
return height;
}

protected boolean keyChar(char ch, int status, int time)
{
if (ch == Characters.ENTER)
{
return true;
}
else
{
return super.keyChar(ch, status, time);
}
}

public String getText()
{
return ((EditField)getField(0)).getText();
}

public void setText(final String text)
{
((EditField)getField(0)).setText(text);
}
}



Monday, July 27, 2009

Title Bar in Blackberry



The common approach of setting title in BB scrren is like:
setTitle(Field)

But problem of using setTitle method is the border color that you cannot remove.
This is associated with the device theme.

Then one have to write his own title bar.

The following TitleBar has the below properties:
* background color is black
* title image is placed horizontal center
* title bar height is same as the height of the title image


import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
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.system.*;


/**
* customized Title Bar
* background color is black (BACKGROUND_COLOR)
* image is placed horizontal center (titleImage)
* title bar height is same as the height of the title image (fieldHeight)
*/
public class TitleBar extends Field implements DrawStyle
{
private int fieldWidth;
private int fieldHeight;
private int fontColour;
private int backgroundColor;

private Bitmap titleImage = Bitmap.getBitmapResource("topBannerTransparent.png");
private static final int BACKGROUND_COLOR = 0x00000000;


public TitleBar()
{
super(Field.NON_FOCUSABLE);
fieldHeight = titleImage.getHeight();
fieldWidth = Graphics.getScreenWidth();

//background color is black
backgroundColor = BACKGROUND_COLOR;
}

public void setBackgroundColour(int _backgroundColour)
{
backgroundColor = _backgroundColour;
invalidate();
}

protected void layout(int width, int height)
{
setExtent(getPreferredWidth(), getPreferredHeight());
}

public int getPreferredWidth()
{
return fieldWidth;
}

public int getPreferredHeight()
{
return fieldHeight;
}

protected void paint(Graphics graphics)
{

int w = this.getPreferredWidth();
int h = this.getPreferredHeight();

graphics.setColor(backgroundColor);
graphics.fillRect(0, 0, w, h);

int marginX = (w- titleImage.getWidth() ) / 2 ;
graphics.drawBitmap(marginX, 0, w, h, titleImage, 0, 0);
}
}


To make this TitleBar treat like original title bar( always visible in the top) the main scrren have to modify like below:

import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.Graphics;
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.system.*;

class TitleBarExampleScreen extends MainScreen
{
TitleBar titleBar = new TitleBar();
int titleBarHeight = titleBar.getPreferredHeight();

public TitleBarExampleScreen()
{

super(NO_VERTICAL_SCROLL);

//title Bar added here
this.add(titleBar);


VerticalFieldManager verticalManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(0x00000000);
graphics.clear();
super.paint(graphics);
}
protected void sublayout( int maxWidth, int maxHeight )
{
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight() - titleBarHeight;

super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};

//now add everything in the verticalManager
verticalManager.add(new LabelField("Test Label"));
verticalManager.add(new ButtonField("Test Button"));

//and at last add verticalManager in scereen
this.add(verticalManager);
}
}



Thursday, July 23, 2009

How to Read, Write and Copy file in Blackberry

It is very common feature in Blackberry to read/write/copy file programatically in BlackBerry.

Read file in the SDCard in the following way:

InputStream inputStream = null;
FileConnection fileConnection = (FileConnection) Connector.open( "file:///SDCard/testfile.txt");
if (fileConnection.exists())
{
inputStream = fconn.openInputStream();
}


ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
while (true) {
int bytesRead = inputStream.read( buffer, 0, BUFFER_SIZE );
if (bytesRead == -1)
break;
byteArrayOutputStream.write( buffer, 0, bytesRead );
}
byteArrayOutputStream.flush();
byte[] result = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
String resultString = new String(result);



Write/Save file in SDCard in the following way:

FileConnection fc = (FileConnection) Connector.open(System.getProperty("file:///SDCard/"+"fileName.txt"),Connector.READ_WRITE);
if(!fc.exists())
{
fc.create();
}
OutputStream os =fc.openOutputStream();
os.write("Test");
os.close();
fc.close()




Copy file in SDCard in the following way:

public static void copyFile(String srFile, String dtFile)
{
try
{
FileConnection f1;
FileConnection f2;

f1 = (FileConnection) Connector.open(srFile,Connector.READ_WRITE);
f2 = (FileConnection) Connector.open(dtFile,Connector.READ_WRITE);
if(!f2.exists()) // if file does not exists , create a new one
{
f2.create();
}
InputStream is = f1.openInputStream();
OutputStream os =f2.openOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
{
os.write(buf, 0, len);
}
is.close();
os.close();
}
catch(IOException e)
{

}
}



Also check this link for more information about file path.

How to Place a Field Vertically and Horizontally center in the Blackberry Screen

For placing a Field (for example HorizontalFieldManager) in center of the screen simple setting margin will do the trick.

Here is an example of placing a HorizontalFieldManager in the center.



HorizontalFieldManager hfm = new HorizontalFieldManager();

LabelField testLabel1 = new LabelField( "Test Label1");
LabelField testLabel2 = new LabelField( "Test Label2");
hfm.add(testLabel1);
hfm.add(testLabel2);

int leftEmptySpace = (Display.getWidth() - hfm.getPreferredWidth()) / 2;
int topEmptySpace = (Display.getHeight() - hfm.getPreferredHeight()) / 2;
hfm.setMargin(topEmptySpace, 0, 0, leftEmptySpace);

//now add this manager to MainScreen
this.add(hfm);





How to set Background color of Blackberry Screen

For setting background color in Blackberry screen we need to do the following.

Disable Vertical scrolling of the main screen.

Now create a VerticalFieldManager with vertical scroll enabled. This will be the main manger where screen component have to add. Set the width and height of this manager as Screen width and height by overriding sublayout() method.
And override paint() method to set backgroung color

Here is the example code with above implemented.



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.system.*;

class TestScreen extends MainScreen{

private VerticalFieldManager verticalManager;
private HorizontalFieldManager hrzManager;

TestScreen()
{
super(NO_VERTICAL_SCROLL);

//rather than adding component
//in the mainScreen add components
//in this verticalManager and then
//add this manager to mainScreen
verticalManager = new VerticalFieldManager(
Manager.VERTICAL_SCROLL |
Manager.VERTICAL_SCROLLBAR)
{
public void paint(Graphics graphics)
{
//blue
graphics.setBackgroundColor(0x000000ff);
graphics.clear();
super.paint(graphics);
}
protected void sublayout( int maxWidth, int maxHeight )
{
int width = Display.getWidth();
int height = Display.getHeight();
super.sublayout( width, height);
setExtent( width, height);
}
};

ButtonField button1 = new ButtonField("Button1");
ButtonField button2 = new ButtonField("Button2");
ButtonField button3 = new ButtonField("Button3");
ButtonField button4 = new ButtonField("Button4");
ButtonField button5 = new ButtonField("Button5");

verticalManager.add(button1);
verticalManager.add(button2);
verticalManager.add(button3);
verticalManager.add(button4);
verticalManager.add(button5);
this.add(verticalManager);

}
}



Also have a look at this KnowledgeBase Article for getting better idea.


How to set Background Image in Blackberry

For setting image in the background of the Blackberry screen we need to do the following.

First create a VerticalFieldManager and override the paint method of that manager and then draw Bitmap inside paint() method with the device width and height. Disable vertical scrolling of this manager.

Now create another VerticalFieldManager with vertical scroll enabled. This will be the main manger where screen component have to add. Set the width and height of this manager as Screen width and height by overriding sublayout() method.


Here is the example code with above implemented.


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.system.*;

public class TestScreen extends MainScreen
{

private VerticalFieldManager mainManager;
private VerticalFieldManager subManager;
private Bitmap _backgroundBitmap = Bitmap.getBitmapResource
("sunset.png");
private int deviceWidth = Display.getWidth();
private int deviceHeight = Display.getHeight();

public TestScreen()
{
super(NO_VERTICAL_SCROLL);

//this manager is used for the static background image
mainManager = new VerticalFieldManager(
Manager.NO_VERTICAL_SCROLL |
Manager.NO_VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.clear();
graphics.drawBitmap(0, 0, deviceWidth,
deviceHeight, _backgroundBitmap, 0, 0);
super.paint(graphics);
}
};

//this manger is used for adding the componentes
subManager = new VerticalFieldManager(
Manager.VERTICAL_SCROLL |
Manager.VERTICAL_SCROLLBAR )
{
protected void sublayout(int maxWidth, int maxHeight)
{
int displayWidth = deviceWidth;
int displayHeight = deviceHeight;

super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};

/// add your component to this subManager
subManager.add(new ButtonField("Test Button"));
/////////////////////////////////////////

//add subManager over the mainManager
mainManager.add(subManager);

//finally add the mainManager over the screen
this.add(mainManager);
}
}



Wednesday, July 22, 2009

HelloWorld in BlackBerry

Before starting anything its became a tradition to start with HelloWorld.
Here list of HelloWorld programming in 200 different languages.

So to maintain the tradition we are going to write helloWorld in BlackBerry. :)

1. Open the JDE

2. Create a new workspace (File -> New -> Workspaces) and name it as helloWorld .

3. Create a new Project under the helloWorld workspace
File -> New -> Projects or
Right click on the helloWorld.jdw (on the left side of the JDE) and click 'Create new Project in
helloWorld.jdw ...' and name it as helloWorld.

4. Now create a file under the helloWorld project.
Right click on the helloWorld.jdp and click 'Create new File in
Project ...' and name it as HelloWorld.java

5. Paste the following in the HelloWorld.java file.




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.system.*;

class HelloWorld extends UiApplication
{
public HelloWorld()
{
super();

/// creating mainScreen to diaply hellowrld
MainScreen helloWorldScreen = new MainScreen();
LabelField lbl = new LabelField("Hello World");
helloWorldScreen.add(lbl);

//pushing that screen to Display
this.pushScreen(helloWorldScreen);
}

public static void main(String[] args)
{
HelloWorld helloWorld = new HelloWorld();
helloWorld.enterEventDispatcher();
}
}


6. Now build and Run the project (Build -> Build All and Run)

7. Go to the home screen of the simulator and click the application named helloWorld.

8. Enjoy HelloWorld in the BB Simulator.

Create the Environment for BlackBerry development

Before starting HelloWorld we need to create the environment for BlackBerry development.

Blackberry applications can be developed using Blackberry JDE, Eclipse Plugin, Netbeans plugin and Visual Studio Plugin.

I use Blackberry JDE for my development. I prefer this because this is provided by the RIM.


We have to follow the following steps for making our PC to start HelloWorld using BB JDE.

1. Before staring it is very important to choose the JDE. Have a look at this KnowledgeBase article.

2. For example you chosen JDE 4.6.0.
You can download any other version from here.

3. Now Install the "BlackBerry_JDE_4.6.0.exe" that you downloaded

4. Install any latest JDK (ex: jdk-6u5-windows-i586-p.exe)

5. Update your environment variable.
Control Panel -> System -> Environment variables -> click path in the system variables ->
Edit. Now add the following in Variable value ; each with a semicolon in the end
a) C:\Program Files\Java\jdk1.6.0_05\bin

b) C:\Program Files\Java\jre1.6.0_05\bin

c) C:\Program Files\Research In Motion\BlackBerry JDE 4.6.0\bin

6. Restart your PC or simply the logoff will do.

Now we are ready to start HelloWorld in Blackberry :)