Saving data to persistent store bug in BlackBerry 6 - blackberry

I am trying to save a path to an image in the persistent store to show the image when a user chooses a specific product from a history list(one image per product, taken by the user). Now the problem I am having is that when I load the app to the phone for the first time and try adding an entry to the persistent store, it throws an error a bit after and the app freezes. However when I come back, and add an image again, it works just fine and the images always load when I choose each specific product.
This is leading me to believe that the culprit is the first store8.commit() that I'm doing, for some reason it throws an exception : No Stack Trace, when debugging. Here is my code:
public class Storage extends Application {
private static final long PERSISTENT_KEY8 = 0x2c4c45c139ee9728L;
static PersistentObject store8 = PersistentStore.getPersistentObject(PERSISTENT_KEY8);
private static Vector pics;
/**
* Picture Section ***********************************************************
*/
public static void savePicture(){
store8.setContents(new Vector());
store8.commit();
if(pics == null){
pics = new Vector();
}
synchronized(store8) {
store8.setContents(pics);
store8.commit();
}
}
public static String getPicture(String productName){
if(pics.size()==0){
return "";
}else{
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
return product.getPic();
}
}
return "";
}
}
public static void removePicture(String productName){
if(pics.size()==0){
return;
}else{
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
pics.removeElementAt(i);
}
}
}
}
public static void loadPicture(){
pics = (Vector)store8.getContents();
if(pics == null){
pics = new Vector();
}
}
public static void setPicture(Pics pro){
if(pics.size()!=0){
for(int j = 0; j< pics.size() ; j++){
Pics product = (Pics)pics.elementAt(j);
if(pro.getProductName().equals(product.getProductName())){
pics.removeElementAt(j);
}
}
}
pics.addElement(pro);
}
}
So that is the class that contains my methods to save the image. Now for the other class where I am manipulating it:
public class ProductImage extends MainScreen implements FieldChangeListener, AppLaunchResource {
private ImageButtonField logo;
private ButtonField newImage, chooseExisting;
public static BitmapField takenPicture;
//public static String picPath ="";
private String currentPicture = "";
private String currentProduct ="";
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
this.setTitle(new LabelField("Add An Image", Field.FIELD_HCENTER));
if(ToolbarManager.isToolbarSupported())
{
Toolbar tb = new Toolbar();
setToolbar(tb.createToolBar());
}
else{
Toolbar tb = new Toolbar();
add(tb.createNavBar());
}
try{
Storage.loadPicture();
}catch(NullPointerException e){
e.printStackTrace();
}
newImage = new ButtonField("Take Photo", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) (net.rim.device.api.system.Display.getWidth());
}
};
chooseExisting= new ButtonField("Change Image", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) (net.rim.device.api.system.Display.getWidth());
}
};
newImage.setChangeListener(this);
chooseExisting.setChangeListener(this);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
VerticalFieldManager vfMain = new VerticalFieldManager();
vfMain.add(new SeparatorField());
vfMain.add(newImage);
vfMain.add(chooseExisting);
vfMain.add(takenPicture);
add(vfMain);
currentPicture = Storage.getPicture(currentProduct);
showPicture();
}
public void choosePicture(){
String imageExtensions[] = {"jpg", "jpeg",
"bmp", "png", "gif"};
FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
fps.pickFile();
String theFile = fps.getFile();
UiApplication.getUiApplication().pushScreen(fps);
if (theFile == null)
{
Dialog.alert("Screen was dismissed. No file was selected.");
}
else
{
try{
String path= "file:///" + theFile;
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
if(Display.getHeight()>Display.getWidth()){
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
else{
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
UiApplication.getUiApplication().popScreen(fps);
takenPicture.setBitmap(eImage.getBitmap());
Storage.setPicture(new Pics(currentProduct, path));
try{
Storage.savePicture();
}catch(Exception e){
e.printStackTrace();
}
}
catch(Exception e){
}
Dialog.alert("Picture Saved");
}
}
public void showPicture(){
if(currentPicture != ""){
try{
String path= currentPicture;
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
if(Display.getHeight()>Display.getWidth()){
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
else{
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
takenPicture.setBitmap(eImage.getBitmap());
}
catch(Exception e){
}
}
}
public void fieldChanged(Field field, int context) {
if(field == logo){
}
else if(field == newImage){
takePicture();
}
else if(field == chooseExisting){
choosePicture();
}
}
}
I removed many parts of this class, sorry if it is long, there are basically 4 Storage method calls in this code and I believe they are all in the right place.. but again im having the problem on first load, not afterwards.
Can anyone see what Im doing wrong here? I have had this problem for a week
Thanks for any help provided!

Try something like this:
public class Storage extends Application{
private static final long PERSISTENT_KEY8 = 0x2c4c45c139ee9728L;
static PersistentObject store8 = null;
private static Vector pics = null;
static{
store8 = PersistentStore.getPersistentObject(PERSISTENT_KEY8)
pics = (Vector)store8.getContents();
if(pics == null){
pics = new Vector();
store8.setContents(pics);
store8.commit();
}
}
public static void savePicture(){
try{
synchronized(store8){
store8.setContents(pics);
store8.commit();
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static int findPicture(String productName){
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
return i;
}
}
return -1;
}
public static String getPicture(String productName){
int idx = findPicture(productName);
if(idx != -1){
return ((Pics)pics.elementAt(idx)).getPic();
}
return "";
}
public static void removePicture(String productName){
int idx = findPicture(productName);
if(idx != -1){
pics.removeElementAt(idx);
}
}
public static void setPicture(Pics pro){
removePicture(pro.getProductName());
pics.addElement(pro);
}
}
.
public class ProductImage extends MainScreen implements FieldChangeListener, AppLaunchResource {
private ImageButtonField logo;
private ButtonField newImage, chooseExisting;
public static BitmapField takenPicture;
//public static String picPath ="";
private String currentPicture = "";
private String currentProduct = "";
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
setTitle(new LabelField("Add An Image", Field.FIELD_HCENTER));
Toolbar tb = new Toolbar();
if(ToolbarManager.isToolbarSupported()){
setToolbar(tb.createToolBar());
}
else{
add(tb.createNavBar());
}
newImage = new ButtonField("Take Photo", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) Display.getWidth();
}
};
chooseExisting = new ButtonField("Change Image", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) Display.getWidth();
}
};
newImage.setChangeListener(this);
chooseExisting.setChangeListener(this);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
VerticalFieldManager vfMain = new VerticalFieldManager();
vfMain.add(new SeparatorField());
vfMain.add(newImage);
vfMain.add(chooseExisting);
vfMain.add(takenPicture);
add(vfMain);
currentPicture = Storage.getPicture(currentProduct);
showPicture();
}
public void choosePicture(){
String imageExtensions[] = {"jpg", "jpeg", "bmp", "png", "gif"};
FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
fps.pickFile();
String theFile = fps.getFile();
if (theFile == null){
Dialog.alert("Screen was dismissed. No file was selected.");
return;
}
EncodedImage eImage = loadImage("file:///" + theFile);
if(eImage != null){
takenPicture.setBitmap(eImage.getBitmap());
Storage.setPicture(new Pics(currentProduct, path));
Storage.savePicture();
Dialog.alert("Picture Saved");
}
}
private EncodedImage loadImage(String path){
try{
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
int scaleFactorX, scaleFactorY;
if(Display.getHeight()>Display.getWidth()){
scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(Display.getWidth()));
scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
}
else{
scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(Display.getWidth()));
scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(Display.getHeight()));
}
return eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
catch (Exception e){
return null;
}
}
public void showPicture(){
if(currentPicture != ""){
EncodedImage eImage = loadImage(currentPicture);
if (eImage != null){
takenPicture.setBitmap(eImage.getBitmap());
}
}
}
public void fieldChanged(Field field, int context){
if(field == logo){
}
else if(field == newImage){
takePicture();
}
else if(field == chooseExisting){
choosePicture();
}
}
}

