Wednesday, April 28, 2010

performing click event in blackberry

protected boolean touchEvent(TouchEvent message)
{
boolean isConsumed = false;

int eventCode = message.getEvent();


if(eventCode == TouchEvent.CLICK) {

UiApplication.getUiApplication().pushScreen(new selctcategory());
}


return isConsumed;
}

Use of Touch events in Blackberry

protected boolean touchEvent(TouchEvent message)
{
boolean isConsumed = false;

TouchGesture touchGesture = message.getGesture();
if (touchGesture != null)
{

if (touchGesture.getEvent() == TouchGesture.SWIPE)
{

switch(touchGesture.getSwipeDirection())
{
case TouchGesture.SWIPE_NORTH:
Dialog.alert("Swipe to up side ");
break;
case TouchGesture.SWIPE_SOUTH:
Dialog.alert("Swipe to down side ");
break;
case TouchGesture.SWIPE_EAST:

Dialog.alert("Swipe to right side ");
break;
case TouchGesture.SWIPE_WEST:

Dialog.alert("Swipe to left side ");

break;
}
isConsumed = true;
}
}
return isConsumed;
}

How to convert an image coming in base64 from webservice into bitmap

byte [] Decoded = Base64InputStream.decode(getNodeValue(detailNode), 0, getNodeValue(detailNode).length());
String dd = new String(Decoded);
dataArray = dd.getBytes();
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
Bitmap bmp = bitmap.getBitmap();
add( new BitmapField(bmp));

Note:- here getNodeValue(detailNode) is a method which reads nodes of Web Service

Thursday, April 22, 2010

Fetch image from url in blackberry

First make a class and paste the code as it is.

package reports;

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

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

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

public class UrlToImage
{
public static Bitmap _bmap;
UrlToImage(String url)
{
HttpConnection connection = null;
InputStream inputStream = null;
EncodedImage bitmap;
byte[] dataArray = null;

try
{
connection = (HttpConnection) Connector.open(url, Connector.READ, true);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData)))
{
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK)
{
throw new IOException("HTTP response code: "
+ responseCode);
}

final String result = rawResponse.toString();
dataArray = result.getBytes();
}
catch (final Exception ex)
{ }

finally
{
try
{
inputStream.close();
inputStream = null;
connection.close();
connection = null;
}
catch(Exception e){}
}

bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
// this will scale your image acc. to your height and width of bitmapfield

int multH;
int multW;
int currHeight = bitmap.getHeight();
int currWidth = bitmap.getWidth();
multH= Fixed32.div(Fixed32.toFP(currHeight),Fixed32.toFP(480));//height
multW = Fixed32.div(Fixed32.toFP(currWidth),Fixed32.toFP(360));//width
bitmap = bitmap.scaleImage32(multW,multH);

_bmap=bitmap.getBitmap();
}
public Bitmap getbitmap()
{
return _bmap;

}


}

Now in ur main class where you want to display picture write the code


package reports;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.MainScreen;

public class First extends UiApplication{
public static void main(String[] args)
{
First theapp = new First();
theapp.enterEventDispatcher();

}
public First()
{
pushScreen(new scr());
}

}
class scr extends MainScreen
{
Bitmap bit ;
BitmapField pic;
public scr()
{
String url ="http://www.somesite.image.jpg";
UrlToImage img = new UrlToImage( url);
bit =img.getbitmap();
pic = new BitmapField(bit);
add(pic);

}
}

Wednesday, April 21, 2010

Update GPS positions in blackberry at regular interval of time

first made a class GPSScreen .Java in which write this code .This will update latitude and longitude after 5 seconds,and shows longitude and latitude update and as well as mapfield changes as lat and long changes.

package com.rim.gpstryupadate;

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

import javax.microedition.location.Coordinates;

import net.rim.device.api.lbs.MapField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

