List of all Iphone and Blackberry Development codes in a one click Iphone,objective C,xcode,blackberry Development,iOS Development

Friday, May 18, 2012

Blackberry Knowledge Base Articles


     
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
 


        

Tuesday, May 15, 2012

Draw painting and save as Image in Blackberry




Draw your paintings and save it as an image. This will help you for doing that.

















Background white image for drawing your paintings.

_bitmap= Bitmap.getBitmapResource("background.png");//white color background image
_signatureField = new SignatureField(_bitmap);
add(_signatureField);


When you press the capture button on the menu, it will save your painting as an image.

private MenuItem _captureItem = new MenuItem("Capture", 200000, 10) {
public void run() {
//Create a new instance of the encoder to encode the bitmap into an image
PNGEncoder encoder = new PNGEncoder(_bitmap, true);
try {
byte[] imageBytes = encoder.encode(true);
EncodedImage image = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
try {
FileConnection fconn = (FileConnection) Connector.open(
new StringBuffer().append("file:///store/home/user/").append("Signature-").append(System.currentTimeMillis()).append(".png").toString());
if (!fconn.exists())
fconn.create();
DataOutputStream ds = fconn.openDataOutputStream();
ds.write(image.getData());
ds.close();
fconn.close();
} catch (IOException e) {
Dialog.alert(e.getMessage());
e.printStackTrace();
}
} catch (IOException e) {
Dialog.alert(e.getMessage());
e.printStackTrace();
}
}
};

/**
* MenuItem to clear the signature field
*/
private MenuItem _clearItem = new MenuItem("Clear", 200000, 10) {
public void run() {
_signatureField.clear();
}

};

/**
* MenuItem to close the application
*/
private MenuItem _closeItem = new MenuItem("Close", 200000, 10) {
public void run() {
onClose();
}
};

/**
* Create the menu
*/
protected void makeMenu(Menu menu, int instance) {
menu.add(_captureItem);
menu.add(_clearItem);
menu.add(_closeItem);
}

final class SignatureField extends BitmapField {

private Graphics _graphics;

/**
* Constructor
*/
public SignatureField(Bitmap b) {
this.setBitmap(b);
_graphics = new Graphics(b);
}

/**
* Handle touch events
*/
protected boolean touchEvent(TouchEvent message) {
try {
if (message.getEvent() == TouchEvent.MOVE) { //Move event fired
//Get the move points
int pointsSize = message.getMovePointsSize();

if (pointsSize > 1)
{
int[] xPoints = new int[pointsSize];
int[] yPoints = new int[pointsSize];
message.getMovePoints(1, xPoints, yPoints, null);
drawPath(xPoints,yPoints);
}
} else if (message.getEvent() == TouchEvent.GESTURE) { //Gesture event fired
TouchGesture gesture = message.getGesture();
if (gesture.getEvent() == TouchGesture.TAP) { //Tap Gesture
//Since we have a tap only draw a single point
int xPoint = message.getX(1);
int yPoint = message.getY(1);
drawPoint(xPoint,yPoint);
} else if (gesture.getEvent() == TouchGesture.SWIPE) { //Swipe Gesture
//Get the move points
int pointsSize = message.getMovePointsSize();
int[] xPoints = new int[pointsSize];
int[] yPoints = new int[pointsSize];
message.getMovePoints(1, xPoints, yPoints, null);
drawPath(xPoints,yPoints);
}
}
} catch (Throwable e) {
throw new RuntimeException(e.toString());
}
return true;
}

/**
* Draw a path through the set of points
*/
private void drawPath(int[] xPoints, int[] yPoints) {
int oldColor = _graphics.getColor();
//Draw a path through the points
_graphics.setColor(Color.RED);
_graphics.drawPathOutline(xPoints,yPoints, null, null, false);
_graphics.setColor(oldColor);
//Repaint
invalidate();
}

/**
* Draw a point
*/
private void drawPoint(int xPoint, int yPoint) {
int oldColor = _graphics.getColor();
_graphics.setColor(0x000000);
_graphics.drawPoint(xPoint, yPoint);
_graphics.setColor(oldColor);
//Repaint
invalidate();
}

/**
* Clear the field
*/
private void clear() {
int oldColor = _graphics.getColor();
_graphics.setColor(0xFFFFFF);
_graphics.fillRect(0, 0, _bitmap.getWidth(), _bitmap.getHeight());
_graphics.setColor(oldColor);
invalidate();
}
}




        