Related

Background Application unable to display UI when receive push notification

Here is my full push notification listener.
public class MyApp extends UiApplication {
public static void main(String[] args) {
PushAgent pa = new PushAgent();
pa.enterEventDispatcher();
}
}
Is this class extended correctly?
public class PushAgent extends Application {
private static final String PUSH_PORT = "32023";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "2727-c55087eR3001rr475448i013212a56shss2";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=mds-public";
public static final long ID = 0x749cb23a75c60e2dL;
private MessageReadingThread messageReadingThread;
public PushAgent() {
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
return;
}
if (DeviceInfo.isSimulator()) {
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
try {
socket = (ServerSocketConnection) Connector.open(url);
} catch (IOException ex) {
}
while (running) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream(conn, inputStream);
PushMessageReader.process(pushInputStream, conn);
} catch (Exception e) {
if (running) {
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}
}
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
private String formRegisterRequest(String bpasUrl, String appId,
String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null)
+ CONNECTION_SUFFIX;
Object theSource = new Object() {
public String toString() {
return "Oriental Daily";
}
};
NotificationsManager.registerSource(ID, theSource,
NotificationsConstants.IMPORTANT);
new Thread() {
public void run() {
try {
HttpConnection httpConnection = (HttpConnection) Connector
.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID,
response) + CONNECTION_SUFFIX;
HttpConnection nextHttpConnection = (HttpConnection) Connector
.open(nextUrl);
InputStream nextInputStream = nextHttpConnection
.openInputStream();
response = new String(
IOUtilities.streamToBytes(nextInputStream));
close(nextHttpConnection, is, null);
} catch (IOException e) {
}
}
}.start();
}
}
}
This is the process;
public class PushMessageReader {
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
private static final String MESSAGE_TYPE_TEXT = "text";
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
public static final long ID = 0x749cb23a75c60e2dL;
public static Bitmap popup = Bitmap.getBitmapResource("icon_24.png");
private PushMessageReader() {
}
public static void process(PushInputStream pis, Connection conn) {
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException(
"Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
NotificationsManager.triggerImmediateEvent(ID, 0, null,
null);
processTextMessage(buffer);
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
Base64InputStream bis = new Base64InputStream(
new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
}
}
pis.accept();
} catch (Exception e) {
} finally {
PushAgent.close(conn, pis, null);
}
}
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
private static void processTextMessage(final byte[] data) {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
GlobalDialog screen = new GlobalDialog("New Notification",
"Article ID : " + new String(data), new String(data));
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
static class GlobalDialog extends PopupScreen implements
FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
| FIELD_HCENTER);
String data = "";
public GlobalDialog(String title, String text, String data) {
super(new VerticalFieldManager());
this.data = data;
add(new LabelField(title));
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
add(new LabelField(text, DrawStyle.HCENTER));
mOKButton.setChangeListener(this);
add(mOKButton);
}
public void fieldChanged(Field field, int context) {
if (mOKButton == field) {
try {
ApplicationManager.getApplicationManager().launch(
"OrientalDailyBB");
ApplicationManager.getApplicationManager().postGlobalEvent(
ID, 0, 0, data, null);
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
close();
} catch (ApplicationManagerException e) {
}
}
}
}
}
In this project, I checked Auto-run on startup so that this background app listener will run all the time and set the start tier to 7 in the BB App Descriptor.
However, it cannot display the popup Dialog, but I can see the device has received the push notification.
After the dialog popup and user click OK will start the OrientalDailyBB project and display the particular MainScreen.
FYI: The listener priority is higher than the OrientalDailyBB project because it is a background application. So when I install OrientalDailyBB, it will install this listener too. It happened because this listener is not in the OrientalDailyBB project folder, but is in a different folder. I did separate them to avoid the background application being terminated when the user quits from OrientalDailyBB.
I believe that this is a threading problem. pushGlobalScreen is a message you could try to use with invokeLater.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
});
you could try to push the application to the foreground too.

Get suffix string for BlackBerry connection on 4.6.1?

