BlackBerry Java Plugin for Eclipse - .net web service - blackberry

I have a web service that accepts a username and password and if the login credentials are correct, it returns the user's name, status, image and last known gps coordinates.
As for now I am stuck in the "login" button where the application neither proceeds nor throws any error. Simulator produces no result and I am unable to load the app on to my handset.
package mypackage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.Hashtable;
import javacard.framework.UserException;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.Location;
import javax.microedition.location.LocationProvider;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xmlpull.v1.XmlPullParserException;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.component.pane.TitleView;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.image.Image;
public class LoginTest extends UiApplication
{
public static void main(String[] args)
{
//Create a new instance of the app
//and start the app on the event thread.
LoginTest app = new LoginTest();
app.enterEventDispatcher();
}
public LoginTest()
{
//Display a new screen.
pushScreen(new LoginTestScreen());
}
}
//Create a new screen that extends MainScreen and provides
//behaviour similar to that of other apps.
final class LoginTestScreen extends MainScreen
{
//declare variables for later use
private InfoScreen _infoScreen;
private ObjectChoiceField choiceField;
private int select;
BasicEditField username;
PasswordEditField passwd;
CheckboxField checkBox1;
ButtonField loginBtn;
Hashtable persistentHashtable;
PersistentObject persistentObject;
static final long KEY = 0x9df9f961bc6d6baL;
// private static final String URL="http://prerel.track24elms.com/Android/T24AndroidLogin.asmx";
String strResult;
public LoginTestScreen()
{
//Invoke the MainScreen constructor.
super();
//Add a screen title.
setTitle("Track24ELMS");
LabelField login = new LabelField("ELMS Login", LabelField.FIELD_HCENTER);
login.setFont(Font.getDefault().derive(Font.BOLD, 30));
login.setMargin(10, 0, 20, 0); //To leave some space from top and bottom
HorizontalFieldManager user = new HorizontalFieldManager();
user.setMargin(0, 0, 10, 0);
HorizontalFieldManager pass = new HorizontalFieldManager();
pass.setMargin(0, 0, 20, 0);
HorizontalFieldManager checkbox = new HorizontalFieldManager();
checkbox.setMargin(0, 0, 30, 0);
HorizontalFieldManager btns = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
LabelField usernameTxt = new LabelField("Username :");
LabelField passwordTxt = new LabelField("Password :");
username = new BasicEditField();
passwd = new PasswordEditField();
loginBtn = new ButtonField("Login", ButtonField.CONSUME_CLICK);
// btn.setChangeListener(new view listener);
//checkBox1 = new CheckboxField("Remember me", false,Field.FOCUSABLE);
checkBox1 = new CheckboxField("Remember me",false);
user.add(usernameTxt);
user.add(username);
pass.add(passwordTxt);
pass.add(passwd);
//checkbox.add(checkBox1);
btns.add(loginBtn);
add(login);
add(user);
add(pass);
add(checkBox1);
add(btns);
// loginBtn.setChangeListener(btnlistener);
}
public void saveChecked() {
persistentHashtable.put("", username.getText());
persistentHashtable.put("", passwd.getText());
persistentHashtable.put("BoolData", new Boolean(checkBox1.getChecked()));
persistentObject.commit();
}
FieldChangeListener btnlistener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
//Open a new screen
String uname = username.getText();
String pwd = passwd.getText();
//If there is no input
if (uname.length() == 0 || pwd.length()==0) {
Dialog.alert("One of the textfield is empty!");
} else {
final String METHOD_NAME = "ValidateCredentials";
final String NAMESPACE = "http://tempuri.org/";
final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
final String URL = "http://prerel.track24elms.com/Android/T24AndroidLogin.asmx";
SoapObject resultRequestSOAP = null;
HttpConnection httpConn = null;
HttpTransport httpt;
System.out.println("The username" + uname + "password" + pwd );
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//String usernamecode = Base64.encode(username.getBytes());
//String pwdEncodeString = Base64.encode(passwd.getBytes());
request.addProperty("Username", "abc");//First parameter is tag name provided by web service
request.addProperty("Password", "xyz");
System.out.println("The request is=======" + request.toString());
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
envelope.setOutputSoapObject(request);
System.out.println("The envelope has the value++++"+ envelope.toString());
/* URL+ Here you can add paramter so that you can run on device,simulator etc. this will work only for wifi */
httpt = new HttpTransport(URL+ ";deviceside=true;ConnectionUID=S TCP-WiFi");
httpt.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
httpt.debug = true;
try
{
System.out.println("SOAP_ACTION == " + SOAP_ACTION);
httpt.call(SOAP_ACTION, envelope);
System.out.println("the tranport" + httpt.toString());
resultRequestSOAP = (SoapObject) envelope.bodyIn;
System.out.println("result == " + resultRequestSOAP);
}
catch (IOException e) {
System.out.println("The exception is IO==" + e.getMessage());
} catch (XmlPullParserException e) {
System.out.println("The exception xml parser example==="
+ e.getMessage());
}
System.out.println( resultRequestSOAP);
UiApplication.getUiApplication().pushScreen(new InfoScreen()); //Open a new Screen
}
}
};
//To display a dialog box when a BlackBerry device user
//closes the app, override the onClose() method.
public boolean onClose()
{
if(checkBox1.equals("true"))
{
persistentObject = PersistentStore.getPersistentObject(KEY);
if (persistentObject.getContents() == null) {
persistentHashtable = new Hashtable();
persistentObject.setContents(persistentHashtable);
}
else {
persistentHashtable = (Hashtable)persistentObject.getContents();
}
if (persistentHashtable.containsKey("EditData")) {
username.setText((String)persistentHashtable.get("EditData"));
}
if (persistentHashtable.containsKey("BoolData")) {
Boolean booleanObject = (Boolean)persistentHashtable.get("BoolData");
checkBox1.setChecked(booleanObject.booleanValue());
if(booleanObject.booleanValue()==true){
saveChecked();
}
}
}
Dialog.alert("Goodbye!");
System.exit(0);
return true;
}
//Create a menu item for BlackBerry device users to click to see more
//information about the city they select.
private MenuItem _viewItem = new MenuItem("More Info", 110, 10)
{
public void run()
{
//Store the index of the city the BlackBerry device user selects
select = choiceField.getSelectedIndex();
//Display a new screen with information about the
//city the BlackBerry device user selects
_infoScreen = new InfoScreen();
UiApplication.getUiApplication().pushScreen(_infoScreen);
}
};
//Create a menu item for BlackBerry device users to click to close
//the app.
private MenuItem _closeItem = new MenuItem("Close", 200000, 10)
{
public void run()
{
onClose();
}
};
//To add menu items to the menu of the app,
//override the makeMenu method.
//Create an inner class for a new screen that displays
//information about the city a BlackBerry device user selects.
private class InfoScreen extends MainScreen
{
public InfoScreen()
{
super();
setTitle("Itinerary");
LabelField login = new LabelField("Employee Itinerary", LabelField.FIELD_HCENTER);
Bitmap bitmap = Bitmap.getBitmapResource("img1.jpg");
EditField statusMsg = new EditField("Status Message", "Update status here");
}
}
}

