Wednesday, January 23, 2013

Custom Radio Button


We can make a custom radio button with picture images and other drawing  methods. please have a look on the code and improve accordingly!!



package customradio;

import net.rim.device.api.ui.component.RadioButtonField;
import net.rim.device.api.ui.component.RadioButtonGroup;

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;

/**
 *
 */
public class CustomRadioButton extends RadioButtonField {

private String label;
private Bitmap _currentPicture;
private Bitmap _onPicture; // image for "in focus"
private Bitmap _offPicture; // image for "not in focus"
private int width;
private int height;

// Constructor
public CustomRadioButton(String offImage, String onImage, String label,
RadioButtonGroup group, boolean selected) {

super(label, group, selected);
this.label = label;
_offPicture = Bitmap.getBitmapResource(offImage);
_onPicture = Bitmap.getBitmapResource(onImage);
_currentPicture = _offPicture;

} // end of constructor

public CustomRadioButton(String label) {

this.label = label;

}

/**
* The getPreferredHeight() and getPreferredWidth() methods return 45 since
* the images for custom buttons are 45 x 45 pixel
*
* @return <description>
*/
public int getPreferredHeight() {

/**
* If image not null then set height is equal to image height plus
* label. getFont().getHeight() + 8 shows that left 8 pixels from top
* and bottom of image so label not stick with image
*/
if (_currentPicture != null) {

return Math.max(getFont().getHeight(), _currentPicture.getHeight());

} else {

return getFont().getHeight() + 8;

}

} // end of getPreferredHeight()

public int getPreferredWidth() {

int width = Display.getWidth();
return width;

} // end of getPreferredWidth()

protected void layout(int width, int height) {

super.layout(getPreferredWidth(), getPreferredHeight());

setExtent(getPreferredWidth(), Math.min(height, getPreferredHeight())+20);

} // end of layout()

/**
* These functions set the currentPicture variable to the correct image when
* the user rolls over the button using the paint() method. The image is
* redrawn after the change by calling the invalidate() method.
*
*/
protected void onFocus(int direction) {

super.onFocus(direction);
_currentPicture = _onPicture;
invalidate();

}

protected void onUnfocus() {

super.onUnfocus();
_currentPicture = _offPicture;
invalidate();

}

protected void paint(Graphics graphics) {

/**
* If the Bitmap is taller than the font, we want the text centerd
* vertically. Similarly, if the font is taller, we want the bitmap
* centered vertically. The algorithm in both cases is the same position
* = (Field height - item height) / 2;
*/
int textY = (getHeight() - getFont().getHeight()) / 2;

if (_currentPicture != null) {

int imageY = (getHeight() - _currentPicture.getHeight()) / 2;

if (_currentPicture == _onPicture) {

graphics.setColor(Color.GREEN);

}

if (isSelected()) {

graphics.setColor(Color.RED);
graphics.drawRoundRect(2, 2, getWidth() - 4, getHeight() - 2,
15, 15);
// graphics.drawRect(5, getHeight() / 4, 20, 20);
graphics.drawArc(5, getHeight() / 4, 20, 20, 0, 360);
graphics.fillArc(5 + 2, (getHeight() / 4) + 2, 16, 16, 0, 360);
graphics.drawBitmap(24, imageY, _currentPicture.getWidth(),
_currentPicture.getHeight(), _currentPicture, 0, 0);
graphics.drawText(label, 65, textY);

} else { // end of if (isSelected())

graphics.drawRoundRect(2, 2, getWidth() - 4, getHeight() - 2,
15, 15);
// graphics.drawRect(5, getHeight() / 4, 20, 20);
graphics.drawArc(5, getHeight() / 4, 20, 20, 0, 360);
graphics.drawBitmap(24, imageY, _currentPicture.getWidth(),
_currentPicture.getHeight(), _currentPicture, 0, 0);
graphics.drawText(label, 65, textY);

} // end of if / else (isSelected())

} else { // end of if (_currentPicture != null)

if (isFocus()) {

graphics.setColor(Color.GREEN);

} // end of if (isFocus())

if (isSelected()) {

graphics.setColor(Color.RED);
graphics.drawRoundRect(2, 2, getWidth() - 4, getHeight() - 2,
15, 15);
graphics.drawArc(5, getHeight() / 4, 16, 16, 0, 360);
graphics.fillArc(5 + 2, (getHeight() / 4) + 2, 12, 12, 0, 360);
graphics.drawText(label, 24, textY);

} else {

graphics.drawRoundRect(2, 2, getWidth() - 4, getHeight() - 2,
15, 15);
graphics.drawArc(5, getHeight() / 4, 16, 16, 0, 360);
graphics.drawText(label, 24, textY);

}

} // end of if / else (_currentPicture != null)

} // end of paint()

/**
* We'll disable the default focus so that the blue rectangle isn't drawn.
* To do this, we just override drawFocus() and have it to do nothing
*/
protected void drawFocus(Graphics graphics, boolean on) {

} // end of drawFocus()

} // end of class BasitCustomRadioButton