I'm trying to develop an application which uses HttpRequest for requesting a web page. The problem is that I still can't find the right way to get the suffix in the connection string for OS 4.6.1.
Thanks.
The links I believe I used to create my connection strings, pre OS 5.0, were these two:
http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-make-an-HTTP-or-socket-connection/ta-p/445879
http://docs.blackberry.com/en/developers/deliverables/34480/Network_transport_options_1293321_11.jsp
BlackBerry of course supports several different transports (Wifi, WAP, BIS, etc.). You probably want to decide which transport you would like to use, and create your connection string depending on which transports are available at any one time, and on your priority.
Here's some more sample code to download from blackberry.com that helps build connection string suffixes. See the attachment links near the bottom for the actual downloads.
Also, if you're in a time crunch, and don't have time to read the resources I listed in my other answer, and just want some quick code, I remember there was an implementation in BlackBerry's original Facebook SDK that looked close to what I wrote myself (sorry, I can't post that code I wrote, because it's my client's). But, the Facebook SDK implementation appears to be free to publish. I can't find a link to it anymore, but I'll paste it below for your enjoyment:
/**
* Copyright (c) E.Y. Baskoro, Research In Motion Limited.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* This License shall be included in all copies or substantial
* portions of the Software.
*
* The name(s) of the above copyright holders shall not be used
* in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*
*/
package com.blackberry.util.network;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import com.blackberry.util.log.Logger;
import net.rim.device.api.io.http.HttpHeaders;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.Branding;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.WLANInfo;
public class HttpConnectionFactory {
public static final int TRANSPORT_WIFI = 1;
public static final int TRANSPORT_BES = 2;
public static final int TRANSPORT_BIS = 4;
public static final int TRANSPORT_DIRECT_TCP = 8;
public static final int TRANSPORT_WAP2 = 16;
public static final int TRANSPORT_SIM = 32;
public static final int TRANSPORTS_ANY = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
public static final int TRANSPORTS_AVOID_CARRIER = TRANSPORT_WIFI | TRANSPORT_BES | TRANSPORT_BIS | TRANSPORT_SIM;
public static final int TRANSPORTS_CARRIER_ONLY = TRANSPORT_DIRECT_TCP | TRANSPORT_WAP2 | TRANSPORT_SIM;
public static final int DEFAULT_TRANSPORT_ORDER[] = { TRANSPORT_SIM, TRANSPORT_WIFI, TRANSPORT_BIS, TRANSPORT_BES, TRANSPORT_WAP2, TRANSPORT_DIRECT_TCP };
private static final int TRANSPORT_COUNT = DEFAULT_TRANSPORT_ORDER.length;
// private static ServiceRecord srMDS[], srBIS[], srWAP2[], srWiFi[];
private static ServiceRecord srWAP2[];
private static boolean serviceRecordsLoaded = false;
private int transports[];
private int lastTransport = -1;
protected Logger log = Logger.getLogger(getClass());
public HttpConnectionFactory() {
this(0);
}
public HttpConnectionFactory(int allowedTransports) {
this(transportMaskToArray(allowedTransports));
}
public HttpConnectionFactory(int transportPriority[]) {
if (!serviceRecordsLoaded) {
loadServiceBooks(false);
}
transports = transportPriority;
}
public static String getUserAgent() {
StringBuffer sb = new StringBuffer();
sb.append("BlackBerry");
sb.append(DeviceInfo.getDeviceName());
sb.append("/");
sb.append(DeviceInfo.getSoftwareVersion());
sb.append(" Profile/");
sb.append(System.getProperty("microedition.profiles"));
sb.append(" Configuration/");
sb.append(System.getProperty("microedition.configuration"));
sb.append(" VendorID/");
sb.append(Branding.getVendorId());
return sb.toString();
}
public static String getProfile() {
StringBuffer sb = new StringBuffer();
sb.append("http://www.blackberry.net/go/mobile/profiles/uaprof/");
sb.append(DeviceInfo.getDeviceName());
sb.append("/");
sb.append(DeviceInfo.getSoftwareVersion().substring(0, 3)); //RDF file format is 4.5.0.rdf (does not include build version)
sb.append(".rdf");
return sb.toString();
}
public HttpConnection getHttpConnection(String pURL) {
return getHttpConnection(pURL, null, null);
}
public HttpConnection getHttpConnection(String pURL, HttpHeaders headers) {
return getHttpConnection(pURL, headers, null);
}
public HttpConnection getHttpConnection(String pURL, byte[] data) {
return getHttpConnection(pURL, null, data);
}
public HttpConnection getHttpConnection(String pURL, HttpHeaders headers, byte[] data) {
if ((pURL.length() > 5) && pURL.startsWith("cod://")) {
return new LocalHttpConnection(pURL);
}
int curIndex = 0;
HttpConnection con = null;
while ((con = tryHttpConnection(pURL, curIndex, headers, data)) == null) {
try {
curIndex = nextTransport(curIndex);
} catch (HttpConnectionFactoryException e) {
e.printStackTrace();
break;
} finally {
}
}
if (con != null) {
setLastTransport(transports[curIndex]);
}
return con;
}
private int nextTransport(int curIndex) throws HttpConnectionFactoryException {
if ((curIndex >= 0) && (curIndex < transports.length - 1)) {
return curIndex + 1;
} else {
throw new HttpConnectionFactoryException("No more transport available.");
}
}
private HttpConnection tryHttpConnection(String pURL, int tIndex, HttpHeaders headers, byte[] data) {
HttpConnection con = null;
OutputStream os = null;
log.debug("Trying " + getTransportName(transports[tIndex]) + "... ");
switch (transports[tIndex]) {
case TRANSPORT_SIM:
try {
con = getSimConnection(pURL, false);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_WIFI:
try {
con = getWifiConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_BES:
try {
con = getBesConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_BIS:
try {
con = getBisConnection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
case TRANSPORT_DIRECT_TCP:
try {
con = getTcpConnection(pURL);
} catch (IOException e) {
} finally {
break;
}
case TRANSPORT_WAP2:
try {
con = getWap2Connection(pURL);
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
break;
}
}
log.debug("con = " + con);
if (con != null) {
try {
log.debug("url = " + con.getURL());
//add headers to connection
if (headers != null) {
int size = headers.size();
for (int i = 0; i < size;) {
String header = headers.getPropertyKey(i);
String value = headers.getPropertyValue(i++);
if (value != null) {
con.setRequestProperty(header, value);
}
}
}
// post data
if (data != null) {
con.setRequestMethod(HttpConnection.POST);
con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED);
con.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(data.length));
os = con.openOutputStream();
os.write(data);
} else {
con.setRequestMethod(HttpConnection.GET);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return con;
}
public int getLastTransport() {
return lastTransport;
}
public String getLastTransportName() {
return getTransportName(getLastTransport());
}
private void setLastTransport(int pLastTransport) {
lastTransport = pLastTransport;
}
private HttpConnection getSimConnection(String pURL, boolean mdsSimulatorRunning) throws IOException {
if (DeviceInfo.isSimulator()) {
if (mdsSimulatorRunning) {
return getConnection(pURL, ";deviceside=false", null);
} else {
return getConnection(pURL, ";deviceside=true", null);
}
}
return null;
}
private HttpConnection getBisConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(4 /* CoverageInfo.COVERAGE_BIS_B */)) {
return getConnection(pURL, ";deviceside=false;ConnectionType=mds-public", null);
}
return null;
}
private HttpConnection getBesConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(2 /* CoverageInfo.COVERAGE_MDS */)) {
return getConnection(pURL, ";deviceside=false", null);
}
return null;
}
private HttpConnection getWifiConnection(String pURL) throws IOException {
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
return getConnection(pURL, ";interface=wifi", null);
}
return null;
}
private HttpConnection getWap2Connection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */) && (srWAP2 != null) && (srWAP2.length != 0)) {
return getConnection(pURL, ";deviceside=true;ConnectionUID=", srWAP2[0].getUid());
}
return null;
}
private HttpConnection getTcpConnection(String pURL) throws IOException {
if (CoverageInfo.isCoverageSufficient(1 /* CoverageInfo.COVERAGE_DIRECT */)) {
return getConnection(pURL, ";deviceside=true", null);
}
return null;
}
private HttpConnection getConnection(String pURL, String transportExtras1, String transportExtras2) throws IOException {
StringBuffer fullUrl = new StringBuffer();
fullUrl.append(pURL);
if (transportExtras1 != null) {
fullUrl.append(transportExtras1);
}
if (transportExtras2 != null) {
fullUrl.append(transportExtras2);
}
return (HttpConnection) Connector.open(fullUrl.toString());
}
public static void reloadServiceBooks() {
loadServiceBooks(true);
}
private static synchronized void loadServiceBooks(boolean reload) {
if (serviceRecordsLoaded && !reload) {
return;
}
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
Vector mdsVec = new Vector();
Vector bisVec = new Vector();
Vector wap2Vec = new Vector();
Vector wifiVec = new Vector();
if (!serviceRecordsLoaded) {
for (int i = 0; i < records.length; i++) {
ServiceRecord myRecord = records[i];
String cid, uid;
if (myRecord.isValid() && !myRecord.isDisabled()) {
cid = myRecord.getCid().toLowerCase();
uid = myRecord.getUid().toLowerCase();
if ((cid.indexOf("wptcp") != -1) && (uid.indexOf("wap2") != -1) && (uid.indexOf("wifi") == -1) && (uid.indexOf("mms") == -1)) {
wap2Vec.addElement(myRecord);
}
}
}
srWAP2 = new ServiceRecord[wap2Vec.size()];
wap2Vec.copyInto(srWAP2);
wap2Vec.removeAllElements();
wap2Vec = null;
serviceRecordsLoaded = true;
}
}
public static int[] transportMaskToArray(int mask) {
if (mask == 0) {
mask = TRANSPORTS_ANY;
}
int numTransports = 0;
for (int i = 0; i < TRANSPORT_COUNT; i++) {
if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
numTransports++;
}
}
int transports[] = new int[numTransports];
int index = 0;
for (int i = 0; i < TRANSPORT_COUNT; i++) {
if ((DEFAULT_TRANSPORT_ORDER[i] & mask) != 0) {
transports[index++] = DEFAULT_TRANSPORT_ORDER[i];
}
}
return transports;
}
private static String getTransportName(int transport) {
String tName;
switch (transport) {
case TRANSPORT_WIFI:
tName = "WIFI";
break;
case TRANSPORT_BES:
tName = "BES";
break;
case TRANSPORT_BIS:
tName = "BIS";
break;
case TRANSPORT_DIRECT_TCP:
tName = "TCP";
break;
case TRANSPORT_WAP2:
tName = "WAP2";
break;
case TRANSPORT_SIM:
tName = "SIM";
break;
default:
tName = "UNKNOWN";
break;
}
return tName;
}
}