public class GPSScreen extends UiApplication {
public static void main(String[]args)
{
GPSScreen theapp = new GPSScreen();
theapp.enterEventDispatcher();
}
public GPSScreen()
{
pushScreen(new first());
}

class first extends MainScreen
{GPS gps;
Timer timer;
RichTextField txtGPS;
MapField mpfld;
Coordinates cor;
public first(){
gps = new GPS();
timer = new Timer();
timer.schedule(new CheckGPS(), 100, 5000); //check for GPS every 5 second;

String textGPS = "";
txtGPS = new RichTextField(textGPS, RichTextField.NON_FOCUSABLE);
mpfld = new MapField();

add(txtGPS);
add(mpfld);

}
public boolean onClose()
{
timer.cancel(); //cleanup
this.close();
return true;
}

public class CheckGPS extends TimerTask{
public CheckGPS() {
}

public void run() {
double lat;
double lng;
lat = 0;
lng = 0;

lat = gps.getLatitude();
lng = gps.getLongitude();

if (lat != 0.0 & lng != 0.0) {
//synchronized (MyApplicationName.getEventLock()) {
double acc = gps.getAccuracy();
txtGPS.setText(lat + ", " + lng + " (" + gps.getSatCount() + ") (" + (int) acc + ")");
cor = new Coordinates(lat,lng,0);
mpfld.moveTo(cor);
//}
}
else
{
String thetxt = txtGPS.getText();
//synchronized (MyApplicationName.getEventLock()) {
if(thetxt.length() > 10)
if(thetxt.length() > 25)
txtGPS.setText("Waiting for GPS.");
else
txtGPS.setText(thetxt + ".");
else
txtGPS.setText("Waiting for GPS.");
//}
}
}
}
}
}


Make a class GPS.Java this will provide you longitude and latitude values



package com.rim.gpstryupadate;

import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import javax.microedition.location.QualifiedCoordinates;

public class GPS extends Thread{
private double latitude;
private double longitude;
private String satCountStr;
private float accuracy;
/* private double heading;
private double altitude;
private double speed;*/

private int interval = 1; // time in seconds to get new gps data

/**
* This will start the GPS
*/
public GPS() {
// Start getting GPS data
if (currentLocation()) {
// This is going to start to try and get me some data!
}
}

private boolean currentLocation() {
boolean retval = true;
try {
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null) {
lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
} else {
// GPS is not supported, that sucks!
// Here you may want to use UiApplication.getUiApplication() and post a Dialog box saying that it does not work
retval = false;
}
} catch (LocationException e) {
System.out.println("Error: " + e.toString());
}

return retval;
}

private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
//heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
//altitude = location.getQualifiedCoordinates().getAltitude();
//speed = location.getSpeed();

// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null) {
satCountStr = location.getExtraInfo(NMEA_MIME);
}

// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}

public void providerStateChanged(LocationProvider provider, int newState) {
// no-op
}
}

/**
* Returns the terminal's course made good in degrees relative to true north.
* The value is always in the range (0.0,360.0) degrees.
*
* @return double
*/
//public double getHeading() {
//return heading;
// }

/**
* Returns the altitude component of this coordinate.
* Altitude is defined to mean height above the WGS84 reference ellipsoid.
* 0.0 means a location at the ellipsoid surface, negative values mean the
* location is below the ellipsoid surface, Float.NaN that no altitude is
* available.
*
* @return double
*/
//public double getAltitude() {
//return altitude;
//}

/**
* Get the number of satellites that you are currently connected to
*
* @return String
*/
public String getSatCount() {
return satCountStr;
}

/**
* Get the Accuracy of your current GPS location
*
* @return float
*/
public float getAccuracy() {
return accuracy;
}

/**
* Returns the latitude component of this coordinate.
*
* Positive values indicate northern latitude and negative values southern latitude.
*
* @return double
*/
public double getLatitude() {
return latitude;
}

/**
* Returns the longitude component of this coordinate.
*
* Positive values indicate eastern longitude and negative values western longitude.
*
* @return double
*/
public double getLongitude() {
return longitude;
}

/**
* Get your current ground speed in meters per second (m/s) at the time of measurement
*
* @return double
*/
//public double getSpeed() {
// return speed;
//}

}

Friday, April 16, 2010

Make a phonecall from application in blackberry

PhoneArguments phoneArgs = new PhoneArguments(PhoneArguments.ARG_CALL,
"9646616910");
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, phoneArgs);

Thursday, April 15, 2010

Generate apopup screen in blackberry