and we can use it with the following code


package customradio;

import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;

public class RadiScreen extends MainScreen {
public RadiScreen() {
setTitle("Radio Button Demo");
RadioButtonGroup rbg = new RadioButtonGroup();
add(new CustomRadioButton("on.png","off.png","Option 1", rbg, true));
add(new CustomRadioButton("on.png","off.png","Option 2", rbg, false));
}
}


BlackBerry Create the Custom Button


private class MyCustomButton extends Field implements DrawStyle{
   
  private Bitmap _currentPicture;
     private Bitmap _onPicture; //image for "in focus"
     private Bitmap _offPicture; //image for "not in focus"
     private int width;
     private int height;
     
     //Ctor: pass path to on/off images you're using.
     MyCustomButton (String onImage, String offImage){
      super();
      _offPicture = Bitmap.getBitmapResource(offImage);
      _onPicture = Bitmap.getBitmapResource(onImage);
      _currentPicture = _offPicture;
           
     }
     
     public int getPreferredHeight(){      
      return 80;
     }
     
     public int getPreferredWidth(){
      return 80;
     }
     
 
     public boolean isFocusable(){
      return true;
     }
     
     //Override function to switch picture
     protected void onFocus(int direction){
      _currentPicture = _onPicture;
      invalidate();
     }
     //Override function to switch picture
     protected void onUnfocus(){
      _currentPicture = _offPicture;
      invalidate();
     }
     
  protected void layout(int width, int height) {
    setExtent(Math.min( width, getPreferredWidth()), Math.min( height, getPreferredHeight()));
  }
   
  //update the fieldchange
  protected void fieldChangeNotify(int context) {
      try {
       this.getChangeListener().fieldChanged(this, context);
      } catch (Exception exception) {
      }
  }
   
  //Since button is rounded we need to fill corners with dark color to match
  protected void paint(Graphics graphics) {  
   graphics.setColor(Color.BLACK);  
         graphics.fillRect(0, 0, getWidth(), getHeight());
         graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
  }
 
  //Listen for navigation Click
  protected boolean navigationClick(int status, int time){
   fieldChangeNotify(1);
   return true;
  }
 
 }
 
 
 }

BlackBerry custombutton-field-3

BlackBerry custombutton-field-3
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;

public class CustomButtonField extends Field
{

    private int backgroundColour = Color.GRAY;
    private int highlightColour;
    private int fieldWidth;
    private int fieldHeight;
    private String text;
    private int padding = 8;

    public CustomButtonField(String text, int highlightColour)
    {
        super(Field.FOCUSABLE);
        this.text = text;
        this.highlightColour = highlightColour;
        Font defaultFont = Font.getDefault();
        fieldHeight = defaultFont.getHeight() + padding;
        fieldWidth = defaultFont.getAdvance(text) + (padding * 2);
        this.setPadding(2, 2, 2, 2);
    }

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

    protected void onFocus(int direction)
    {
        backgroundColour = highlightColour;
        invalidate();
    }

    protected void onUnfocus()
    {
        backgroundColour = Color.GRAY;
        invalidate();
    }

    public int getPreferredWidth()
    {
        return fieldWidth;
    }

    public int getPreferredHeight()
    {
        return fieldHeight;
    }

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

    protected void drawFocus(Graphics graphics, boolean on)
    {

    }

    protected void fieldChangeNotify(int context)
    {
        try
        {
            this.getChangeListener().fieldChanged(this, context);
        }
        catch (Exception e)
        {}
    }

    protected void paint(Graphics graphics)
    {
        graphics.setColor(backgroundColour);
        graphics.fillRoundRect(0, 0, fieldWidth, fieldHeight, 8, 8);
        graphics.setColor(Color.GRAY);
        graphics.drawRoundRect(0, 0, fieldWidth, fieldHeight, 8, 8);
        graphics.setColor(Color.WHITE);
        graphics.drawText(text, padding - 1, padding / 2 + 1);
    }
}

BlackBerry custom button field -2


final class CustomButtonField extends Field {