Get Camera captured images and create bitmap image

How to get camera captured images after native camera app exits ?
How to create an Bitmap image from the already existing SD card Jpeg image ?
I want to add this Bitmap to the screen.
ButtonField btn_Take_Pic = new ButtonField("Take a pic",Field.FIELD_HCENTER|FOCUSABLE)
{
protected boolean navigationClick(int status, int time) {
// TODO Auto-generated method stub
InvokeCameraScreen screen = new InvokeCameraScreen(CaptureImage.this);
screen.addCam();
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
//Perform screen changes here.
//Calling invalidate() on your screen forces the paint
//method to be called.
CaptureImage deal_Screen = new CaptureImage();
deal_Screen.invalidate();
}
});
return true;
}
};
Add body part of ImagePath() method
public void ImagePath(String path) {
try
{
Img_path = path;
EncodedImage.createEncodedImage(imgarr,0,imgarr.length);
Bitmap setimage = resizeBitmap(getBitmapFromFile(info.getImg_Path()),(int) (ScreenWidth *0.20),(int) (ScreenHeight *0.20));
Img_Field.setBitmap(setimage);
}
catch (Exception e) {
// TODO: handle exception
Dialog.alert("Ex path: " + e.toString());
}
}
implements ImagePath interface
public interface ImagePath {
public void ImagePath(String path);
}
public class InvokeCameraScreen implements FileSystemJournalListener {
private long lastUSN;
private String resultData, imagepath;
private VerticalFieldManager addToSCreen;
private boolean isAlreadeyExcuted = true;
private byte[] imageData;
private ImagePath pathImage;
public InvokeCameraScreen(ImagePath path) {
this.pathImage = path;
}
public void addCam() {
isAlreadeyExcuted = true;
getAddToSCreen().deleteAll();
startCam();
}
private void startCam() {
lastUSN = FileSystemJournal.getNextUSN();
UiApplication.getUiApplication().addFileSystemJournalListener(this);
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
});
} catch (Exception e) {
System.out.println("CheckinFormScreen Exception: " + e.toString());
}
}
private void closeCamera() {
System.out.println("Closing Cam");
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 25);
inject.post();
try {
Thread.sleep(500);
} catch (Exception e) {
}
UiApplication.getUiApplication().removeFileSystemJournalListener(this);
System.out.println("Done with closing cam");
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public void fileJournalChanged() {
try {
closeCamera();
} catch (Exception e) {
}
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
String path = entry.getPath();
if (path != null && path.indexOf(".jpg") != -1) {
if (isAlreadeyExcuted) {
isAlreadeyExcuted = false;
resultData = "file://" + path;
pathImage.ImagePath(resultData);
// ShowUploadImage(resultData);
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0, 25);
inject.post();
inject.post();
if (Display.getWidth() == 480
&& Display.getHeight() == 360
|| Display.getWidth() == 360
&& Display.getHeight() == 480) {
try {
Thread.sleep(500);
inject.post();
} catch (Exception e) {
}
}
}
}
return;
}
}
}
public VerticalFieldManager getAddToSCreen() {
if (addToSCreen == null) {
addToSCreen = new VerticalFieldManager();
addToSCreen.setPadding(10, 10, 10, 10);
}
return addToSCreen;
}
public void setAddToSCreen(VerticalFieldManager addToSCreen) {
this.addToSCreen = addToSCreen;
}
private void ShowUploadImage(String path) {
}
}
try this,
CAll Below Class Like:
EncodedImage result = NcCamera.getInstance().getPictureTaken();
//
This is class in which you can get Camera images.
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class NcCamera extends MainScreen
{
private VideoControl videoControl;
private Field videoField;
public static EncodedImage pictureTaken = null;
private boolean initialized = false;
private boolean result;
public static boolean CAPTURING_DONE = true;
public static boolean CAPTURING_CANCELED = false;
private VerticalFieldManager main;
private static NcCamera instance;
CommonFunction cmn_fun;
public static byte[] raw;
public NcCamera()
{
super(NO_VERTICAL_SCROLL);
main = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
{
// I wan't to force the backgound to black
public void paintBackground(Graphics g)
{
g.setBackgroundColor(0x000000);
g.clear();
}
};
super.add(main);
}
public void add(Field field)
{
main.add(field);
}
public EncodedImage getPictureTaken()
{
return pictureTaken;
}
public Screen getThisScreen()
{
return this;
}
public void reset()
{
pictureTaken = null;
result = CAPTURING_CANCELED;
}
public boolean showDialog()
{
result = CAPTURING_CANCELED;
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushModalScreen(getThisScreen());
if (pictureTaken != null)
result = CAPTURING_DONE;
}
});
return result;
}
public static NcCamera getInstance()
{
if (instance == null)
instance = new NcCamera();
return instance;
}
public void onDisplay() {
if (!initialized)
{
initializeCamera();
if (videoField!=null) add(videoField);
else {
LabelField sorry = new LabelField("Sorry, we cannot use camera right now.") {
// I need to force the label to be white colored to be visible above
// it's underlying manager (that is black).
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xffffff);
super.paint(g);
g.setColor(color);
}
};
add(sorry);
}
initialized = true;
}
}
private void initializeCamera()
{
try {
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
if (videoControl != null)
{
videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
}
player.start();
} catch (Exception e)
{
}
}
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if (!handled)
{
switch (action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void takePicture()
{
try {
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
raw = videoControl.getSnapshot(null);
// SaveImageSdcard(raw);
Bitmap img= Bitmap.createBitmapFromBytes(raw, 0, raw.length,3);
Constants.PICTURE_TAKEN=cmn_fun.resizeBitmap(img, 150, 150);
// save the picture taken into pictureTaken variable
pictureTaken = EncodedImage.createEncodedImage(raw, 0, raw.length);
result = CAPTURING_DONE;
close();
} catch (Exception e)
{
}
}
}
public boolean keyDown(int keycode,
int time) {
if (keycode == 1769472)
{ // escape pressed
reset();
close();
return true;
}
return super.keyDown(keycode, time);
}
}