Wednesday, May 2, 2012

BarGraph in Blackberry



















If you want to display a bar graph, then lets try this code sample. This will help you in drawing a bar graph in blackberry.

//BarScreen  - MainScreen class ---

import net.rim.device.api.ui.component.NullField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class BarScreen extends MainScreen
{
 
    private BarGraphField _bar;
    private boolean _barChanged = false;
    private MainScreen _barScreen;
 
    public BarScreen(long style)
    {
        super(style);
     
        _barScreen = this;
     
        //Graph data.
        VerticalFieldManager graphLayout = new VerticalFieldManager(VerticalFieldManager.FIELD_VCENTER);
        final int[] values = {60,50,40,30,20,10};
        final int[] colors = {0x00FF0000,0x007F525D , 0x00E77471, 0x00C8B560, 0x00ADDFFF,0};      
        _bar = new BarGraphField(values, colors, 100, 5, 30, BarGraphField.PADDING_MEDIUM, BarGraphField.PADDING_HIGH, true);
        //Add a focusable NullField for scrolling purposes.
        this.add(new NullField(NullField.FOCUSABLE));
        _bar.setPadding(20, 0, 0, 20);
        graphLayout.add(_bar);
        this.add(graphLayout);
        this.add(new NullField(NullField.FOCUSABLE));
     
    }
}


// BarGraphField  class--------

import net.rim.device.api.ui.Graphics;
import net.rim.device.api.util.Arrays;
import net.rim.device.api.ui.Font;

public class BarGraphField extends GraphField
{
    
    public static final int PADDING_NONE = 0;
    
    public static final int PADDING_LOW = 4;
  
    public static final int PADDING_MEDIUM = 8;
    
  
    public static final int PADDING_HIGH = 12;
    
    private int _scale, _increment, _barWidth, _barPadding, _scalePadding;
    private boolean _showScale;
    
  
    public BarGraphField(int[] values, int[] colors, int scale, int increment, int barWidth)
    {
        this(values, colors, scale, increment, barWidth, PADDING_MEDIUM, PADDING_MEDIUM, false);
    }
    
   
    public BarGraphField(int[] values, int[] colors, int scale, int increment, int barWidth, boolean showScale)
    {
        this(values, colors, scale, increment, barWidth, PADDING_MEDIUM, PADDING_MEDIUM, showScale);
    }
    
    
    public BarGraphField(int[] values, int[] colors, int scale, int increment, int barWidth, int barPadding, 
        int scalePadding, boolean showScale)
    {
        
        //Ensure the scale is greater than 0.
        if (scale <= 0)
            throw new IllegalArgumentException("Scale must be greater than 0.");
            
        //Ensure the increment is greater than 0.
        if (increment <= 0)
            throw new IllegalArgumentException("Increment must be greater than 0.");
            
        //Ensure the barWidth is greater than 0.
        if (barWidth <= 0)
            throw new IllegalArgumentException("Bar width must be greater than 0.");
            
        //Ensure barPadding is a valid value.
        switch (barPadding)
        {
            case PADDING_NONE:
            case PADDING_LOW:
            case PADDING_MEDIUM:
            case PADDING_HIGH:
            break;
            default:
                throw new IllegalArgumentException("Invalid bar padding specified");
        }
        
        //Ensure scalePadding is a valid value.
        switch (scalePadding)
        {
            case PADDING_NONE:
            case PADDING_LOW:
            case PADDING_MEDIUM:
            case PADDING_HIGH:
            break;
            default:
                throw new IllegalArgumentException("Invalid scale padding specified");
        }
        
        //Ensure the number of bar values match the number of colors.
        if (values.length != colors.length)
            throw new IllegalArgumentException("Non matching array lengths for values and colors.");
            
        //Ensure not values are greater than the scale value.
        for(int count = values.length - 1; count >= 0; --count)
        {
            if (values[count] > scale)
                throw new IllegalArgumentException("Value greater than scale.");
        }
        
        _values = values;
        _colors = colors;
        _scale = scale;
        _increment = increment;
        _barWidth = barWidth;
        _barPadding = barPadding;
        _scalePadding = scalePadding;
        _showScale = showScale;
        _width = calcWidth();
        _height = calcHeight();
    }
    
   