In the code you posted, nothing is ever setup to respond to your login button being pressed.
First of all, let's remove this anonymous class that implements FieldChangeListener:
FieldChangeListener btnlistener = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
and make it like this:
private class LoginButtonListener implements FieldChangeListener {
public void fieldChanged(Field field, int context) {
// no change to the content of this method!
}
}
and in the constructor for LoginTestScreen, instantiate it, and hook it up to the login button:
loginBtn = new ButtonField("Login", ButtonField.CONSUME_CLICK);
loginBtn.setChangeListener(new LoginButtonListener());
it looks like you were close, in the commented out code. Just needed a little more. Try that, and report back!
Note: you could make it work with the anonymous button listener class you originally had. I just don't like the readability of anonymous classes when they get that big, especially since your btnListener member was declared in a totally different place than all your other ones. The real missing piece was the call to setChangeListener. I just wanted to differentiate what I'm recommending, from what's needed.

Related

how to give my page slide animation in blackberry?

I'm creating a BlackBerry application, and now I want to present an animation when I click on an image button. In my application, I use a splash screen, and after that a login page is shown. When I click on my login page's submit button, a home screen is displayed, and there I want to show a slide animation.
This is my code:
public class LoginPage extends MainScreen implements FieldChangeListener {
public TextField tf_username;
public TextField tf_password;
private Bitmap[] img1;
public LabelField labeluser;
public LabelField labelpass;
public static String strUsername = "";
public static String strPassword = "";
public CheckboxField objRemembercheckbox;
private ImageButton btn_login;
private ImageButton btn_clear;
public BitmapField loading = new BitmapField(Bitmap.getBitmapResource("login-bar.png"));
public H_FieldManager hfm_btn;
public VerticalFieldManager vfm_user, vfm_pass;
public PleaseWaitPopupScreen waitPopupScreen = null;
public VerticalFieldManager vfmMainManager;
public static boolean loginFlag = false;
public static boolean flagOutletButton;
public RecordStore objLoginRecordStore;
private String login_record_Store_Name = "LoginRMS";
public LoginPage() { // TODO Auto-generated constructor stub super(USE_ALL_WIDTH | USE_ALL_HEIGHT); setTitle(loading);
try {
Background bg = BackgroundFactory.createSolidTransparentBackground(
Color.BLUE, 100); getMainManager().setBackground(bg);
} catch (Exception e) { // TODO: handle exception }
labeluser = new LabelField("Enter Username : ", Field.FIELD_LEFT); labeluser.setMargin(10, 0, 0, 10); labeluser.setColor(Color.BLACK);
tf_username = new TextField(TextField.TYPE_PLAIN, Field.FIELD_HCENTER);
labelpass = new LabelField("Enter Password : ", Field.FIELD_LEFT); labelpass.setMargin(10, 0, 0, 10); labelpass.setColor(Color.BLACK);
tf_password = new TextField(TextField.TYPE_PASSWORD,
Field.FIELD_HCENTER);
objRemembercheckbox = new CheckboxField("Remember Me", false); objRemembercheckbox.setMargin(10, 0, 0, 10);
img1 = new Bitmap[3]; img1[0] = Bitmap.getBitmapResource("btn-hover.png"); img1[1] = Bitmap.getBitmapResource("btn.png"); img1[2] = Bitmap.getBitmapResource("btn.png");
btn_login = new ImageButton(img1, "Login", Field.FIELD_LEFT); btn_login.setColor(Color.WHITE); btn_clear = new ImageButton(img1, "Clear", Field.FIELD_RIGHT); btn_clear.setColor(Color.WHITE);
hfm_btn = new H_FieldManager(btn_login, btn_clear, true,
Field.FIELD_HCENTER); vfm_user = new VerticalFieldManager(); vfm_user.add(labeluser); vfm_user.add(tf_username);
vfm_pass = new VerticalFieldManager(); vfm_pass.add(labelpass); vfm_pass.add(tf_password); add(vfm_user); add(vfm_pass); add(objRemembercheckbox); add(hfm_btn);
btn_login.setChangeListener(this); btn_clear.setChangeListener(this);
}
public void fieldChanged(Field field, int context) { // TODO Auto-generated method stub if (field == btn_clear) { tf_username.setText(" "); tf_password.setText(" ");
} else if (field == btn_login) { login(); }
}
public void login() {
try {
LoginPage.strUsername = tf_username.getText().toString(); System.out.println("strUsername==" + strUsername); LoginPage.strPassword = tf_password.getText().toString(); System.out.println("strPassword==" + strPassword);
if (strUsername.length() == 0 || strPassword.length() == 0
|| strUsername == null || strPassword == null) {
Dialog.alert("You must enter credentials");
invalidate(); } else {
// strUsername=username.getText();
// strPassword=password.getText();
try {
waitPopupScreen = new PleaseWaitPopupScreen("Please wait..");
UiApplication.getUiApplication()
.pushScreen(waitPopupScreen);
new Thread() {
public void run() {
ConnectToServer objConnectToServer = new ConnectToServer();
loginFlag = objConnectToServer.loginCheck(
strUsername, strPassword);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
UiApplication.getUiApplication()
.popScreen(waitPopupScreen);
if (loginFlag == true) {
LoginPage.flagOutletButton = false;
System.out
.println("Calling getOutletInfo");
HomeScreen objHome= new HomeScreen ();
UiApplication
.getUiApplication()
.pushScreen(objHome);
}
else {
Dialog.alert("Username Or Password Is Incorrect");
}
}
});
};
}.start();
// ConnectToServer objConnectToServer=new ConnectToServer();
//
// loginFlag=objConnectToServer.loginCheck(strUsername,
// strPassword);
System.out.println("loginFlag==" + loginFlag);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
} catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
}
}
Please suggest how to implement the slide animation.
Thank you.
Try following links:
TransitionContext - The TransitionContext class contains all the necessary data to
uniquely describe a transition animation between two screens.
BlackBerry Screen Transition Sample Code
BlackBerry Java Application Screen Transitions - Sample Application Overview
Creating a screen transition Code sample