first create an object of PopupScreen
PopupScreen pop;
now crete an object of verticalfieldmanager
VerticalFieldManager vmainager;

add this vmainager in popupscreen

pop = new PopupScreen(vmainager);
and you all done

Note:-->> Give layout in verticalfield manager.

How to go to previous screen in Blackberry

>>---You can do this by writing this metod.

public boolean onClose()
{
UiApplication.getUiApplication().popScreen(getScreen());
return true;
}

Monday, April 12, 2010

Use of Navigation Click with ListField

package com.rim.listimplement;// Package name

// Import API's
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectListField;
import net.rim.device.api.ui.container.MainScreen;

//Entering into the Appliction
public class List extends UiApplication {
public static void main(String[] args)
{
List theapp = new List();
theapp.enterEventDispatcher();

}
public List()
{
pushScreen(new first());
}

}
/ MAin screen of the class
class first extends MainScreen
{
ObjectListField mylist = new ObjectListField()// Creating ObjectListField
{
// Implementing Navigation Click
protected boolean navigationClick(int status, int time)
{
int selectedindex = mylist.getSelectedIndex();
String it = (String)mylist.get(mylist, selectedindex);
lb = new LabelField(it,LabelField.ELLIPSIS);
Dialog.alert("value"+lb);
return true;
}
};
LabelField lb ;
public first()
{// Getting Values From ListField
super();
String[] item = new String[] {"One","Two","Three"};
mylist.set(item);
add(mylist);


}





}

Saturday, April 10, 2010

Simple GPS Example

package com.rim.GPSTest;

import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

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

public class GPSTest extends UiApplication{



public static void main(String[] args) {
GPSTest gps = new GPSTest();
gps.enterEventDispatcher();

}
public GPSTest(){
pushScreen(new GPSTestScreen());
}
}



final class GPSTestScreen extends MainScreen{
LocationProvider provider;
Location location;
public GPSTestScreen() {


Criteria c = new Criteria();
c.setCostAllowed(false);
c.setHorizontalAccuracy(50);
c.setVerticalAccuracy(50);

try {
provider = LocationProvider.getInstance(c);
location = provider.getLocation(-1);


} catch (LocationException e) {
Dialog.inform("Location Exception");
e.printStackTrace();
} catch (Exception e) {
Dialog.inform("Exception");
e.printStackTrace();
}

add(new LabelField("location: "+Double.toString(location.getQualifiedCoordinates().getLatitude())));
add(new LabelField("location: "+Double.toString(location.getQualifiedCoordinates().getLongitude())));


}
}

Friday, April 9, 2010

XML parsing in Blackberry

package com.rim.androidxml;

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