Blackberry: Multiline ListView

I have made list view with checkboxes. I have read similar articles n many people have suggested to do changes in drawlistRow but it is not happening. Can u suggest me where should i change to make it a multi line list.The code snippet is :
Updated: I updated my code and it is still not working
public class CheckboxListField extends MainScreen implements ListFieldCallback, FieldChangeListener {
int mCheckBoxesCount = 5;
private Vector _listData = new Vector();
private ListField listField;
private ContactList blackBerryContactList;
private BlackBerryContact blackBerryContact;
private Vector blackBerryContacts;
private MenuItem _toggleItem;
ButtonField button;
BasicEditField mEdit;
CheckboxField cb;
CheckboxField[] chk_service;
HorizontalFieldManager hm4;
CheckboxField[] m_arrFields;
boolean mProgrammatic = false;
public static StringBuffer sbi = new StringBuffer();
VerticalFieldManager checkBoxGroup = new VerticalFieldManager();
LabelField task;
//A class to hold the Strings in the CheckBox and it's checkbox state (checked or unchecked).
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData()
{
_stringVal = "";
_checked = false;
}
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
private void setStringVal(String stringVal)
{
_stringVal = stringVal;
}
private void setChecked(boolean checked)
{
_checked = checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
CheckboxListField()
{
_toggleItem = new MenuItem("Change Option", 200, 10)
{
public void run()
{
//Get the index of the selected row.
int index = listField.getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
listField.invalidate(index);
if (index != -1 && !blackBerryContacts.isEmpty())
{
blackBerryContact =
(BlackBerryContact)blackBerryContacts.
elementAt(listField.getSelectedIndex());
ContactDetailsScreen contactDetailsScreen =
new ContactDetailsScreen(blackBerryContact);
UiApplication.getUiApplication().pushScreen(contactDetailsScreen);
}
}
};
listField = new ListField();
listField.setRowHeight(getFont().getHeight() * 2);
listField.setCallback(this);
reloadContactList();
//CheckboxField[] cb = new CheckboxField[blackBerryContacts.size()];
for(int count = 0; count < blackBerryContacts.size(); ++count)
{
BlackBerryContact item =
(BlackBerryContact)blackBerryContacts.elementAt(count);
String displayName = getDisplayName(item);
CheckboxField cb = new CheckboxField(displayName, false);
cb.setChangeListener(this);
add(cb);
listField.insert(count);
}
blackBerryContacts.addElement(cb);
add(checkBoxGroup);
}
protected void makeMenu(Menu menu, int instance)
{
menu.add(new MenuItem("Get", 2, 2) {
public void run() {
for (int i = 0; i < checkBoxGroup.getFieldCount(); i++) {
//for(int i=0; i<blackBerryContacts.size(); i++) {
CheckboxField checkboxField = (CheckboxField)checkBoxGroup
.getField(i);
if (checkboxField.getChecked()) {
sbi.append(checkboxField.getLabel()).append("\n");
}
}
Dialog.inform("Selected checkbox text::" + sbi);
}
});
super.makeMenu(menu, instance);
}
private boolean reloadContactList()
{
try {
blackBerryContactList =
(ContactList)PIM.getInstance().openPIMList
(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration allContacts = blackBerryContactList.items();
blackBerryContacts = enumToVector(allContacts);
listField.setSize(blackBerryContacts.size());
return true;
} catch (PIMException e)
{
return false;
}
}
//Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//graphics.drawText("ROW", 0, y, 0, w);
//String rowNumber = "one";
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*graphics.drawText("ROW " + rowNumber, y, 0, w);
graphics.drawText("ROW NAME", y, 20, w);
graphics.drawText("row details", y + getFont().getHeight(), 20, w); */
}
public void drawRow(Graphics g, int x, int y, int width, int height) {
// Arrange the cell fields within this row manager.
layout(width, height);
// Place this row manager within its enclosing list.
setPosition(x, y);
// Apply a translating/clipping transformation to the graphics
// context so that this row paints in the right area.
g.pushRegion(getExtent());
// Paint this manager's controlled fields.
subpaint(g);
g.setColor(0x00CACACA);
g.drawLine(0, 0, getPreferredWidth(), 0);
// Restore the graphics context.
g.popContext();
}
public static String getDisplayName(Contact contact)
{
if (contact == null)
{
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " " + displayName;
}
return displayName;
}
}
return displayName;
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
/*if (listField == list)
{
//If index is out of bounds an exception will be thrown,
//but that's the behaviour we want in that case.
//return blackBerryContacts.elementAt(index);
_listData = (Vector) blackBerryContacts.elementAt(index);
return _listData.elementAt(index);
}
return null;*/
}
//Returns the first occurence of the given String, bbeginning the search at index,
//and testing for equality using the equals method.
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
//return _listData.indexOf(p, s);
return -1;
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Graphics.getScreenWidth();
//return Display.getWidth();
}
public void fieldChanged(Field field, int context) {
boolean mProgrammatic = false;
if (!mProgrammatic) {
mProgrammatic = true;
CheckboxField cbField = (CheckboxField) field;
int index = blackBerryContacts.indexOf(cbField);
if (cbField.getChecked())
{
for(int i=0;i<blackBerryContacts.size();i++)
{
Dialog.inform("Selected::" + cbField.getLabel());
sbi=new StringBuffer();
sbi.append(cbField.getLabel());
}
}
mProgrammatic = false;
}
}
This code may be improved with:
Using ListField instead of VerticalFieldManager + CheckboxField array (ListField is much more faster, 100+ controls may slow down UI)
Using simple array instead of vector in list data (it's faster)
Moving contacts load from UI thread (we should aware of blocking UI thread with heavy procedures like IO, networking or work with contact list)
Actually using ListField with two line rows has one issue: we have to set the same height for all rows in ListField. So there always will be two lines per row, no matter if we will use second line or not. But it's really better than UI performance issues.
See code:
public class CheckboxListField extends MainScreen implements
ListFieldCallback {
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private Vector mContacts;
private MenuItem mMenuItemToggle = new MenuItem(
"Change Option", 0, 0) {
public void run() {
toggleItem();
};
};
private MenuItem mMenuItemGet = new MenuItem("Get", 0,
0) {
public void run() {
StringBuffer sbi = new StringBuffer();
for (int i = 0; i < mListData.length; i++) {
ChecklistData checkboxField = mListData[i];
if (checkboxField.isChecked()) {
sbi.append(checkboxField.getStringVal())
.append("\n");
}
}
Dialog.inform("Selected checkbox text::\n"
+ sbi);
}
};
// A class to hold the Strings in the CheckBox and it's checkbox state
// (checked or unchecked).
private class ChecklistData {
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
private void toggleChecked() {
_checked = !_checked;
}
}
CheckboxListField() {
// toggle list field item on navigation click
mListField = new ListField() {
protected boolean navigationClick(int status,
int time) {
toggleItem();
return true;
};
};
// set two line row height
mListField.setRowHeight(getFont().getHeight() * 2);
mListField.setCallback(this);
add(mListField);
// load contacts in separate thread
loadContacts.run();
}
protected Runnable loadContacts = new Runnable() {
public void run() {
reloadContactList();
// fill list field control in UI event thread
UiApplication.getUiApplication().invokeLater(
fillList);
}
};
protected Runnable fillList = new Runnable() {
public void run() {
int size = mContacts.size();
mListData = new ChecklistData[size];
for (int i = 0; i < mContacts.size(); i++) {
BlackBerryContact item = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(item);
mListData[i] = new ChecklistData(
displayName, false);
}
mListField.setSize(size);
}
};
protected void toggleItem() {
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
// Invalidate the modified row of the ListField.
mListField.invalidate(index);
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(mListField
.getSelectedIndex());
// process selected contact here
}
}
protected void makeMenu(Menu menu, int instance) {
menu.add(mMenuItemToggle);
menu.add(mMenuItemGet);
super.makeMenu(menu, instance);
}
private boolean reloadContactList() {
try {
ContactList contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
Enumeration allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
return true;
} catch (PIMException e) {
return false;
}
}
// Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
Object obj = this.get(list, index);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked()) {
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
rowString.append(Characters.BALLOT_BOX);
}
// Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
// Draw the text.
graphics.drawText(rowString.toString(), 0, y,
0, w);
String secondLine = "Lorem ipsum dolor sit amet, "
+ "consectetur adipiscing elit.";
graphics.drawText(secondLine, 0, y
+ getFont().getHeight(),
DrawStyle.ELLIPSIS, w);
} else {
graphics.drawText("No rows available.", 0, y,
0, w);
}
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(
Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " "
+ displayName;
}
return displayName;
}
}
return displayName;
}
// Returns the object at the specified index.
public Object get(ListField list, int index) {
Object result = null;
if (mListData.length > index) {
result = mListData[index];
}
return result;
}
// Returns the first occurrence of the given String,
// beginning the search at index, and testing for
// equality using the equals method.
public int indexOfList(ListField list, String p, int s) {
return -1;
}
// Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
// return Display.getWidth();
}
}
Have a nice coding!