Blackberry BarcodeScanner - barcodeDecode switch to MainScreen

Can somebody tell me how to close the Screen (which opened by the BarcodeScanner) and show the mainscreen again after the barcodeDecoded method was invoked?
I can't get it right. I tried a lot, one of them was this:
public void barcodeDecoded(String rawText) {
final String result = rawText;
try
{
final UiApplication ui = UiApplication.getUiApplication();
final MainScreen current = (MainScreen) ui.getActiveScreen();
System.out.println("Current: " + current.toString());
if (UiApplication.isEventDispatchThread()) {
getText(result);
ui.popScreen(current);
System.out.println("Close Window by active screen");
ui.pushScreen(_frm);
System.out.println("Push screen frmMain");
}else{
ui.invokeLater(new Runnable() {
public void run() {
getText(result); <-- Abstract method to use within the main app.
ui.popScreen(current);
ui.pushScreen(_frm);
}
});
}
}catch(Exception err){
System.out.println(err.getMessage());
}
}
the abstract method when i start the Scanner
private MenuItem mnuCamera = new MenuItem("Scan", 1, 1){
public void run(){
frmMain f = (frmMain)getScreen();
_decode = new BarcodeDecoderClass(f) {
public void getText(String tekst) {
setScannedText(tekst);
}
};
_decode.Start();
}
};
Ok, for the people who are stuck with the same problem. I found it out. Below you find the complete code:
The BarcodeScanner class:
public abstract class BarcodeDecoderClass implements BarcodeDecoderListener {
private Hashtable _hints;
private Vector _formats;
private BarcodeScanner _scanner;
private BarcodeDecoder _decoder;
private Field _viewFinder;
private MainScreen _screen;
public abstract void getText(String tekst, Screen screen);
public BarcodeDecoderClass(){
_hints = new Hashtable();
_formats = new Vector();
_formats.addElement(BarcodeFormat.QR_CODE);
_hints.put(DecodeHintType.POSSIBLE_FORMATS, _formats);
_decoder = new BarcodeDecoder(_hints);
try
{
_scanner = new BarcodeScanner(_decoder, this);
_scanner.getVideoControl().setDisplayFullScreen(true);
_viewFinder = _scanner.getViewfinder();
}catch(Exception err){
System.out.println(err.getMessage());
}
}
public void Start(){
try
{
_screen = new MainScreen();
_screen.add(_viewFinder);
UiApplication.getUiApplication().pushScreen(_screen);
_scanner.startScan();
}catch(Exception err){
System.out.println(err.getMessage());
}
}
public synchronized void Close(){
if(_scanner.isScanning()){
try{
_scanner.stopScan();
}catch(Exception err){
Dialog.alert(err.getMessage());
}
}
_scanner.getVideoControl().setVisible(false);
_scanner.getPlayer().close();
}
public void barcodeDecoded(String rawText) {
try
{
getText(rawText, _screen);
}catch(Exception err){
System.out.println(err.getMessage());
}
}
}
The MainScreen from which I start the BarcodeScanner (i just copied the method)
private MenuItem mnuCamera = new MenuItem("Scan", 1, 1){
public void run(){
final Screen f = getScreen();
_decode = new BarcodeDecoderClass() {
public void getText(String tekst, final Screen _screen) {
setScannedText(tekst);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_decode.Close();
_screen.close();
}
});
}
};
_decode.Start();
}
};
May be help full this code.
import java.util.Hashtable;
import java.util.Vector;
import net.rim.device.api.barcodelib.BarcodeDecoder;
import net.rim.device.api.barcodelib.BarcodeDecoderListener;
import net.rim.device.api.barcodelib.BarcodeScanner;
import net.rim.device.api.system.KeyListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.FullScreen;
import net.rim.device.api.ui.container.MainScreen;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
public class BarcodeScanSample extends MainScreen{
private FullScreen _barcodeScreen;
private BarcodeScanner _scanner;
private LabelField lblBarcodeText;
private ButtonField btnScan;
public BarcodeScanSample(String barcodeText){
lblBarcodeText = new LabelField(barcodeText);
add(lblBarcodeText);
btnScan = new ButtonField("Scan");
btnScan.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
scanBarcode();
}
});
add(btnScan);
}
private void scanBarcode() {
// If we haven't scanned before, we will set up our barcode scanner
if (_barcodeScreen == null) {
// First we create a hashtable to hold all of the hints that we can
// give the API about how we want to scan a barcode to improve speed
// and accuracy.
Hashtable hints = new Hashtable();
// The first thing going in is a list of formats. We could look for
// more than one at a time, but it's much slower. and set Barcode Format.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
formats.addElement(BarcodeFormat.CODE_128);
formats.addElement(BarcodeFormat.CODE_39);
formats.addElement(BarcodeFormat.DATAMATRIX);
formats.addElement(BarcodeFormat.EAN_13);
formats.addElement(BarcodeFormat.EAN_8);
formats.addElement(BarcodeFormat.ITF);
formats.addElement(BarcodeFormat.PDF417);
formats.addElement(BarcodeFormat.UPC_A);
formats.addElement(BarcodeFormat.UPC_E);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// We will also use the "TRY_HARDER" flag to make sure we get an
// accurate scan
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
// We create a new decoder using those hints
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Finally we can create the actual scanner with a decoder and a
// listener that will handle the data stored in the barcode. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new MyBarcodeDecoderListener());
_barcodeScreen = new MyBarcodeScannerViewScreen(_scanner);
} catch (Exception e) {
System.out.println("Could not initialize barcode scanner: " + e);
return;
}
}
// If we get here, all the barcode scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
try {
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_barcodeScreen);
} catch (Exception e) {
System.out.println("Could not start scan: " + e);
}
}
/***
* MyBarcodeScannerViewScreen
* <p>
* This view screen is simply an extension of MainScreen that will hold our
* scanner's viewfinder, and handle cleanly stopping the scan if the user
* decides they want to abort via the back button.
*
* #author PBernhardt
*
*/
private class MyBarcodeScannerViewScreen extends MainScreen {
public MyBarcodeScannerViewScreen(BarcodeScanner scanner) {
super();
try {
// Get the viewfinder and add it to the screen
_scanner.getVideoControl().setDisplayFullScreen(true);
Field viewFinder = _scanner.getViewfinder();
this.add(viewFinder);
// Create and add our key listener to the screen
this.addKeyListener(new MyKeyListener());
} catch (Exception e) {
System.out.println("Error creating view screen: " + e);
}
}
/***
* MyKeyListener
* <p>
* This KeyListener will stop the current scan cleanly when the back
* button is pressed, and then pop the viewfinder off the stack.
*
* #author PBernhardt
*
*/
private class MyKeyListener implements KeyListener {
public boolean keyDown(int keycode, int time) {
// First convert the keycode into an actual key event, taking
// modifiers into account
int key = Keypad.key(keycode);
// From there we can compare against the escape key constant. If
// we get it, we stop the scan and pop this screen off the stack
if (key == Keypad.KEY_ESCAPE) {
try {
_scanner.stopScan();
} catch (Exception e) {
System.out.println("Error stopping scan: " + e);
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_barcodeScreen);
}
});
return true;
}
// Otherwise, we'll return false so as not to consume the
// keyDown event
return false;
}
// We will only act on the keyDown event
public boolean keyChar(char key, int status, int time) {
return false;
}
public boolean keyRepeat(int keycode, int time) {
return false;
}
public boolean keyStatus(int keycode, int time) {
return false;
}
public boolean keyUp(int keycode, int time) {
return false;
}
}
}
/***
* MyBarcodeDecoderListener
* <p>
* This BarcodeDecoverListener implementation tries to open any data encoded
* in a barcode in the browser.
*
* #author PBernhardt
*
**/
private class MyBarcodeDecoderListener implements BarcodeDecoderListener {
public void barcodeDecoded(final String rawText) {
// First pop the viewfinder screen off of the stack so we can see
// the main app
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_barcodeScreen);
}
});
_barcodeScreen.invalidate();
//Display this barcode on LabelField on BarcodeScanSample MainScreen we can also set whatever field here.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen();
UiApplication.getUiApplication().pushScreen(new BarcodeScanSample(rawText));
_barcodeScreen.close();
_barcodeScreen=null;
}
});
}
}
}