import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class First extends UiApplication{
public static void main(String[] args)
{
First theapp = new First();
theapp.enterEventDispatcher();
}
public First()
{
pushScreen(new firstxml());
}
}
class firstxml extends MainScreen
{
public firstxml()
{

try
{
HttpConnection conn = null;
String url = "http://www.updatedpics.com/pics/ucatxml.php?catid=46";//URL of web Service
conn = (HttpConnection)Connector.open(url);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document doc = builder.parse(conn.openInputStream());
org.w3c.dom.Element rootElement = doc.getDocumentElement();
rootElement.normalize();
NodeList list = doc.getElementsByTagName("image1");
for(int i=0;i {
Node nd = list.item(i);
if(nd.getNodeType()!=Node.TEXT_NODE)
{
NodeList ndlist = nd.getChildNodes();
for(int k =0;k {
Node nd1 = ndlist.item(k);
if(nd1.getNodeType()!=Node.TEXT_NODE)
{
NodeList nd1list = nd1.getChildNodes();
for(int j=0;j {
Node ddetailnode = nd1list.item(j);
if(ddetailnode.getNodeType()!=Node.TEXT_NODE)
{
if(ddetailnode.getNodeName().equalsIgnoreCase("catname"))
{
add(new RichTextField(getNodeValue(ddetailnode))
{
public void paint(Graphics g)
{
g.setColor(Color.ORANGE);
super.paint(g);
}
});
}
if(ddetailnode.getNodeName().equalsIgnoreCase("name"))
{
add(new RichTextField(getNodeValue(ddetailnode))
{
public void paint(Graphics g)
{
g.setColor(Color.BLUE);
super.paint(g);
}
});


}
}
}
}
}
}
}


}
catch(Exception e)
{}
}
public String getNodeValue(Node node)
{
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}

NOTE:- No. of loop depends upon no.of tags before the tags which you want to read.
Sorry i can't make everyline as comment so understand on your behalf.

Thursday, April 8, 2010

Implementation of MapField in Blackberry

import javax.microedition.location.Coordinates;

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

public class MapFielddemo extends UiApplication
{
public static void main(String[] args)
{
MapFielddemo theApp = new MapFielddemo();
theApp.enterEventDispatcher();
}

MapFielddemo()
{
pushScreen(new myScreen());
}
}

class myScreen extends FullScreen implements FieldChangeListener
{
private MapField _mapField;
private ButtonField _zoomIn;
private ButtonField _zoomOut;
private double _prevLat = 30.721596105585;
private double _prevLon = 76.710104942322;// positions of city in india, so if you want to try it please zoom out when you run this code.
private int _prevZoom = 4;

myScreen()
{
super(DEFAULT_MENU | DEFAULT_CLOSE);
createUI();
}

private void createUI()
{
Coordinates cord = new Coordinates(_prevLat,_prevLon,0);
VerticalFieldManager vfm;

synchronized (Application.getEventLock())
{
vfm = new VerticalFieldManager
(Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT);
_mapField = new MapField();
_mapField.setPreferredSize(_mapField.getPreferredWidth(),
(int)(Display.getHeight() * 0.91));
vfm.add(_mapField);
}

FlowFieldManager ffm = new FlowFieldManager();
ffm.add(_zoomIn = new ButtonField("Zoom In",ButtonField.CONSUME_CLICK));
_zoomIn.setChangeListener(this);

ffm.add(_zoomOut = new ButtonField("Zoom Out",ButtonField.CONSUME_CLICK));
_zoomOut.setChangeListener(this);



vfm.add(ffm);
add(vfm);

_mapField.moveTo(cord);


_mapField.setZoom(_prevZoom);
}

public void fieldChanged(Field field, int context)
{
if (field == _zoomIn)
{
_mapField.setZoom(Math.max(_mapField.getZoom() - 1,
_mapField.getMinZoom()));
}
else if (field == _zoomOut)
{
_mapField.setZoom(Math.min(_mapField.getZoom() + 1,
_mapField.getMaxZoom()));
}




}
}

Wednesday, April 7, 2010

Implementation of fieldchange listner in blackberry

//import packages manually or otherwise it comes bydefault
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
ButtonField Enterbutton;//Declare a button field inside your class.
//this goes inside constructor.
Enterbutton = new ButtonField("Enter",ButtonField.FOCUSABLE);
FieldChangeListener enterlistner = new FieldChangeListener()//implementing fieldchange listner named as enterlistner
{
public void fieldChanged(Field field, int context)
{
if(field==Enterbutton)
{
Dialog.alert("button clicked");
}
}
};

Enterbutton.setChangeListener(enterlistner);// set button to listen for particular listner.

Use of Splash Screen in Your Project

package com.rim.carmap;// This is Package name

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.container.MainScreen;

public class Splashscreen extends UiApplication{
public static void main(String[]args)
{
Splashscreen theapp = new Splashscreen();
theapp.enterEventDispatcher();
}
public Splashscreen()
{
pushScreen(new startscreen());
}

}
class startscreen extends MainScreen
{
Bitmap b1;
BitmapField splsh;
FirstScreen firstpage;// Class name or screen name where i want to move as the splash goes off.
public startscreen()
{
b1 = Bitmap.getBitmapResource("splashtry.png");
splsh=new BitmapField(b1,BitmapField.HCENTER);
add(splsh);
firstpage = new FirstScreen();
startloading();
}
public void startloading()
{
Thread loadthread = new Thread()
{
public void run()
{
try
{
Thread.sleep(10000);
}
catch (java.lang.InterruptedException e)
{}

UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushScreen(firstpage);
}
});
}
};
loadthread.start();
}


}