 private int backgroundColor = Color.LIGHTGREY;
 private int backgroundBorder = Color.LIGHTGREY;
 private int textColor=Color.CORNFLOWERBLUE;
 // Focus color of the button
 private int color;
 // Field width and height are calculated
 private int fieldWidth;
 private int fieldHeight;
 // Text to be displayed in the button
 private String text;
 private int padding = 15;
 private int arc = 20;
 //width - ratio of screen width
 public static final int SCREEN_WIDTH=1;
 public  static  final int ONE_THIRD_SCREEN_WIDTH=2;
 public  static final int TWO_THIRD_SCREEN_WIDTH=3;
 public  static  final int THREE_FOURTH_SCREEN_WIDTH=4;
 public  static  final int HALF_SCREEN_WIDTH=5;

public CustomButtonField(String label, int color) {
 super(Field.FOCUSABLE | Field.FIELD_HCENTER);
 // Text on the button
 text = label;
 this.color = color;
 Font defaultFont = Font.getDefault();

// Height and width of the field
 fieldHeight = defaultFont.getHeight() + padding;
 fieldWidth = defaultFont.getAdvance(text) + (padding * 2);
 this.setPadding(2, 2, 2, 2);
 }
 public CustomButtonField(String label, int color, long style)
 {
 super(Field.FOCUSABLE | style);
 // Text on the button
 text = label;
 this.color = color;
 Font defaultFont = Font.getDefault();

// Height and width of the field
 fieldHeight = defaultFont.getHeight() + padding;
 fieldWidth = defaultFont.getAdvance(text) + (padding * 2);
 this.setPadding(2, 2, 2, 2);
 }
 //newly added
 public CustomButtonField(String label, int color,int maxWidthScreenRatio)
 {
 super(Field.FOCUSABLE | Field.FIELD_HCENTER);
 // Text on the button
 text = label;
 this.color = color;
 Font defaultFont = Font.getDefault();
 this.setPadding(2, 2, 2, 2);
 // Height and width of the field
 fieldHeight = defaultFont.getHeight() + padding;
 //fieldWidth = defaultFont.getAdvance(text) + (padding * 2);
 switch(maxWidthScreenRatio)
 {
 case SCREEN_WIDTH:
 //left-right margin
 fieldWidth = Display.getWidth()-10*2;
 break;
 case ONE_THIRD_SCREEN_WIDTH:
 //fieldWidth = ((Graphics.getScreenWidth() * 1) / 3)+ (padding * 2);
 fieldWidth = ((Display.getWidth() * 1) / 3)+ (padding * 2);
 break;
 case TWO_THIRD_SCREEN_WIDTH:
 //fieldWidth = ((Graphics.getScreenWidth() * 2) / 3)+ (padding * 2);
 fieldWidth = ((Display.getWidth() * 2) / 3)+ (padding * 2);
 break;
 case THREE_FOURTH_SCREEN_WIDTH:
 fieldWidth = ((Display.getWidth() * 3) / 4) + (padding * 2);
 break;
 case HALF_SCREEN_WIDTH:
 //fieldWidth = (Graphics.getScreenWidth()  / 2) - (padding * 2);
 fieldWidth = (Display.getWidth()  / 2) - (padding * 2);
 break;
 default:
 fieldWidth = defaultFont.getAdvance(text) + (padding * 2);
 }

}
 protected void onFocus(int direction) {
 // Color set
 backgroundColor = color;
 textColor = Color.WHITE;
 invalidate();
 super.onFocus(direction);
 }

protected void onUnfocus() {
 // Color set to dim gray
 backgroundColor = Color.LIGHTGREY;
 textColor = Color.CORNFLOWERBLUE;
 invalidate();
 super.onUnfocus();
 }

protected boolean navigationClick(int status, int time) {
 // Field change notify
 fieldChangeNotify(1);
 return false;
 }

public int getPreferredWidth() {
 return fieldWidth;
 }

public int getPreferredHeight()
 {
 return fieldHeight;
 }

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

protected void drawFocus(Graphics graphics, boolean on) {
 }

protected void fieldChangeNotify(int context) {
 try
 {
 // Alert the change listener
 this.getChangeListener().fieldChanged(this, context);
 }
 catch (Exception e)
 {
 System.out.println("CustomButton.fieldChangeNotify():ex - "+ e.getMessage());
 }
 }

protected void paint(Graphics graphics) {
 graphics.setColor(backgroundBorder);
 // Fill a white rectangle
 graphics.fillRoundRect(0, 0, fieldWidth, fieldHeight, arc, arc);
 // Draw a white rectangle - (this will give a white ring like effect)
 graphics.drawRoundRect(0, 0, fieldWidth, fieldHeight, arc, arc);
 graphics.setColor(backgroundColor);
 // Fill with the background color
 graphics.fillRoundRect(1, 1, fieldWidth-2, fieldHeight-2, arc, arc);
 //
 graphics.setColor(textColor);
 graphics.setFont(graphics.getFont().derive(Font.BOLD));
 //graphics.drawText(text, padding - 1, padding / 2 - 1);
 int x = (fieldWidth/2)-(graphics.getFont().getAdvance(text)/2);
 graphics.drawText(text, x , padding/2-1);
 }
 }//end of class

