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



Sunday, December 23, 2012

BlackBerry Deleting data in SD CARD from a given path directory


In BlackBerry we can delete all the data from a given path in SD card by using the following code method. it is help utility which we can use in our programs.

private static void deleteFolder(String fullPath) {
   try {
    FileConnection dirConn = (FileConnection)Connector.open(fullPath, Connector.READ_WRITE);
       if(dirConn.exists() && dirConn.isDirectory()) {
        for(Enumeration e = dirConn.list("*", true); e.hasMoreElements();) {
String name = e.nextElement().toString();
deleteIOneFile(fullPath + name);
}
        dirConn.delete();
       }
       dirConn.close();
} catch(IOException ioe) {
System.out.println("1 Exception : " + ioe.toString());
}
}

Where path can be like
 fullPath= "file:///SDCard/Databases/SQLite_Guide/imageshere/";

BlackBerry checking Network availability before theNetwork Interaction


Some time we need to check the availability of the network connection , with the help of this little code snippet we can check that the network is available or not, before using the the network interaction!!

public static String getTransports() {

avail = "notavailable";
_transportsWithCoverage = TransportInfo.getCoverageStatus();
_transports = TransportInfo
.getTransportDescriptors(_transportsWithCoverage);
for (int i = _transports.length - 1; i >= 0; --i) {
switch (_transports[i].getTransportType()) {
case TransportInfo.TRANSPORT_BIS_B: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_MDS: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_TCP_CELLULAR: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_TCP_WIFI: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_WAP: {
avail = "available";
return avail;
}
case TransportInfo.TRANSPORT_WAP2: {
avail = "available";
return avail;
}
}
}
return avail;

}