Search This Blog

Monday, 26 March 2012

How to change size of fields and Managers..

Hello friends, Here is the simple one for you , how to change the width and height of any field in Blackberry development.... you just need to over ride the sublayout function for managers, and layout function for fields...
 Code :
 For Managers(HorizontalFieldManager):

public int getPreferredWidth(){
                return Display.getWidth();
            }
            public int getPreferredHeight(){
            return _speedB.getHeight()+5;
            }
            public void sublayout(int maxWidth,int maxHeight){
                super.sublayout(getPreferredWidth(), getPreferredHeight());
                setExtent(getPreferredWidth(),getPreferredHeight());
            }


 For Fields(RichTextField):


 RichTextField _vehicle = new RichTextField(ListOfVehicles._resultName.toUpperCase()){
 public int getPreferredWidth(){
 return 100;
 }
 public int getPreferredHeight(){
 return 50;
}
 public void layout(int maxWidth,int maxHeight){
 super.layout(getPreferredWidth(), getPreferredHeight()); setExtent(getPreferredWidth(),getPreferredHeight());
}

Sunday, 25 March 2012

How to use animation while switching from one screen to another

Hello friends, So nothing to explain,its just how to use animation in blackberry... what you need to do is use this code before pushing a screen... Code: TransitionContext transition = new TransitionContext(TransitionContext.TRANSITION_FADE); transition.setIntAttribute(TransitionContext.ATTR_DURATION,500); transition.setIntAttribute(TransitionContext.ATTR_DIRECTION,TransitionContext.DIRECTION_DOWN); transition.setIntAttribute(TransitionContext.ATTR_STYLE,TransitionContext.STYLE_PUSH); UiEngineInstance engine = Ui.getUiEngineInstance(); engine.setTransition(,,UiEngineInstance.TRIGGER_PUSH, transition); UiApplication.getUiApplication().popScreen(); UiApplication.getUiApplication().pushScreen();

Friday, 23 March 2012

How to convert Vector to array.....

Hello friends,
                        This seems not a big issue but sometimes we really need to use array instead of a vector.....sometimes perhaps, so here is the function i got from my anonymous friend ....i thank him very much for this .....

public static void copyVectorToArray(Vector src, Object[] _device2) {
       if(_device2.length != src.size() )
          throw new IllegalArgumentException("Target array length must be size of src vector");
       }
       Enumeration enum = src.elements();
       int count = 0;
       while(enum.hasMoreElements()) {
          Object element = enum.nextElement();
          _device2[count++] = element;
        }
        }

just try this one......

Thursday, 22 March 2012

How to display a welcome screen on application startup

Hello friends,
                              So ,yesterday what i was trying is to give my application some professional look by displaying a screen with application logo and a little bit photoshop work kind of you know like some banner for some seconds,this gives the application nice look....so here it is how can you display a screen with an image or anything for some seconds and then it automatically pops up and the mainScreen of app comes on display...

the first thing is to push the main screen of you app....like follows in a main thread.....basically its a MyApp.java file in blackberry there we push the screen which we want to display on app startup.So here below i aam pushing my main screen in stack...

public MyApp(){

pushScreen(<MainScreen of my app>);
 //Now push the screen which you want to display for some seconds.
pushScreen(<my Welcome screen>);
//Now i am using a function to pop this welcome screen.
kill(<my welcome Screen>);
}

Now what u need to do is to copy this below function in your app.

 public void kill(final Screen screen) {
        Timer _timer = new Timer();
        TimerTask _timerTask = new TimerTask(){
            public void run() {
                getUiApplication().invokeAndWait(closeScreen);       
            }
        };
        _timer.schedule(_timerTask, 4000);
    }   
Runnable closeScreen = new Runnable(){
    public void run(){
        closeScr();
    }
};
public void closeScr(){
    UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());


}
Copy this whole code in your same java file and its done you can change the seconds you want to display your welcome screen by editing the timerschedule,like here i am displaying it for 4 seconds.

Ask for any queries.....

Wednesday, 21 March 2012

How to implement a News strip text field in your app

Hello friends,
                      So another issue for today , how to implement a text field that will scroll horizontally like a news strip in your blackberry app? here it is copy this code and make a class with the name of this class...and use it as other fields in blackberry you will get the arguments detail from the construstor....

package mypackage;

import java.util.Timer;
import java.util.TimerTask;

import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;

