Wednesday, January 23, 2013

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));

Tuesday, December 25, 2012

BlackBerry SQLITE databse example with CURD Operations

1)Create a project with name DataBaseExample

and insert the code inside MyScreen.java


package mypackage;

import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.MainScreen;

public final class MyScreen extends MainScreen {

public static final String uripath = "file:///SDCard/Databases/example/"
+ "DemoApp.db";

public MyScreen() {

setTitle("Database Example");
DatabaseSupporter dboperation = new DatabaseSupporter();
dboperation.createDataBaseApp(uripath);
add(new LabelField("database created"));
add(new SeparatorField());
dboperation.createDataBaseTable(uripath);
add(new LabelField("database table created"));
add(new SeparatorField());
dboperation.insertintoDataBaseTable(uripath);
add(new LabelField("database value inserted"));
add(new SeparatorField());
String temp = dboperation.retrievefromoDataBaseTable(uripath);
add(new LabelField("database retrieved==" + temp));
add(new SeparatorField());
//dboperation.updateDataBaseTable(uripath);
//dboperation.deleteDatabase(uripath);
}
}





2) now make new java class for CURD operations as DatabaseSupporter.java and copy following code to it



package mypackage;

import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;

public class DatabaseSupporter {
Database d;

public DatabaseSupporter() {
}

public void createDataBaseApp(String uripath) {

try {
URI myURI = URI.create(uripath);
if (DatabaseFactory.exists(myURI) == true) {
// nothing to do if ALREADY exists
} else {
d = DatabaseFactory.create(myURI);
d.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

public void createDataBaseTable(String uripath) {
try {
URI myURI = URI.create(uripath);
d = DatabaseFactory.open(myURI);
Statement st_todelete = d
.createStatement("DROP TABLE if exists People");
st_todelete.prepare();
st_todelete.execute();
st_todelete.close();
Statement st = d.createStatement("CREATE TABLE 'People' ( "
+ "'Name' TEXT, " + "'Age' INTEGER )");
st.prepare();
st.execute();
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

public void insertintoDataBaseTable(String uripath) {
try {
URI myURI = URI.create(uripath);
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("INSERT INTO People(Name,Age) "
+ "VALUES ('Jitesh',26)");
st.prepare();
st.execute();
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

public String retrievefromoDataBaseTable(String uripath) {
String stringvalue = "value inside db is==>";
try {
URI myURI = URI.create(uripath);
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT Name,Age FROM People");
st.prepare();
net.rim.device.api.database.Cursor c = st.getCursor();
Row r;
int i = 0;
while (c.next()) {
r = c.getRow();
i++;
stringvalue = stringvalue
+ (" " + i + "=> Name = " + r.getString(0) + " , "
+ "Age = " + r.getInteger(1));
}
if (i == 0) {
return "there is nothing to return";
}
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return stringvalue;
}

public void updateDataBaseTable(String uripath) {
try {
d = DatabaseFactory.open(uripath);
Statement st = d.createStatement("UPDATE People SET Age=27 "
+ "WHERE Name='jitesh'");
st.prepare();
st.execute();
st.close();
d.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}

public void deleteDatabase(String uripath) {
try {
URI myURI = URI.create(uripath);
DatabaseFactory.delete(myURI);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

}

}

3) run on emulator, do not forget to insert sd card, follow these steps

simulate==>change sd card=> [click on "+ folder icon" and choose the path]=> now click on "+" at right side to insert sd card and click again on the path value shown to you