About ListField in Blackberry

Plz give the code or function how to clear the ListField and update the ListField .
Suppose i want to display some multiple text( Project Name, Project Manager )extracted from JSON object , in a ListField.
I am able to display this strings in the ListField but one more feature i need to add ie.. above the ListField there should be a ButtonField and when the user clicks on the ButtonField the ListField should display the string in sorted manner base on Project Name. So i need to clear the ListField
Code for NetworkingMainScreen is
package src1;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.system.*;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import java.util.Vector;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.UiApplication;
class NetworkingMainScreen extends MainScreen
{
private EditField urlField;
private BitmapField imageOutputField;
private RichTextField textOutputField;
private ListField prjctlist_Field;
private Vector prjct_list_v = new Vector();
VerticalFieldManager vfm;
private String prjts;
public int total_prjcts;
JSONArray data_json_array;
JSONObject outer;
ListField myList;
private Vector v_prj_title;
private Vector v_prj_mgr;
private Vector send_vector;
private Vector send_vector3;
private Vector send_vector4;
private String t1,t2;
public JSONArray jsArrPrjts;
ListCallBack callback;
ButtonField sort;
NetworkingMainScreen()
{
// Screen2 s = new Screen2();
// UiApplication.getUiApplication.pushScreen(s);
setTitle("Networking");
urlField = new EditField("URL:", "http://iphone.openmetrics.com/apps/mattson/api.html?action=login&user=Nathan&password=coffee00&server=exp.lcgpence.com;deviceside=true");
textOutputField = new RichTextField();
imageOutputField = new BitmapField();
add(urlField);
add(new SeparatorField());
add(new LabelField("Text retrieved:"));
add(textOutputField);
myList = new ListField();
callback = new ListCallBack();
myList.setRowHeight(80);
myList.setCallback(callback);
add(myList);
}
protected void makeMenu(Menu menu, int instance)
{
super.makeMenu(menu, instance);
menu.add(new MenuItem("Get", 10, 10) {
public void run() {
getURL();
}
});
}
private void getURL()
{
HttpRequestDispatcher dispatcher = new HttpRequestDispatcher(urlField.getText(),"GET", this);
dispatcher.start();
}
public void requestSucceeded(byte[] result, String contentType)
{
if (contentType.startsWith("text/")) {
synchronized (UiApplication.getEventLock())
{
String strResult = new String(result);
try
{
JSONObject joPrjt = new JSONObject(strResult);
String res_code = joPrjt.optString("responseCode");
if( res_code.equals("1"))
{
data_json_array = new JSONArray();
data_json_array = joPrjt.optJSONArray("data");
int s = data_json_array.length();
v_prj_title = new Vector();
v_prj_mgr = new Vector();
outer = new JSONObject();
for(int i=0; i<s; i++)
{
//outer = new JSONObject();
outer = data_json_array.getJSONObject(i);
String job_no = outer.optString("job_number");
String contract_date = outer.optString("contract_date");
String project_title = outer.optString("project_title");
String project_manager = outer.optString("project_manager");
String created_date = outer.optString("created_date");
String project_name = outer.optString("project_name");
v_prj_title.addElement(project_title);
v_prj_mgr.addElement(project_manager);
}
UiApplication.getUiApplication().pushScreen(new Screen2(v_prj_title,v_prj_mgr,0,v_prj_title,v_prj_mgr));
}
else
{
Dialog.alert("Web page connected but not the requested page");
}
}
catch(JSONException e)
{
e.printStackTrace();
System.out.println("key not found catched " + e);
}
}
}
else
{
synchronized (UiApplication.getEventLock()) {
Dialog.alert("Unknown content type: " + contentType);
}
}
}
public void requestFailed(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("Request failed. Reason: " + message);
}
});
}
}
Code for Screen2 is
package src1;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import java.util.Vector;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
class Screen2 extends MainScreen implements FieldChangeListener
{
JSONArray j_array;
JSONObject j_object;
CustomButtonField bf1;
Vector v_prj_title,v_prj_mgr,v_job_no,v_created_date,v_prj_name,send_vector;
Vector main_v_prj_title,main_v_prj_mgr;
String job_no,contract_date,project_title,project_manager,created_date,project_name;
VerticalFieldManager vfm;
ListField myList;
ListCallBack callback;
int pic_status;
int b;
String t1,t2;
String temp1,temp2,f1,f2;
// ListField prjctlist_Field;
Screen2(Vector v_prj_title2,Vector v_prj_mgr2,int pic_status,Vector main_v_prj_title_o2,Vector main_v_prj_mgr_o2)
{
this.main_v_prj_title = main_v_prj_title_o2;
this.main_v_prj_mgr = main_v_prj_mgr_o2;
this.v_prj_title = v_prj_title2;
this.v_prj_mgr = v_prj_mgr2;
this.pic_status = pic_status;
bf1 = new CustomButtonField("Name",pic_status,0);
bf1.setChangeListener(this);
vfm = new VerticalFieldManager();
vfm.add(bf1);
int s = v_prj_title.size();
myList = new ListField();
callback = new ListCallBack();
myList.setRowHeight(80);
myList.setCallback(callback);
for(int i=0;i<s;i++)
{
myList.insert(i);
t1 = v_prj_title.elementAt(i).toString();
send_vector = new Vector(2);
send_vector.addElement(t1);
t2 = v_prj_mgr.elementAt(i).toString();
send_vector.addElement(t2);
callback.insert(send_vector,i);
}
vfm.add(myList);
add(vfm);
}
public void fieldChanged(Field field, int context)
{
if(field == bf1)
{
if(pic_status == 0)
{
b =1;
int s = v_prj_title.size();
for(int i=0;i<s;i++)
{
for(int t=i+1;t<s;t++)
{
temp1 = (String)v_prj_title.elementAt(i);
temp2 = (String)v_prj_title.elementAt(t);
if(temp1.compareTo(temp2)>0)
{
//System.out.println("Comparision Executed :"+temp1 + " is greater than " + temp2);
f1 = (String)v_prj_mgr.elementAt(i);
f2 = (String)v_prj_mgr.elementAt(t);
v_prj_title.setElementAt(temp1,t);
v_prj_title.setElementAt(temp2,i);
v_prj_mgr.setElementAt(f1,t);
v_prj_mgr.setElementAt(f2,i);
}
}
}
UiApplication.getUiApplication().pushScreen(new Screen2(main_v_prj_title,main_v_prj_mgr,b,main_v_prj_title,main_v_prj_mgr));
}
if(pic_status == 1)
{
b=0;
UiApplication.getUiApplication().pushScreen(new Screen2(main_v_prj_title,main_v_prj_mgr,b,main_v_prj_title,main_v_prj_mgr));
}
}
}
}
one more thing i need to clearify is that in my above code firstly i have parsed the JSON object in NetworkingMainScreen and if the JSON parsing is success i have push a new screen name Screen2 passing the stored Vector to the Screen2. The Screen2 performs ListField drawings or should i perform the ListField drawing in NetworkingMainScreen class only.
For details about the items i need to display plz look **http://iphone.openmetrics.com/apps/mattson/api.html?action=login&user=Nathan&password=coffee00&server=exp.lcgpence.com&output=data**
Implement ListFieldCallback in your screen, you can then handle the drawing of your rows however you want in drawListRow.