Blackberry create a Custom Button Field -1




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

public class CustomButtonField extends Field
{
    Bitmap Unfocus_img, Focus_img, current_pic;
    int width;
    String text;
    Font font;  
    CustomButtonField(int width, String text, Bitmap onFocus, Bitmap onUnfocus, long style)
    {
        super(style);
        Unfocus_img = onUnfocus;
        Focus_img = onFocus;
        current_pic = onFocus;
        this.text = text;
        this.width = width;
    }
    protected void layout(int width, int height)
    {
        setExtent(current_pic.getWidth(), current_pic.getHeight());      
    }
    protected void paint(Graphics graphics)
    {
        try
        {
                FontFamily fntFamily = FontFamily.forName("BBAlpha Sans");
                font = fntFamily.getFont(Font.BOLD,14);            
        }
        catch(Exception e)
        {
            font = Font.getDefault();
       
        }
        graphics.setFont(font);
        graphics.setColor(Color.WHITE);
        graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic, 0, 0);
        graphics.drawText(text, width, 7);
    }
    protected void onFocus(int direction)
    {
        super.onFocus(direction);
        current_pic = Unfocus_img;
        this.invalidate();
    }
  protected void drawFocus(Graphics graphics, boolean on)
  {
     
    }
    protected void onUnfocus()
    {
        super.onUnfocus();
        current_pic = Focus_img;
        invalidate();
    }
    public boolean isFocusable() {
        return true;
    }
    protected boolean navigationClick(int status, int time) {
        fieldChangeNotify(0);
        return true;
    }
}


And the  use of the given above code is as follows:


Bitmap focus = Bitmap.getBitmapResource("printButton_focus.png");
Bitmap unfocus = Bitmap.getBitmapResource("printButton_unfocus.png");
         
Bitmap focus1 = Bitmap.getBitmapResource("button-highlight.png");Bitmap unfocus1 = Bitmap.getBitmapResource("button.png");
         
 ButtonField obj = new ButtonField("Button");
 CustomButtonField button1 = new CustomButtonField(0,"",unfocus,focus,Field.FOCUSABLE);
 CustomButtonField button2 = new CustomButtonField(25,"Next",unfocus1,focus1,Field.FOCUSABLE);
         
 add(obj);
 add(new RichTextField(Field.NON_FOCUSABLE));
 add(button1);
 add(new RichTextField(Field.NON_FOCUSABLE));
 add(button2);

Monday, January 21, 2013

BlackBerry Blurr a given image


package mypackage;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Graphics;