class MarqueLabel extends LabelField {
    int currentChar = 0;
    String currentText = null;
    Font ourFont;
    private Timer _scrollTimer;
    private TimerTask _scrollTimerTask;
    public MarqueLabel(String text, long style) {
        super(text, style);    
    }
    public void paint(Graphics graphics) {
        currentText = this.getText();
        if (currentChar < currentText.length()) {
            currentText = currentText.substring(currentChar);
        }
        graphics.drawText(currentText, 0, 0, DrawStyle.ELLIPSIS, Display.getWidth());
        super.paint(graphics);
    }
    public void layout(int width, int height) {
        ourFont = this.getFont();
        setExtent(500, ourFont.getHeight());
    }
    protected void onDisplay() {
        startScroll();
    }
    protected void onUnfocus() {
        startScroll();
    }
    private void startScroll() {
        // Start scrolling
        final String fullText = this.getText();
        if (_scrollTimer == null) {
            _scrollTimer = new Timer();
            _scrollTimerTask = new TimerTask() {
                public void run() {
                    currentChar = currentChar + 2;
                    if (currentChar > fullText.length()) {
                        currentChar = 0;
                    }
                    invalidate();
                }
            };
            _scrollTimer.scheduleAtFixedRate(_scrollTimerTask, 0, 450);
        }
    }
    protected void onFocus(int direction) {
        if (_scrollTimer != null) {
            _scrollTimerTask.cancel();
            _scrollTimer.cancel();
            _scrollTimer = null;
            _scrollTimerTask = null;
        }
    }
    protected boolean navigationMovement(int dx, int dy,
        int status, int time) {
        currentText = this.getText();
        int oldCurrentChar = currentChar;
        if (Math.abs(dx) > Math.abs(dy)) {
            if (dx > 0) {
                currentChar = Math.min(currentText.length() - 1,
                        currentChar + 1);
            } else if (dx < 0) {
                currentChar = Math.max(0, currentChar - 1);
            }
            if (oldCurrentChar != currentChar) {
                this.invalidate();
            }
            return true;
        } else {
            return super.navigationMovement(dx, dy, status, time);
        }
    }
    }



Use it as many times as you want and can change the speed by editing the timer in this class....ask for any queries....

Tuesday, 20 March 2012

How to resize an image programmatically in blackberry.

Hello friends,
                  so there is another issue i faced in my last app,as we know blackberry handsets have different screen size with different resolution,so how can we make our app automatically detect the size and re size our screen???...here is what i used....you can make it a function and call this every time or you just use it directly...                                                                        

CODE :

    int oolddWidth;
    int oolddHeight;
    int ddispplayWidth;
    int ddispplayHeight;
    EncodedImage eih1 = EncodedImage.getEncodedImageResource("add2.png");
    oolddWidth = eih1.getWidth();
    oolddHeight = eih1.getHeight();
    ddispplayWidth = Display.getWidth()-40;//Declare the width you want for the image
    ddispplayHeight = 80;//Declare the height you want...
        int nnumeerator = net.rim.device.api.math.Fixed32.toFP(oolddWidth);
        int ddenoominator = net.rim.device.api.math.Fixed32.toFP(ddispplayWidth);
        int wwidtthScale = net.rim.device.api.math.Fixed32.div(nnumeerator, ddenoominator);
        nnumeerator = net.rim.device.api.math.Fixed32.toFP(oolddHeight);
        ddenoominator = net.rim.device.api.math.Fixed32.toFP(ddispplayHeight);
        int hheighhtScale = net.rim.device.api.math.Fixed32.div(nnumeerator, ddenoominator);
        EncodedImage newEih1 = eih1.scaleImage32(wwidtthScale, hheighhtScale);
        final Bitmap header1 = newEih1.getBitmap();//Bitmap header1 will give you a resized image..

The best part is no matter what the size of the image and resolution this will resize it to the width and height you want...hope it will be helpful for you people

Monday, 19 March 2012

How to implement a volume slider in Blackberry

here is the function to implement the volume slider in your app , what you need is to make a class with the name "SliderField" and copy this function in it....you can use your own images for the slider as i did in my apps....and the constructor will give you the arguments you need to pass to this field....can be initialized as we initialize other fields in Blackberry...

package mypackage;

import java.lang.Math;

import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;

public class SliderField extends Field
{
    Bitmap _imageThumb;
   
    Bitmap _imageSlider;
    Bitmap _imageSliderLeft;
    Bitmap _imageSliderCenter;
    Bitmap _imageSliderRight;
   