BlackBerry Alarm Integeration

Below is my application code. i want alarm to ring on my blackberry on every 6 of this month whether this apllication is running or not. please guide me in details i am a beginner.
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.*;
import net.rim.device.api.util.*;
import java.util.*;
import java.lang.String.*;
public class ListChk extends UiApplication
{
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
String getCompany;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private AutoTextEditField company;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
private ButtonField search;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
ListChk objListChk = new ListChk();
objListChk.enterEventDispatcher();
}//end of main of ListChk
public ListChk()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
company = new AutoTextEditField("Company: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
// A button that saves the the user data persistently when it is clicked
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
// a button which closes the entire application when clicked
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
// A button that shows the List of all Data being stored persistently
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
// pushing the next screen
pushScreen(new ListScreen());
}
});
search = new ButtonField("Search",ButtonField.CONSUME_CLICK);
search.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
pushScreen(new SearchScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(company);
mainScreen.add(gender);
mainScreen.add(status);
// Addning horizontal field manager
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
//adding buttons to the main screen in Horizontal field manager
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
horizontal.add(search);
//Adding the horizontal field manger to the screen
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
Dialog.alert("Closing Application");
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
getCompany = (info.getElement(StoreInfo.setCompany));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.setCompany, company.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
company.setText(null);
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public static final int setCompany = 5;
public StoreInfo()
{
_elements = new Vector(6);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String getUserFirstName;
String getUserLastName;
String getUserEmail;
String getUserGender;
String getUserStatus;
String getUserCompany;
String[] setData ;
String getData = new String();
String collectData = "";
ObjectListField fldList;
int counter = 0;
private ButtonField btnBack;
public ListScreen()
{
setTitle(new LabelField("Showing Data",LabelField.NON_FOCUSABLE));
//getData = myList();
//Dialog.alert(getData);
// setData = split(getData,"$");
// for(int i = 0;i<setData.length;i++)
// {
// add(new RichTextField(setData[i]+"#####"));
// }
showList();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK|ButtonField.FIELD_HCENTER);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void showList()
{
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLLBAR|HorizontalFieldManager.HORIZONTAL_SCROLL);
//SeparatorField spManager = new SeparatorField();
LabelField lblcheck = new LabelField("check",LabelField.NON_FOCUSABLE);
getData = myList();
setData = split(getData,"$");
fldList = new ObjectListField(ObjectListField.MULTI_SELECT);
fldList.set(setData);
//fldList.setEmptyString("heloo", 12);
//hfManager.add(lblcheck);
hfManager.add(fldList);
//hfManager.add(spManager);
add(hfManager);
addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = fldList.getSelectedIndex();
String item = (String)fldList.get(fldList, selectedIndex);
pushScreen(new ShowDataScreen(item));
}
});
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
public String myList()
{
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--,counter++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
//StoreInfo info = (StoreInfo)_data.lastElement();
getUserFirstName = (info.getElement(StoreInfo.NAME));
getUserLastName = (info.getElement(StoreInfo.LastNAME));
//getUserEmail = (info.getElement(StoreInfo.EMail));
//getUserGender = (info.getElement(StoreInfo.GenDer));
//getUserStatus = (info.getElement(StoreInfo.setStatus));
getUserCompany = (info.getElement(StoreInfo.setCompany));
collectData = collectData + getUserFirstName+" "+getUserLastName+" "+getUserCompany+ "$";
}
}
}
catch(Exception e){}
return collectData;
}//end of myList method
public boolean onClose()
{
System.exit(0);
return true;
}
}//end of class ListScreen
class ShowDataScreen extends MainScreen
{
String getFirstName;
String getLastName;
String getCompany;
String getEmail;
String getGender;
String getStatus;
String[] getData;
public ShowDataScreen(String data)
{
getData = split(data," ");
getFirstName = getData[0];
getLastName = getData[1];
getCompany = getData[2];
_data = (Vector) store.getContents();
try
{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
if (!_data.isEmpty())
{
if((getFirstName.equalsIgnoreCase(info.getElement(StoreInfo.NAME))) && (getLastName.equalsIgnoreCase(info.getElement(StoreInfo.LastNAME))) && (getCompany.equalsIgnoreCase(info.getElement(StoreInfo.setCompany))))
{
getEmail = info.getElement(StoreInfo.EMail);
getGender = info.getElement(StoreInfo.GenDer);
getStatus = info.getElement(StoreInfo.setStatus);
HorizontalFieldManager hfManager = new HorizontalFieldManager(HorizontalFieldManager.NON_FOCUSABLE);
AutoTextEditField name = new AutoTextEditField("Name: ",getFirstName+" "+getLastName);
AutoTextEditField email = new AutoTextEditField("Email: ",getEmail);
AutoTextEditField company = new AutoTextEditField("Company: ",getCompany);
AutoTextEditField Gender = new AutoTextEditField("Gender: ",getGender);
AutoTextEditField status = new AutoTextEditField("Status: ",getStatus);
add(name);
add(email);
add(company);
add(Gender);
add(status);
}
}
}//end of for loop
}//end of try
catch(Exception e){}
//Dialog.alert("fname is "+getFirstName+"\nlastname = "+getLastName+" company is "+getCompany);
}
public String[] split(String inString, String delimeter) {
String[] retAr;
try {
Vector vec = new Vector();
int indexA = 0;
int indexB = inString.indexOf(delimeter);
while (indexB != -1) {
vec.addElement(new String(inString.substring(indexA, indexB)));
indexA = indexB + delimeter.length();
indexB = inString.indexOf(delimeter, indexA);
}
vec.addElement(new String(inString.substring(indexA, inString
.length())));
retAr = new String[vec.size()];
for (int i = 0; i < vec.size(); i++) {
retAr[i] = vec.elementAt(i).toString();
}
} catch (Exception e) {
String[] ar = { e.toString() };
return ar;
}
return retAr;
}//end of Split Method
}
class SearchScreen extends MainScreen
{
private ButtonField btnFirstName;
private ButtonField btnLastName;
private ButtonField btnSearch;
private ButtonField btnEmail;
private SeparatorField sp;
String userName;
HorizontalFieldManager hr = new HorizontalFieldManager();
public AutoTextEditField searchField;
public SearchScreen()
{
sp = new SeparatorField();
setTitle(new LabelField("your Search Options"));
add(new RichTextField("Search by : "));
btnFirstName = new ButtonField("First Name",ButtonField.CONSUME_CLICK);
hr.add(btnFirstName);
btnFirstName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//HorizontalFieldManager hrs = new HorizontalFieldManager();
searchField = new AutoTextEditField("First Name: ","ali");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new FirstnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
//hrs.add(sp);
}
});
btnLastName = new ButtonField("Last Name",ButtonField.CONSUME_CLICK);
hr.add(btnLastName);
btnLastName.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Last Name: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new LastnameScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
btnEmail = new ButtonField("Email",ButtonField.CONSUME_CLICK);
hr.add(btnEmail);
btnEmail.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int Context)
{
searchField = new AutoTextEditField("Email: ","");
add(searchField);
btnSearch = new ButtonField("Search",ButtonField.CONSUME_CLICK);
btnSearch.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
//Dialog.alert(searchField.getText());
pushScreen(new EmailScreen(searchField.getText()));
//FirstnameScreen obj = new FirstnameScreen();
//obj.name= searchField.getText();
}
});
add(btnSearch);
}
});
add(hr);
}
void myShow()
{
Dialog.alert(searchField.getText());
}
}
class FirstnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public FirstnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchFirstName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchFirstName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
firstUserName = (info.getElement(StoreInfo.NAME));
if(firstUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class LastnameScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public LastnameScreen(String name)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+name));
userName = name;
searchLastName();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
add(btnBack);
}
public void searchLastName()
{
ButtonField btnDelete;
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
//mGrid.add(new ButtonField("Delete"));
//SeparatorField sps = new SeparatorField();
//mGrid.add(sps);
add(mGrid);
_data = (Vector) store.getContents();
try {
for (int i = _data.size() - 1; i > -1; i--) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
lastUserName = (info.getElement(StoreInfo.LastNAME));
if(lastUserName.equalsIgnoreCase(userName))
{
// if not empty
// create a new object of Store Info class
// stored information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
final int sn = i;
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
btnDelete = new ButtonField("Delete",ButtonField.CONSUME_CLICK);
btnDelete.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
_data.removeElementAt(sn);
}
});
add(btnDelete);
// SeparatorField sps1 = new SeparatorField();
//mGrid.add(sps1);
}
}
}
} catch (Exception e) {
}
}
}
class EmailScreen extends MainScreen
{
String userName;
private Manager mGrid;
String firstUserName;
String lastUserName;
String userEmail;
String userGender;
String userStatus;
ButtonField btnBack;
Font font;
public EmailScreen(String mail)
{
setTitle(new LabelField("your Search Results"));
add(new RichTextField("Search results for"+mail));
userName = mail;
searchEmail();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBa
What are the benefits of integrating with the built-in alarm application? Would it be better for your application to place an event in the device's calendar and make the event show a reminder?
If you have to have a more prominent alarm, why not do it yourself? An alarm is an action the phone does (either make a sound and/or vibrate) that shows on the screen why it is taking that action and the action stops when someone responds to it.
Can you just make an app that starts in the background, checks the day, and makes a sound/vibrates on that day?
The default Alarm app on my phone only supports one time to ring. If I set it to wake me up at 4 a.m., but your app reschedules the alarm on my phone for 8 a.m., you would instantly lose a customer (after I wake up 4 hours too late).

Resources