public class ImageTools
{
    // Variables and Fields
    private static int _radius;
    private static int _kernelSize;
    private static int[] _kernel;
    private static int[][] _productTable;

 
    public static void buildKernel(int radius){
        // Determine if Radius Selected is Valid (Values 64, 128, and 256 are Valid Maxima Values for Radius)
        radius = Math.min(64, Math.max(1, radius));
       
        // Initialize Global Variables
        _radius = radius;
        _kernelSize = 1 + 2*radius;    // This is the range for Pixel Selection
        _kernel= new int[_kernelSize]; // This is a Gaussian Distribution Dictionary
       
        // This is an added Optimization for Embedded Devices (Reduces CPU Stress)
        _productTable = new int[_kernelSize][256];

        // Augment Values of Gaussian Curve Excluding Radius Pixel
        for(int i=1; i<radius; i++){
            // Initialize Temp Variables
            int increment = radius - i;
           
            // Gaussian Curve is Symmetric
            _kernel[radius+i] = _kernel[increment] = increment*increment;
           
            // Produce Product Table for 'each' Pixel Color 0-255
            for(int j=0; j<256; j++)
                _productTable[radius+i][j] = _productTable[increment][j] = _kernel[increment]*j;
        }
       
        // Augment Values of Gaussian Curve for Radius Pixel
        _kernel[radius] = radius*radius;
        for(int j=0; j<256; j++)
            _productTable[radius][j] = _kernel[radius]*j;
    }


 
    public static Bitmap blur(Bitmap image, int left, int top, int width, int height, boolean isAlpha){
        // Determine Bitmap Properties
        int imgWidth = image.getWidth();
        int imgHeight = image.getHeight();
        int numPixels = width*height; // Only select the Region Size (Optimization)
       
        // Check Image if Alpha Channel Exists
        if(!image.hasAlpha() && isAlpha)
            isAlpha = false;
       
        // Determine Region to Blur on 'image'
        int topYAxis = 0;
        top = Math.min(imgHeight, Math.max(0, top));
        left = Math.min(imgWidth, Math.max(0, left));
        width = Math.min(imgWidth, Math.max(0, width));
        height = Math.min(imgHeight, Math.max(0, height));
       
        // Obtain Bitmap Pixels in ARGB from that Region
        int[] data = new int[numPixels];
        image.getARGB(data, 0, width, top, left, width, height); // Obtain pixel data from 'image' only the Region Specified
       
        // Separate Color Channels
        int a[] = new int[numPixels];
        int r[] = new int[numPixels];
        int g[] = new int[numPixels];
        int b[] = new int[numPixels];
        for(int i=0; i<numPixels; i++){
            // Initialize Temp Variables
            int pixel = data[i];
            if(isAlpha)
                a[i] = Math.abs((pixel&0xFF000000)>>24);
            r[i] = (pixel&0x00FF0000)>>16;
            g[i] = (pixel&0x0000FF00)>>8;
            b[i] = (pixel&0x000000FF);
        }

        // Clone Array(s) of Color Channels
        int a2[] = new int[numPixels];
        int r2[] = new int[numPixels];
        int g2[] = new int[numPixels];
        int b2[] = new int[numPixels];

        // Produce Clone of Bitmap with Horizontal Blurring
        for(int y=0; y<height; y++){
            for(int x=0; x<width; x++){
                // Initialize Temp Variables
                int alphaChannel=0, redChannel=0, greenChannel=0, blueChannel=0, summation=0;
                int pixel = x - _radius;

                // Collect RGB Data from the range [radius-x, radius+x]
                for(int i=0; i<_kernelSize; i++){
                    // Initialize Temp Variables
                    int tmpPixel = pixel + i;
                   
                    // Determine if Selected Pixel is within Boundary
                    if(tmpPixel >= 0 && tmpPixel < width){
                        // Collect RGB or Alpha Data over Radius
                        tmpPixel += topYAxis;
                        if(!isAlpha){
                            redChannel += _productTable[i][r[tmpPixel]];
                            greenChannel += _productTable[i][g[tmpPixel]];
                            blueChannel += _productTable[i][b[tmpPixel]];
                        }
                        else
                            if(a[tmpPixel] != 0)
                                alphaChannel += _productTable[i][255];

                        // Increase Color Average
                        summation += _kernel[i];
                    }
                }
                // Store Processed Data into Clone Array(s)
                if(isAlpha)
                    a2[x+topYAxis] = alphaChannel/summation;
                else{
                    r2[x+topYAxis] = redChannel/summation;
                    g2[x+topYAxis] = greenChannel/summation;
                    b2[x+topYAxis] = blueChannel/summation;
                }
            }  
            // Set New Data Position for Pixel Array
            topYAxis += width;
        }

        // Produce Clone of Bitmap with Vertical Blurring
        for(int x=0; x<width; x++){
            for(int y=0; y<height; y++){
                // Initialize Temp Variables
                int alphaChannel=0, redChannel=0, greenChannel=0, blueChannel=0, summation=0;
                int pixel = y - _radius;

                // Collect RGB Data from the range [radius-y, radius+y]
                for(int i=0; i<_kernelSize; i++){
                    // Initialize Temp Variables
                    int tmpPixel = (pixel + i)*width + x;
                   
                    // Determine if Selected Pixel is within Boundary
                    if(tmpPixel < numPixels && tmpPixel >= 0){
                        // Collect RGB or Alpha Data over Radius
                        if(!isAlpha){
                            redChannel += _productTable[i][r2[tmpPixel]];
                            greenChannel += _productTable[i][g2[tmpPixel]];
                            blueChannel += _productTable[i][b2[tmpPixel]];
                        }
                        else
                            if(a[tmpPixel] != 0)
                                alphaChannel += _productTable[i][a2[tmpPixel]];
                               
                        // Increase Color Average
                        summation += _kernel[i];
                    }
                }
                // Recombine Color Channels with Full Opacity
                if(isAlpha)
                    data[x+y*width] =  (alphaChannel/summation)<<24 | r[x+y*width]<<16 | g[x+y*width]<<8 | b[x+y*width];
                else
                    data[x+y*width] =  0xFF000000 | (redChannel/summation)<<16 | (greenChannel/summation)<<8 | (blueChannel/summation);
            }
        }
       
        // Replace 'image' Data with PreProcessed Data
        image.setARGB(data, 0, width, top, left, width, height);
        return image;
    }
}