Blackberry: saving ListField content and dirty state management

I have prepared a simple test case to demonstrate my problem.
It is just 1 file which will run instantly when added to a new project.
I would like to have a MainScreen displaying an editable list of items:
and when leaving this screen, the user should be asked - if she wants to save the modified list to persistent storage, by presenting the standard Save/Discard/Cancel-dialog:
I have added setDirty(true) to my menu items and the standard dialog does come up okay.
My problem is: I don't know how to clear the dirty flag after saving - in my current code the Save/Discard/Cancel-dialog comes again and again, even if I just view the ListField, without editing it.
src\mypackage\MyList.java:
package mypackage;
import java.util.*;
import net.rim.device.api.collection.*;
import net.rim.device.api.collection.util.*;
import net.rim.device.api.system.*;
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.ui.decor.*;
import net.rim.device.api.util.*;
public class MyList extends UiApplication implements FieldChangeListener {
MyScreen myScreen = new MyScreen();
public static void main(String args[]) {
MyList app = new MyList();
app.enterEventDispatcher();
}
public MyList() {
MainScreen titleScreen = new MainScreen();
titleScreen.setTitle("Click the button:");
ButtonField myButton = new ButtonField("Show the list", ButtonField.CONSUME_CLICK) ;
myButton.setChangeListener(this);
titleScreen.add(myButton);
pushScreen(titleScreen);
}
public void fieldChanged(Field field, int context) {
pushScreen(myScreen);
}
}
class MyScreen extends MainScreen {
ObjectListField myList = new ObjectListField();
static PersistentObject myStore;
static Vector myData;
static {
myStore = PersistentStore.getPersistentObject(0xb77f8e453754f37aL);
myData = (Vector) myStore.getContents();
if (myData == null) {
myData = new Vector();
myData.addElement("String 1");
myData.addElement("String 2");
myData.addElement("String 3");
myStore.setContents(myData);
}
}
public MyScreen() {
setTitle("Edit the list below:");
add(myList);
addMenuItem(addItem);
addMenuItem(editItem);
addMenuItem(removeItem);
}
// load data from persistent store into the ListField
private void loadData() {
// clear the ListField
myList.setSize(0);
// copy data from the Vector to the ListField
for (int i = myData.size() - 1; i >= 0; i--)
myList.insert(0, myData.elementAt(i));
}
// save data from the ListField into the persistent store
private void saveData() {
// clear the Vector
myData.removeAllElements();
// copy data from the ListField to the Vector
for (int i = myList.getSize() - 1; i >=0; i--)
myData.addElement(myList.get(myList, i));
synchronized(PersistentStore.getSynchObject()) {
myStore.commit();
}
}
protected void onUiEngineAttached(boolean attached) {
if (attached) {
loadData();
}
}
public void save() {
saveData();
// UPDATE: when I call setDirty(false); here, then
// the app starts displaying Save/Discard/Cancel dialog
// on its exit - so there must be a better way...
}
private final MenuItem addItem = new MenuItem("Add Item", 0, 0) {
public void run() {
String[] buttons = {"Add", "Cancel"};
Dialog myDialog = new Dialog("Add Item", buttons, null, 0, null);
EditField myEdit = new EditField("Item: ", "");
myDialog.add(myEdit);
if (myDialog.doModal() == 0) {
myList.insert(0, myEdit.getText());
setDirty(true);
}
}
};
private final MenuItem editItem = new MenuItem("Edit Item", 0, 0) {
public void run() {
String[] buttons = {"Save", "Cancel"};
Dialog myDialog = new Dialog("Edit Item", buttons, null, 0, null);
int index = myList.getSelectedIndex();
if (index == -1) {
return;
}
String selectedItem = (String) myList.get(myList, index);
EditField myEdit = new EditField("Item: ", selectedItem);
myDialog.add(myEdit);
if (myDialog.doModal() == 0) {
myList.set(index, myEdit.getText());
setDirty(true);
}
}
};
private final MenuItem removeItem = new MenuItem("Remove Item", 0, 0) {
public void run() {
String[] buttons = {"Delete", "Cancel"};
Dialog myDialog = new Dialog("Remove Item", buttons, null, 0, null);
int index = myList.getSelectedIndex();
if (index == -1) {
return;
}
String selectedItem = (String) myList.get(myList, index);
LabelField myLabel = new LabelField("Really delete " + selectedItem + "?");
myDialog.add(myLabel);
if (myDialog.doModal() == 0) {
myList.delete(index);
setDirty(true);
}
}
};
}
Please share your Blackberry 6 experience, advices in regard to persistent storage are also welcome.
In my real program I'm using KeywordFilterField for viewing a SortedReadableList, so from reading Blackberry docs I suppose, that I must always copy data between SortedReadableList and Vector - because the latter is persistable and the former is not?
setDirty(false) will clear the dirty flag if that is what you are after.