    private int calcWidth()
    {
        int theWidth;
        
        if (_showScale)
            theWidth = Font.getDefault().getAdvance(Integer.toString(_scale)) + 8 
                + (_values.length * _barWidth) + ((_values.length - 1) * _barPadding);
        else
            theWidth = 10 + (_values.length * _barWidth) + ((_values.length - 1) * _barPadding); 
       
        return theWidth;
    }
    private int calcHeight()
    {
        if (_showScale)
            return 2 + (Font.getDefault().getHeight() * (_scale / _increment));
        else if (_scalePadding == PADDING_NONE)
            return 2 + (PADDING_LOW * (_scale / _increment));
        else
            return 2 + (_scalePadding * (_scale / _increment));
    }
    
   protected void paint(Graphics graphics)
    {
        int count, tempX, tempY, leftOver, graphHeight = 0;
        
        int tickHeight;             //The height of the scale ticks.
        int tickIndent;             //The distance to indent the scale ticks.
        
        if (_showScale)
        {
            tickHeight = Font.getDefault().getHeight();
            //Subtract 4 from the width of the scale (2 pixels for the scale width and 2 pixels for spacing).
            tickIndent = Font.getDefault().getAdvance(Integer.toString(_scale)) - 4;
        }
        else
        {
            if (_scalePadding == PADDING_NONE)
                tickHeight = PADDING_LOW;
            else
                tickHeight = _scalePadding;
            
            tickIndent = 0;
        }
        
        //Wipe out any existing graph image data.
        graphics.clear();
        
        graphics.setColor(0);
        
        //In case the increment doesn't divide into the scale evenly.
        leftOver = _scale % _increment;
        tempY = 0;
        
        //Draw the scale.
        for (count = _scale; count > leftOver; count-=_increment)
        {
            graphics.fillRect(tickIndent, tempY, 6, 2);
            
            if (_showScale)
                graphics.drawText(Integer.toString(count), 0, tempY);
            
            tempY += tickHeight;
        }
        
        tempX = tickIndent + 6;
        
        //Draw the x axis.
        graphics.fillRect(tempX, tempY, _width - tempX, 2);
        
        //Draw the y axis.
        graphics.fillRect(tempX, 0, 2, _height);
        
        tempX = _width - _barWidth;
        
        //Draw the bars.
        for (count = _values.length - 1; count >= 0; --count)
        {
            graphics.setColor(_colors[count]);
            
            //Calculate the top bar as a percentage of the available graphing space
            //relating to the value.  Graphing space is _height - 2 (2 pixel y axis).
            tempY = _height - (((_height - 2) * _values[count]) / _scale);
            graphHeight = _height - tempY - 2;
            
            graphics.fillRect(tempX, tempY, _barWidth, graphHeight);
            
            //Calculate the next graph starting point.
            tempX -= (_barWidth + _barPadding);
        }
    }
    
   
    public int getBarPadding()
    {
        return _barPadding;
    }
    
    
    public int getBarWidth()
    {
        return _barWidth;
    }
    

   
    public int getIncrement()
    {
        return _increment;
    }
    
   
    public int getScale()
    {
        return _scale;
    }
    
  
    public int getScalePadding()
    {
        return _scalePadding;
    }
   