the above given class can be used as follows

Bitmap _target = Bitmap.getBitmapResource("icon.png");
_target = ImageTools.blur(_target, 0, 0, 50, 50, true);

BitmapField bftemp111 = new BitmapField(_target,
BitmapField.NON_FOCUSABLE | BitmapField.FIELD_HCENTER
| BitmapField.FIELD_VCENTER);
add(bftemp111);

Monday, January 14, 2013

BlackBerry Waiting screen while Downloading Image from a web url

we can show a progress animation while there is a downloading process is going on. for this purpose  create a project with the name WaitScreen and a the main-screen  class with name StartScreen .java copy the below given code to it


package jitesh.waitscreen;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class StartScreen extends MainScreen implements FieldChangeListener {
private ButtonField button;
BitmapField fieldDemo;
WaitScreen msgs;

public StartScreen() {

HorizontalFieldManager hfm = new HorizontalFieldManager();

VerticalFieldManager vfm = new VerticalFieldManager();
button = new ButtonField("Go!", FIELD_HCENTER);
button.setChangeListener(this);
vfm.add(button);

hfm.add(vfm);

add(hfm);
Bitmap bitmapImage = Bitmap.getBitmapResource("icon.png");
fieldDemo = new BitmapField(bitmapImage);
add(fieldDemo);
}

public void getFile() {
msgs = new WaitScreen(this);
HttpConnector
.HttpGetStream(
"http://upload.wikimedia.org/wikipedia/en/9/92/Magnifier_Vista_Icon.png"+";deviceside=true",
msgs);
}

// you should implement this method to use callback data on the screen.
public void updateScreen(Bitmap bitmap) {
fieldDemo.setBitmap(bitmap);
}

public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (field == button) {
getFile();

}
}
}



make  WaitScreen.java for showing  progress animation while downloading image from web url.  copy the given below code to it


package jitesh.waitscreen;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.container.FullScreen;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;

public class WaitScreen extends FullScreen implements ResponseCallback {
StartScreen startScreen;

public WaitScreen(StartScreen startScreen) {
super(new VerticalFieldManager(), Field.NON_FOCUSABLE);
setBackground(BackgroundFactory.createSolidTransparentBackground(
Color.BLUE, 50));
this.startScreen = startScreen;
HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_HEIGHT);

VerticalFieldManager vfm = new VerticalFieldManager(USE_ALL_WIDTH | FIELD_VCENTER);

vfm.add(new ProgressAnimationField(
Bitmap.getBitmapResource("spinner2.png"), 6,
Field.FIELD_HCENTER));

hfm.add(vfm);

add(hfm);

UiApplication.getUiApplication().pushScreen(this);
}

public void callback(Bitmap bmpimage) {
startScreen.updateScreen(bmpimage);
UiApplication.getUiApplication().popScreen(this);
}


}

the spinner2.png can be downloaded from here


after this make HttpConnector.java with following code


package jitesh.waitscreen;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.UiApplication;

public class HttpConnector {
static HttpConnection httpConnection = null;
static DataOutputStream httpDataOutput = null;
static InputStream httpInput = null;
static int rc;

static Bitmap bitmp = null;
static public void HttpGetStream(final String fileToGet,
final ResponseCallback msgs) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
httpConnection = (HttpConnection) Connector.open(fileToGet);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
final EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {

msgs.callback(hai.getBitmap());
}
});;

} catch (Exception ex) {
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
Bitmap bitmapImage = Bitmap
.getBitmapResource("icon.png");

msgs.callback(bitmapImage);
}
});
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();

}
}



}
});
t.start();
}


}



the used interface is ResponseCallback.java with the code


package jitesh.waitscreen;

import net.rim.device.api.system.Bitmap;

public interface ResponseCallback {
    public void callback(Bitmap bmp);
}

again the important class ProgressAnimationField.java is as follows


package jitesh.waitscreen;

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