    Bitmap _imageSliderFocus;
    Bitmap _imageSliderFocusLeft;
    Bitmap _imageSliderFocusCenter;
    Bitmap _imageSliderFocusRight;

    private int _numStates;
    private int _currentState;
    private boolean _selected;

    private int _xLeftBackMargin;
    private int _xRightBackMargin;
   
    private int _thumbWidth;
    private int _thumbHeight;
       
    private int _totalHeight;
    private int _totalWidth;
   
    private int _rop;

    private int _backgroundColours[];
    private int _backgroundSelectedColours[];

    private int _defaultSelectColour = 0x977DED;
    private int _defaultBackgroundColour = 0x009ACD32;
    private int _defaultHoverColour = 0x999999;
   
 
    public SliderField( Bitmap thumb
                , Bitmap sliderBackground
                , int numStates
                , int initialState
                , int xLeftBackMargin
                , int xRightBackMargin )
    {
        this( thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
    }
   
    public SliderField( Bitmap thumb
                , Bitmap sliderBackground
                , int numStates
                , int initialState
                , int xLeftBackMargin
                , int xRightBackMargin
                , long style )
    { 
        this( thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, style );
    }
   
    public SliderField( Bitmap thumb
                , Bitmap sliderBackground
                , Bitmap sliderBackgroundFocus
                , int numStates
                , int initialState
                , int xLeftBackMargin
                , int xRightBackMargin )
    {
        this( thumb, sliderBackground, sliderBackgroundFocus, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
    }
   
    public SliderField( Bitmap thumb
                , Bitmap sliderBackground
                , Bitmap sliderBackgroundFocus
                , int numStates
                , int initialState
                , int xLeftBackMargin
                , int xRightBackMargin
                , long style )
    {
        super( style );

        if( initialState > numStates || numStates < 2 ){
        }
        _imageThumb = thumb;
        _imageSlider = sliderBackground;
        _imageSliderFocus = sliderBackgroundFocus;
        _numStates = numStates;
        setState( initialState );

        _xLeftBackMargin = xLeftBackMargin;
        _xRightBackMargin = xRightBackMargin;

        _rop = _imageSlider.hasAlpha() ? Graphics.ROP_SRC_ALPHA : Graphics.ROP_SRC_COPY;

        _thumbWidth = thumb.getWidth();
        _thumbHeight = thumb.getHeight();
        initBitmaps();
    }             
    public SliderField( Bitmap thumb
                , Bitmap sliderBackground
                , int numStates
                , int initialState
                , int xLeftBackMargin
                , int xRightBackMargin
                , int[] colours
                , int[] selectColours )
    {
        this(thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );

        if( colours.length != numStates+1 ){
            throw new IllegalArgumentException();
        }
        _backgroundColours = colours;
        _backgroundSelectedColours = selectColours;
    }
    public void initBitmaps()
    {
        int height = _imageSlider.getHeight();

        _imageSliderLeft = new Bitmap( _xLeftBackMargin, height );
        _imageSliderCenter = new Bitmap( _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height);
        _imageSliderRight = new Bitmap( _xRightBackMargin, height );

        copy( _imageSlider, 0, 0, _xLeftBackMargin, height, _imageSliderLeft );
        copy( _imageSlider, _xLeftBackMargin, 0, _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height, _imageSliderCenter);
        copy( _imageSlider, _imageSlider.getWidth() - _xRightBackMargin, 0, _xRightBackMargin, height, _imageSliderRight);
       
        _imageSliderFocusLeft = new Bitmap( _xLeftBackMargin, height );
        _imageSliderFocusCenter = new Bitmap( _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height);
        _imageSliderFocusRight = new Bitmap( _xRightBackMargin, height );
       
        copy( _imageSliderFocus, 0, 0, _xLeftBackMargin, height, _imageSliderFocusLeft );
        copy( _imageSliderFocus, _xLeftBackMargin, 0, _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height, _imageSliderFocusCenter);
        copy( _imageSliderFocus, _imageSlider.getWidth() - _xRightBackMargin, 0, _xRightBackMargin, height, _imageSliderFocusRight);
    }
    private void copy(Bitmap src, int x, int y, int width, int height, Bitmap dest) {
        int[] argbData = new int[width * height];
        src.getARGB(argbData, 0, width, x, y, width, height);
        for(int tx = 0; tx < dest.getWidth(); tx += width) {
            for(int ty = 0; ty < dest.getHeight(); ty += height) {
                dest.setARGB(argbData, 0, width, tx, ty, width, height);
            }
        }
    }
    public void setState(int newState) {
        if( newState > _numStates ){
            throw new IllegalArgumentException();
        } else {
            _currentState = newState;
            invalidate();
        }
    }
    public int getState() {
        return _currentState;
    }
    public int getNumStates() {
        return _numStates;
    }
    public int getColour() {
        if(_backgroundSelectedColours != null) {
            return _backgroundSelectedColours[getState()];
        }
        return 0x000000;
    }
   
    public int getPreferredWidth() {
        return _totalWidth;
    }

    public int getPreferredHeight() {
        return _totalHeight;
    }
    protected void layout( int width, int height ) {
        if (width < 0 || height < 0)
            throw new IllegalArgumentException();
        _totalWidth = width;
        _totalHeight = Math.max(_imageSlider.getHeight(), _imageThumb.getHeight());
       
        setExtent( _totalWidth, _totalHeight );
    }

    public void paint( Graphics g )
    {
        int sliderHeight = _imageSlider.getHeight();
        int sliderBackYOffset = ( _totalHeight - sliderHeight ) >> 1;
        int backgroundColor = _defaultBackgroundColour;
        if( _backgroundSelectedColours != null || _backgroundColours != null ) {
           
            if( _selected ) {
                backgroundColor = _backgroundSelectedColours != null ? _backgroundSelectedColours[getState()] : _defaultSelectColour;
            } else if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {
                backgroundColor = _backgroundColours != null ? _backgroundColours[getState()] : _defaultHoverColour;
            } else {
                backgroundColor = _defaultBackgroundColour;
            }
        }
        g.setColor( backgroundColor );
        g.fillRect( 1, sliderBackYOffset + 1, _totalWidth - 2, sliderHeight - 2 );
   
        if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {   
            paintSliderBackground( g, _imageSliderFocusLeft, _imageSliderFocusCenter, _imageSliderFocusRight );
        } else {
            paintSliderBackground( g, _imageSliderLeft, _imageSliderCenter, _imageSliderRight );
        }
        int thumbXOffset = ( ( _totalWidth - _thumbWidth ) * _currentState ) / _numStates;
        g.drawBitmap( thumbXOffset, ( _totalHeight - _thumbHeight ) >> 1, _thumbWidth, _thumbHeight, _imageThumb, 0, 0 );
    }

    private void paintSliderBackground( Graphics g, Bitmap left, Bitmap middle, Bitmap right )
    {
        int sliderHeight = _imageSlider.getHeight();
        int sliderBackYOffset = ( _totalHeight - sliderHeight ) >> 1;
        g.drawBitmap( 0, sliderBackYOffset, _xLeftBackMargin, sliderHeight, left, 0, 0 );
        g.tileRop( _rop, _xRightBackMargin, sliderBackYOffset, _totalWidth - _xLeftBackMargin - _xRightBackMargin, sliderHeight, middle, 0, 0 );
        g.drawBitmap( _totalWidth - _xRightBackMargin, sliderBackYOffset, _xRightBackMargin, sliderHeight, right, 0, 0 );
    }

    public void paintBackground( Graphics g )
    {
    }

    protected void drawFocus( Graphics g, boolean on )
    {
        boolean oldDrawStyleFocus = g.isDrawingStyleSet( Graphics.DRAWSTYLE_FOCUS );
        try {
            if( on ) {
                g.setDrawingStyle( Graphics.DRAWSTYLE_FOCUS, true );
            }
            paint( g );
        } finally {
            g.setDrawingStyle( Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus );
        }
    }
    protected boolean touchEvent(TouchEvent message)
    {
        boolean isConsumed = false;
        boolean isOutOfBounds = false;
        int x = message.getX(1);
        int y = message.getY(1);
        if(x < 0 || y < 0 || x > getExtent().width || y > getExtent().height) {
            isOutOfBounds = true;
        }
        switch(message.getEvent()) {
            case TouchEvent.CLICK:
            case TouchEvent.MOVE:
                if(isOutOfBounds) return true;
                _selected = true;
               
                int stateWidth = getExtent().width / _numStates;
                int numerator = x / stateWidth;
                int denominator = x % stateWidth;
                if( denominator > stateWidth / 2 ) {
                    numerator++;
                }
                _currentState = numerator;
                invalidate();
               
                isConsumed = true;
                break;
            case TouchEvent.UNCLICK:
                if(isOutOfBounds) {
                    _selected = false;
                    return true;
                }
                _selected = false;
                stateWidth = getExtent().width / _numStates;
                numerator = x / stateWidth;
                denominator = x % stateWidth;
                if( denominator > stateWidth / 2 ) {
                    numerator++;
                }
                _currentState = numerator;
                invalidate();
                fieldChangeNotify(0);
                isConsumed = true;
                break;
        }
        return isConsumed;
    }
    protected boolean navigationMovement(int dx, int dy, int status, int time)
    {
        if( _selected )
        {
            if(dx > 0 || dy > 0) {
                incrementState();
                fieldChangeNotify( 0 );
                return true;
            } else if(dx < 0 || dy < 0) {
                decrementState();
                fieldChangeNotify( 0 );
                return true;
            }
        }
        return super.navigationMovement( dx, dy, status, time);
    }
    public void decrementState() {
        if(_currentState > 0) {
            _currentState--;
            invalidate();
        }
    }
    public void incrementState() {
        if(_currentState < _numStates) {
            _currentState++;
            invalidate();
        }
    }
    protected boolean invokeAction(int action) {
        switch(action) {
            case ACTION_INVOKE: {
                toggleSelected();
                return true;
            }
        }
        return false;
    }
    protected boolean keyChar( char key, int status, int time ) {
        if( key == Characters.SPACE || key == Characters.ENTER ) {
            toggleSelected();
            return true;
        }

        return false;
    }
    protected boolean trackwheelClick( int status, int time ) {
        if( isEditable() ) {
            toggleSelected();
            return true;
        }
        return super.trackwheelClick(status, time);
    }
    private void toggleSelected() {
        _selected = !_selected;
        invalidate();
    }
    public void setDirty( boolean dirty )
    { 
    }
    public void setMuddy( boolean muddy )
    {
    }
}

You can get the volume control of the player as you may know....and then just as we do with buttons...set a change listener for this SliderField and you can set the volume by using getState() function of this sliderField and setting it to the setLevel() of volumeControl of the player's.

Comment for any queries.....

How to add multiple markers on MapField.


As far as i faced this issue and messed up my whole app while trying to draw the markers on map,which should be clickable i somehow solved it....So here i am giving you this tip-off.

The theory says, that whenever a screen changes the paint method is recalled ,like if we move the map or we can say pan technically...the thing which happens is that the paint method of MapField is recalled....so here is the code you need to follow to draw multiple markers on MapField in Blackberry

public void paint(Graphics g){
                  
                super.paint(g);
               
                 for(int i=0;i<=_deviceId.size()-1;i++){
                 
                Coordinates coords = getCoordinates();
                coords.setLatitude(Double.parseDouble((String) _latitude.elementAt(i)));
                coords.setLongitude(Double.parseDouble((String) _longitude.elementAt(i)));
               
               
                convertWorldToField(coords,_xypoint);
             
               x1[i] = _xypoint.x;
               y1[i] = _xypoint.y;
               if(_accStatus.elementAt(i).equals("0")){
                   g.drawText((String)_name.elementAt(i),_xypoint.x,_xypoint.y-10);
                   g.drawBitmap(_xypoint.x,_xypoint.y,_loc.getWidth(),_loc.getHeight(),_loc, 0, 0);
               }else{
                   g.drawText((String)_name.elementAt(i),_xypoint.x,_xypoint.y-10);
                   g.drawBitmap(_xypoint.x,_xypoint.y,_locOn.getWidth(),_locOn.getHeight(),_locOn, 0, 0);
               }
               } }
               };
         What i am doing here is i started a for loop , which will run for the no. of devices i have in "_deviceId" Vector.Then i am setting the latitude and longitude of Coordinates object"coords",here you have seen that when i am initializing it i set it to "getCoordinates()" this will get the coordinates of MapField we are using.after this i am converting the latitude and longitude which i got from server and i saved in Vectors "_latitude" and "_longitude" to the display coordinates i.e (xy Coordinates),after that it is simple , i am drawing an icon on that xyCoordinates which i get after conversion,so this will draw all the markers as all it is done in for loop.Don't confuse urself that what will happen if the xyCoordinates you will get is out of drawable area .....put it in try and catch ,everytime you pan the MapField this paint function will b called and whole of the process run,so there is no issue that on panning the map your markers will stay where they are they will also move to their original place......comment for any queries...

Welcome ...

Hello my developer fellas,its me Himanshu,a Blackberry developer from india , and developed many apps for blackberry now ready to share some of the issues and there solutions with you all....Hope you enjoy it