    public boolean isScaleVisible()
    {
        return _showScale;
    }
    
    
    public void setBarPadding(int barPadding)
    {
        //Don't do anything unless the bar padding has changed.
        if (_barPadding != barPadding)
        {
            //Ensure barPadding is a valid value.
            switch (barPadding)
            {
                case PADDING_NONE:
                case PADDING_LOW:
                case PADDING_MEDIUM:
                case PADDING_HIGH:
                break;
                default:
                    throw new IllegalArgumentException("Invalid bar padding specified");
            }
            
            _barPadding = barPadding;
            _width = calcWidth();
        }
    }
    
    
    public void setBarWidth(int barWidth)
    {
        //Dont do anything unless the bar width has changed.
        if (_barWidth != barWidth)
        {
            //Ensure the barWidth is greater than 0.
            if (barWidth <= 0)
                throw new IllegalArgumentException("Bar width must be greater than 0.");
                
            _barWidth = barWidth;
            _width = calcWidth();
        }
    }
    
  
    public void setGraphData(int[] values, int[] colors)
    {
        //Don't do anything unless the data has changed.
        if (!Arrays.equals(_values, values) || !Arrays.equals(_colors, colors))
        {
            //Ensure the number of values match the number of colors.
            if (values.length != colors.length)
                throw new IllegalArgumentException("Non matching array lengths for bars and colors.");
                
            //Ensure not values are greater than the scale value.
            for(int count = values.length - 1; count >= 0; --count)
            {
                if (values[count] > _scale)
                    throw new IllegalArgumentException("Value greater than scale.");
            }                
                            
            _values = values;
            _colors = colors;

            _width = calcWidth();
            _height = calcHeight();
        }
    }
  
   
    public void setIncrement(int increment)
    {
        //Don't do anything unless the increment has changed.
        if (_increment != increment)
        {
            //Ensure the increment is greater than 0.
            if (increment <= 0)
                throw new IllegalArgumentException("Increment must be greater than 0.");
                
            //Only the height changes with an increment change.
            _increment = increment;
            _height = calcHeight();
        }
    }
    
   
    public void setScale(int scale)
    {
        ///Don't do anything unless the scale has changed.
        if (_scale != scale)
        {
            //Ensure the scale is greater than 0.
            if (scale <= 0)
                throw new IllegalArgumentException("Scale must be greater than 0.");
                
            //Ensure no values are greater than the scale value.
            for(int count = _values.length - 1; count >= 0; --count)
            {
                if (_values[count] > scale)
                    throw new IllegalArgumentException("Value greater than scale.");
            }
            
            _scale = scale;
            _width = calcWidth();
            _height = calcHeight();
        }
    }
    
   
    public void setScalePadding(int scalePadding)
    {
        //Don't do anything unless the scale padding has changed.
        if (_scalePadding != scalePadding)
        {
            //Ensure scalePadding is a valid value.
            switch (scalePadding)
            {
                case PADDING_NONE:
                case PADDING_LOW:
                case PADDING_MEDIUM:
                case PADDING_HIGH:
                break;
                default:
                    throw new IllegalArgumentException("Invalid scale padding specified");
            }
            
            _scalePadding = scalePadding;
            _height = calcHeight();
        }
    }
    
   
    public void setScaleVisible(boolean showScale)
    {
        //Don't do anything unless the flag has changed.
        if (_showScale != showScale)
        {
            _showScale = showScale;
            _width = calcWidth();
            _height = calcHeight();
        }
    }
}


//GraphField  class ------

import net.rim.device.api.ui.Field;
public abstract class GraphField extends Field
{
    protected int[] _values;
    
    
    protected int[] _colors;
   
    protected int _width;
    
    
    protected int _height;
    
   
    GraphField() 
    {    
        super();
    }
    
   
    public int getColor(int index)
    {
        return _colors[index];
    }
   
    public int[] getColors()
    {
        return _colors;
    }
   
    public int getValue(int index)
    {
        return _values[index];
    }
    
   
    public int[] getValues()
    {
        return _values;
    }
   
    public void setGraphData(int[] values, int[] colors)
    {
        _values = values;
        _colors = colors;
    }
    
    public int getPreferredHeight()
    {
    return _height;
    }
    
    public int getPreferredWidth()
    {
    return _width;
    }
  
    protected void layout(int width, int height)
    {
    int w, h;
   
    if (width >= _width)
    {
    w = _width;
    }
    else
    {
    w = width;
   
    }
   
    if (height >= _height)
    {
    h = _height;
    }
    else
    {
    h = height;
    }
   
    setExtent(w, h);
    }




        

Tuesday, May 1, 2012

Display Stop Watch (Timer) in Blackberry