public class ProgressAnimationField extends Field implements Runnable
{
    private Bitmap _bitmap;
    private int _numFrames;
    private int _frameWidth;
    private int _frameHeight;
   
    private int _currentFrame;
    private int _timerID = -1;
   
    private Application _application;
    private boolean _visible;
         
    public ProgressAnimationField( Bitmap bitmap, int numFrames, long style )
    {
        super( style | Field.NON_FOCUSABLE );
        _bitmap = bitmap;
        _numFrames = numFrames;
        _frameWidth = _bitmap.getWidth() / _numFrames;
        _frameHeight = _bitmap.getHeight();
       
        _application = Application.getApplication();
    }
   
    public void run()
    {
        if( _visible ) {
            invalidate();
        }
    }
   
    protected void layout( int width, int height )
    {
        setExtent( _frameWidth, _frameHeight );
    }
   
    protected void paint( Graphics g )
    {
        g.drawBitmap( 0, 0, _frameWidth, _frameHeight, _bitmap, _frameWidth * _currentFrame, 0 );
        _currentFrame++;
        if( _currentFrame >= _numFrames ) {
            _currentFrame = 0;
        }
    }
   
    protected void onDisplay()
    {
        super.onDisplay();
        _visible = true;
        if( _timerID == -1 ) {
            _timerID = _application.invokeLater( this, 200, true );
        }
    }
   
    protected void onUndisplay()
    {
        super.onUndisplay();
        _visible = false;
        if( _timerID != -1 ) {
            _application.cancelInvokeLater( _timerID );
            _timerID = -1;
        }
    }
}

the output should look like this







Wednesday, January 9, 2013

BlackBerry Playing audio from a web URL

Make a new project with name AudioPlaybackDemoScreen and copy the following code to AudioPlaybackDemoScreen.java


package audioplaying;

import net.rim.device.api.command.Command;
import net.rim.device.api.command.CommandHandler;
import net.rim.device.api.command.ReadOnlyCommandMetadata;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;

import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.io.*;

public class AudioPlaybackDemoScreen extends MainScreen implements
FieldChangeListener

{
Player p;
ButtonField audio;
private VerticalFieldManager vfm = new VerticalFieldManager();

public AudioPlaybackDemoScreen() {
audio = new ButtonField("Strat");

add(audio);

ButtonField playButton = new ButtonField("Play",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
playButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Start the video
try {
p.start();
p.setLoopCount(-1);
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));
add(playButton);

ButtonField pauseButton = new ButtonField("Pause",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
pauseButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Pause the video
try {
if(p!=null){
p.stop();}else{Dialog.inform("Press start");}
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));
add(pauseButton);
ButtonField closeButton = new ButtonField("Stop",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
closeButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Pause the video
try {
if(p!=null){
p.stop();
p.close();}else{Dialog.inform("Press start");}
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));
add(closeButton);
audio.setChangeListener(this);

}

public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (audio == field) {

try {
p = javax.microedition.media.Manager
.createPlayer("http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3"
+ ";deviceside=true");
p.realize();
VolumeControl volume = (VolumeControl) p
.getControl("VolumeControl");
volume.setLevel(30);
p.setLoopCount(-1);
p.prefetch();
p.start();

} catch (MediaException me) {
Dialog.alert(me.toString());
} catch (IOException ioe) {
Dialog.alert(ioe.toString());
}
}
}
}

just run and use the buttons on the screens. :) enhance the code accordingly for yours need!!

BlackBerry playing video from a web url


We can play a videw from a web link/url in blackberry with the help of MMAPI'S of J2ME. please have a mainscreen with name PlayvideoScreen .java and use the following given code . also copy the above given images to "res" folder


package videoplaying;

import net.rim.device.api.command.Command;
import net.rim.device.api.command.CommandHandler;
import net.rim.device.api.command.ReadOnlyCommandMetadata;
import net.rim.device.api.media.control.AdvancedVideoControl;
import net.rim.device.api.media.control.StreamingBufferControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.image.Image;
import net.rim.device.api.ui.image.ImageFactory;

import javax.microedition.media.*;
import javax.microedition.media.control.*;



public class PlayvideoScreen extends MainScreen implements FieldChangeListener                                                                                          



{
private Player _player;
private static final int VIDEO_WIDTH = Display.getWidth();
private static final int VIDEO_HEIGHT = 200;
    private Player player;

    private VideoControl videoControl;
    ButtonField video ;
    public PlayvideoScreen()
    {
        video = new ButtonField("click me.");

        add(video);

                video.setChangeListener(this);

    }