Blackberry - make a call from native address book

how to make a call from menu item appended in native book of BB('Call from ABC' option)?
Initiate call programmatically
For RIM OS 4.7 and lower use Invoke:
PhoneArguments phoneArgs = new PhoneArguments(PhoneArguments.ARG_CALL,
"555-5555");
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, phoneArgs);
For RIM OS 5.0 declared we can use Phone.initiateCall method:
Phone.initiateCall(Phone.getLineIds()[0], "519-555-0100");
See Make a call from a BlackBerry device application (multi-line environment)
Add custom menu item to BlackBerry application
To add your "Call via ABC" item to address book menu we need to do following:
implement custom item as an extension to ApplicationMenuItem
add instance of custom item to menu using ApplicationMenuItemRepository
before deploying to the real device, don't forget to sign your code (may take up to 2 weeks)
Now, implementing custom menu item:
class AdressBookMenuItem extends ApplicationMenuItem {
Contact mContact;
public AdressBookMenuItem(int order) {
super(order);
}
public Object run(Object context) {
if (context instanceof Contact) {
mContact = (Contact) context;
if (0 < mContact.countValues(Contact.TEL)) {
String phone = mContact.getString(Contact.TEL, 0);
PhoneArguments args = new PhoneArguments(
PhoneArguments.ARG_CALL, phone);
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, args);
} else {
Dialog.alert("This contact has no phone number");
}
}
return null;
}
public String toString() {
return "Call via ABC";
}
}
Now add it to the address book:
AdressBookMenuItem menuItem = new AdressBookMenuItem(0);
ApplicationMenuItemRepository repository =
ApplicationMenuItemRepository.getInstance();
long id = ApplicationMenuItemRepository.MENUITEM_ADDRESSBOOK_LIST;
repository.addMenuItem(id, menuItem);
Putting All Together
Run application
Press Call button
Select contact
Open menu
You should see
address book menu http://img9.imageshack.us/img9/8175/callviaabc.png
Tested on Bold 9000 simulator
Full code:
import javax.microedition.pim.Contact;
import net.rim.blackberry.api.invoke.Invoke;
import net.rim.blackberry.api.invoke.PhoneArguments;
import net.rim.blackberry.api.menuitem.ApplicationMenuItem;
import net.rim.blackberry.api.menuitem.ApplicationMenuItemRepository;
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 CallIntegrate extends UiApplication {
public CallIntegrate() {
pushScreen(new Scr());
}
public static void main(String[] args) {
CallIntegrate app = new CallIntegrate();
app.enterEventDispatcher();
}
}
class AdressBookMenuItem extends ApplicationMenuItem {
Contact mContact;
public AdressBookMenuItem(int order) {
super(order);
}
public AdressBookMenuItem(Object context, int order) {
super(context, order);
}
public Object run(Object context) {
if (context instanceof Contact) {
mContact = (Contact) context;
if (0 < mContact.countValues(Contact.TEL)) {
String phone = mContact.getString(Contact.TEL, 0);
PhoneArguments args = new PhoneArguments(
PhoneArguments.ARG_CALL, phone);
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, args);
} else {
Dialog.alert("This contact has no phone number");
}
}
return null;
}
public Contact getContact() {
return mContact;
}
public String toString() {
return "Call via ABC";
}
}
class Scr extends MainScreen {
public Scr() {
super(DEFAULT_MENU|DEFAULT_CLOSE);
String label = "Now please go to blackberry adressbook, "
+ "select contact and open menu";
add(new LabelField(label));
AdressBookMenuItem menuItem = new AdressBookMenuItem(0);
ApplicationMenuItemRepository repository =
ApplicationMenuItemRepository.getInstance();
long id = ApplicationMenuItemRepository.MENUITEM_ADDRESSBOOK_LIST;
repository.addMenuItem(id, menuItem);
}
}

Resources