        import java.util.Timer;
    import java.util.TimerTask;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.FieldChangeListener;
    import net.rim.device.api.ui.UiApplication;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.Dialog;
    import net.rim.device.api.ui.component.RichTextField;
    import net.rim.device.api.ui.container.HorizontalFieldManager;
    import net.rim.device.api.ui.container.MainScreen;

    public class stopwatch extends MainScreen
    {

       private RichTextField _chronometer;
       Timer timer;
       private int second = 0, minute = 0, hour = 0;
       private boolean _sec = false, _min = false, _hou = false;
       ButtonField record,stop;

       public stopwatch()
       {

           record=new ButtonField("Start");
           stop=new ButtonField("Stop");

           _chronometer = new RichTextField("0" + hour + ":0" + minute + ":0" + second, RichTextField.TEXT_ALIGN_HCENTER | Field.NON_FOCUSABLE);
           add(_chronometer);

           HorizontalFieldManager hfm=new HorizontalFieldManager(FIELD_HCENTER);
           record.setMargin(net.rim.device.api.system.Display.getHeight()/2,0,0,0);
           stop.setMargin(net.rim.device.api.system.Display.getHeight()/2,0,0,20);
           hfm.add(record);

           hfm.add(stop);

           add(hfm);


           FieldChangeListener listener = new FieldChangeListener() {
               public void fieldChanged(Field field, int context) {

                   if(field==record){
                        try
                           {

                               try {
                                   timer = new Timer();
                                   resetChronometer();
                                   timer.scheduleAtFixedRate(new Chronometer(), 1000, 1000);
                               } catch (Exception e) {
                                   e.printStackTrace();
                               }
                           }
                           catch (Exception e)
                           {
                               Dialog.alert(e.toString());
                           }
                   }
                   if(field==stop){

                           try
                           {

                                   timer.cancel();

                           }
                           catch (Exception e)
                           {
                               Dialog.alert(e.toString());
                           }





                   }

               }
           };
           record.setChangeListener(listener);
           stop.setChangeListener(listener);

       }

           private class Chronometer extends TimerTask {
               public void run() {
                   try {
                       second++;
                       UiApplication.getUiApplication().invokeLater(new Runnable() {
                           public void run() {

                               if (_min == true) {
                                   _min = false;
                                   minute = minute + 1;
                                   second = 0;
                               }

                               if (_hou == true) {
                                   _hou = false;
                                   hour = hour + 1;
                                   minute = 0;
                               }

                               if (second == 59) {
                                   _min = true;
                                   if (minute == 59) {
                                       _hou = true;
                                   }
                               }

                               if (second <= 9 && minute <= 9 && hour <= 9) {
                                   _chronometer.setText("0" + hour + ":0" + minute + ":0" + second);
                               }

                               if (second > 9 && minute <= 9 && hour <= 9) {
                                   _chronometer.setText("0" + hour + ":0" + minute + ":" + second);
                               }

                               if (second <= 9 && minute > 9 && hour <= 9) {
                                   _chronometer.setText("0" + hour + ":" + minute + ":0" + second);
                               }

                               if (second <= 9 && minute <= 9 && hour > 9) {
                                   _chronometer.setText("" + hour + ":0" + minute + ":0" + second);
                               }

                               if (second > 9 && minute > 9 && hour > 9) {
                                   _chronometer.setText(hour + ":" + minute + ":" + second);
                               }

                               if (second > 9 && minute > 9 && hour <= 9) {
                                   _chronometer.setText("0" + hour + ":" + minute + ":" + second);
                               }

                               if (second > 9 && minute <= 9 && hour > 9) {
                                   _chronometer.setText("" + hour + ":0" + minute + ":" + second);
                               }

                               if (second <= 9 && minute > 9 && hour > 9) {
                                   _chronometer.setText("0" + hour + ":" + minute + ":" + second);
                               }

                               // rt.setText(hour+":"+minute+":"+second);
                           }
                       });

                       // timer.cancel();
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }

           public void resetChronometer() {
             _chronometer.setText("00:00:00");
             second = 0;
             minute = 0;
             hour = 0;
    }

    }