    public void fieldChanged(Field field, int context)
    {
        if(video == field)
        {
        Field videoField = initializeVideo("http://commonsware.com/misc/test2.3gp"+";deviceside=true");

if (videoField != null) {

// Button for pausing the video
ButtonField pauseButton = new ButtonField("Pause",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
pauseButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Pause the video
try {
_player.stop();
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));

Image pauseImage = ImageFactory.createImage(Bitmap
.getBitmapResource("pause.png"));
pauseButton.setImage(pauseImage);
this.add(pauseButton);

// Button to start/re-start the video
ButtonField playButton = new ButtonField("Play",
ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
playButton.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata metadata,
Object object) {
// Start the video
try {
_player.start();
} catch (Exception e) {
Dialog.inform(e.getMessage());
}
}
}));

Image playImage = ImageFactory.createImage(Bitmap
.getBitmapResource("play.png"));
playButton.setImage(playImage);
this.add(playButton);



this.add(videoField);

}
//            try
//            {//
//             //http://a1408.g.akamai.net/5/1408/1388/2005110405/1a1a1ad948be278cff2d96046ad90768d848b41947aa1986/sample_mpeg4.mp4
//                //              player = Manager.createPlayer("file:///SDCard/Blackberry/videos/Swept.mp4");
//                player = Manager.createPlayer("http://commonsware.com/misc/test2.3gp"+";deviceside=true");
//                player.realize();
//                player.prefetch();
//                videoControl = (VideoControl)player.getControl("VideoControl");
//               // videoControl.setDisplaySize(160, 90);
//                System.out.println("-------------- 6");
//                //              videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
//                Field videoField = (Field)videoControl.initDisplayMode( VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field" );
//
//                add(videoField);
//                player.start();
//                videoControl.setVisible(true);
//                VolumeControl volume = (VolumeControl) player.getControl("VolumeControl");
//                volume.setLevel(30);
//            }
//            catch (final Exception ex)
//            {  
//                System.out.println(ex.toString());
//                UiApplication.getUiApplication().invokeLater(new Runnable()
//                {
//                    public void run()
//                    {
//                        Dialog.alert(""+ex);
//                    }
//                });
//            }
        }

    }
private Field initializeVideo(String s) {
Field videoField = null;

try {
// Create player from input stream

_player = javax.microedition.media.Manager.createPlayer(s
);

// Realize the player
_player.realize();

// Cause playback to begin as soon as possible
// once start()is called on the Player.
StreamingBufferControl sbc = (StreamingBufferControl) _player
.getControl("net.rim.device.api.media.control.StreamingBufferControl");
sbc.setBufferTime(0);

// Obtain video control
AdvancedVideoControl vControl = (AdvancedVideoControl) _player
.getControl("net.rim.device.api.media.control.AdvancedVideoControl");

// Initialize the video control and get the video field
videoField = (Field) vControl.initDisplayMode(
AdvancedVideoControl.USE_GUI_ADVANCED,
"net.rim.device.api.ui.Field");

// Set the video to be a size other than full screen.
// This must be done after calling initDisplayMode().
vControl.setDisplaySize(VIDEO_WIDTH, VIDEO_HEIGHT);

vControl.setVisible(true);
} catch (Exception e) {
Dialog.inform(e.getMessage());
}

return videoField;
}
}

Tuesday, January 1, 2013

BlackBerry getting CellId,MNC,MCC,MAC,LAC


We can retrieve the CELLID,MAC,LAC,MAC,MCC ETC with the help of following code lines!!


                      int CellId=GPRSInfo.getCellInfo().getCellId();
     int LAC=GPRSInfo.getCellInfo().getLAC();
       int MCC=GPRSInfo.getCellInfo().getMCC();
      int MNC=GPRSInfo.getCellInfo().getMNC();

      String CellId1=Integer.toString(CellId);
      String LAC1=Integer.toString(LAC);
      String MCC1=Integer.toString(MCC);
      String MNC1=Integer.toString(MNC);


     
      String CellId2 = System.getProperty("CellID");
      String LAC2 = System.getProperty("LocAreaCode");
     
 
       add(new RichTextField("Hello World!"));
   
       add(new RichTextField("Cell ID is="+CellId1));
       add(new RichTextField("LAC1 is="+LAC1));
       add(new RichTextField("MCC1 is="+MCC1));
       add(new RichTextField("MNC1 is="+MNC1));
       add(new RichTextField("MNC is="+MNC));
       add(new RichTextField("Cell ID2 is="+CellId2));
       add(new RichTextField("LAC2 is="+LAC2));