Saturday, December 17, 2011

PopupScreen example in Blackberry


import java.util.Vector;

import mypackage.LoginScreen;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;



public class PasswordBox extends PopupScreen implements KeyListener, TrackwheelListener
{
   private               String                 m_response;
   private               PasswordEditField      m_answer;
   private               String                 m_password;
   private               String                 m_userName;
   
   public PasswordBox()
   {
       super(new VerticalFieldManager(),Field.FOCUSABLE);

       m_password="moorthy";
                        
       LabelField question = new LabelField("Enter password to unlock.");
       m_answer = new PasswordEditField(" ","");
       add(question);
       add(new SeparatorField());
       add(m_answer);
     
   }
 
 
// This function gets called if the password match
 public void accept()
   {
 close();
 UiEngine ui = Ui.getUiEngine();
 ui.pushScreen(new LoginScreen(0));

        //System.exit(0);
     
   }
 
 

 
 
   ////////////////////////////////////////////
   /// implementation of TrackwheelListener
   ////////////////////////////////////////////
   public boolean trackwheelClick(int status, int time)
   {
       m_response = m_answer.getText();
       if (m_response.equals(m_password))
       {
           accept();
       }
       else
       {
         //  Dialog.alert("Invalid Password !");
       }
       return true;
   }
 
 
   /** Invoked when the trackwheel is released */
   public boolean trackwheelUnclick(int status, int time)
   {
       return false;
   }
 
 
   /** Invoked when the trackwheel is rolled. */
   public boolean trackwheelRoll(int amount, int status, int time)
   {
       return true;
   }
 
 
   /////////////////////////////////////
   /// implementation of Keylistener
   /////////////////////////////////////
   public boolean keyChar(char key, int status, int time)
   {
       //intercept the ESC key - exit the app on its receipt
       boolean retval = false;
       switch (key)
       {
           case Characters.ENTER:
               m_response = m_answer.getText();
               if (m_response.equals(m_password))
               {
                   accept();
               }
               // an alert is displayed if the password is incorrect
               else
               {
                //   Dialog.alert("Invalid Password !");
               }
               retval = true;
               break;
         
             
             
           default:
               retval = super.keyChar(key,status,time);
       }
       return retval;
   }
 
   /** Implementation of KeyListener.keyDown */
   public boolean keyDown(int keycode, int time)
   {
      if(Keypad.key(keycode)==Keypad.KEY_END)
        {
          Application.getApplication().requestForeground();
                  return false;
                 
       }
      return false;
   }
   /** Implementation of KeyListener.keyRepeat */
   public boolean keyRepeat(int keycode, int time)
   {
     
       return false;
   }
   /** Implementation of KeyListener.keyStatus */
   public boolean keyStatus(int keycode, int time)
   {
       return false;
   }
   /** Implementation of KeyListener.keyUp */
   public boolean keyUp(int keycode, int time)
 
   {
    if(Keypad.key(keycode)==Keypad.KEY_END)
        {
             Application.getApplication().requestForeground();
                  return false;
                 
       }
       return false;
   }
 
 /* Invoked when this screen is obscured. A Screen is obscured when it is was the topmost and is no longer by means of:
     (1).  a new screen pushed on the display stack
        (2).  a global screen is displayed above this screen
  (3).  this screen's application goes into the background
      (4).  this screen is pushed and it is deemed obscured by the above rules
 */

   protected void onObscured()
   {
   
     // Application.getApplication().requestForeground();
   }
}

Send SMS example in Blackberry

try{

String[] addressees = {mobile number};
                    if (addressees != null)
                    {
                        mc = (MessageConnection)Connector.open("sms://");
                        TextMessage message = (TextMessage)mc.newMessage(MessageConnection.TEXT_MESSAGE, "sms://");
                        message.setPayloadText(msg);
                        
                        for (int i = 0; i < addressees.length; i++)
                        {
                            if (addressees[i] != null)
                            {
                                message.setAddress("sms://" + addressees[i]);
                                mc.send(message);
                            }
                        }
                        mc.close();
                    }
}
catch (ConnectionNotFoundException ex)
        {
            System.out.println(ex.getMessage());
        }
        catch (IllegalArgumentException ex)
        {
            System.out.println("Ilegal Argument: " + ex.getMessage());
        }
        catch (SIMCardException ex)
        {
            System.out.println("SIMCard Exception: " + ex.getMessage());
        }
        catch (InterruptedIOException e) 
        {
            System.out.println(e.getMessage());
        }
        catch (InterruptedException e) 
        {
            System.out.println(e.getMessage());
        }
        catch (IOException e) 
        {
            System.out.println(e.getMessage());
        }
        catch (NullPointerException e)
        {
            System.out.println(e.getMessage());
        }
        catch (SecurityException e) 
        {
            System.out.println(e.getMessage());
        }
         

Friday, December 9, 2011

Resize image and Field manager Design manual

package mypackage;

import net.rim.device.api.math.Fixed32;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;

public class Layout_Design {
   
    /// Dynamically change image//////////////
   
    public Bitmap getScaledBitmapImage(EncodedImage image, int width, int height)
    {
        // Handle null image
        if (image == null)
        {
            return null;
        }
     
        //return bestFit(image.getBitmap(), width, height);
     
        int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
        int currentHeightFixed32 = Fixed32.toFP(image.getHeight());
     
        int requiredWidthFixed32 = Fixed32.toFP(width);
        int requiredHeightFixed32 = Fixed32.toFP(height);
     
        int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
        int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
     
        image = image.scaleImage32(scaleXFixed32, scaleYFixed32);
     
        return image.getBitmap();
    }
   
    /////VerticalFieldManager dynamically////////////////////////
   
    public VerticalFieldManager getCustomVerticalManager( final int width, final int height)
    {
        VerticalFieldManager verticalManager = new VerticalFieldManager(net.rim.device.api.ui.Manager.VERTICAL_SCROLL | net.rim.device.api.ui.Manager.VERTICAL_SCROLLBAR)
        {
          
            protected void sublayout( int maxWidth, int maxHeight )
            {
                int displayWidth = width;
                int displayHeight = height;
                super.sublayout( displayWidth, displayHeight);
                setExtent( displayWidth, displayHeight);
            }
        };
       
        return verticalManager;
    }
    public VerticalFieldManager getCustomVerticalManager2( final int width, final int height)
    {
        VerticalFieldManager verticalManager = new VerticalFieldManager(net.rim.device.api.ui.Manager.NO_VERTICAL_SCROLL | net.rim.device.api.ui.Manager.NO_VERTICAL_SCROLLBAR)
        {
          
            protected void sublayout( int maxWidth, int maxHeight )
            {
                int displayWidth = width;
                int displayHeight = height;
                super.sublayout( displayWidth, displayHeight);
                setExtent( displayWidth, displayHeight);
            }
        };
       
        return verticalManager;
    }

    public HorizontalFieldManager getCustomHorizontalManager( final int width, final int height)
    {
        HorizontalFieldManager HorizontalManager = new HorizontalFieldManager(net.rim.device.api.ui.Manager.VERTICAL_SCROLL | net.rim.device.api.ui.Manager.VERTICAL_SCROLLBAR)
        {
          
            protected void sublayout( int maxWidth, int maxHeight )
            {
                int displayWidth = width;
                int displayHeight = height;
                super.sublayout( displayWidth, displayHeight);
                setExtent( displayWidth, displayHeight);
            }
        };
       
        return HorizontalManager;
    }   
 
}




////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

1. How to use Bitmap Method?
       
Layout_Design method=new Layout_Design();

                 EncodedImage ei=EncodedImage.getEncodedImageResource("background.png");
                 VericalFieldManager backgroundlay=method.getCustomVerticalManager(deviceWidth, (deviceHeight*80)/100);
 backgroundlay.setBackground(BackgroundFactory.createBitmapBackground(method.getScaledBitmapImage(ei,Display.getWidth(),Display.getHeight())));
            
         









Monday, October 31, 2011

HTTP post method in Blackberry


public void post()
{
URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
//passing q’s value and ie’s value
postData.append("UserName","your username");
postData.append("Password", "your password");

ConnectionFactory conFactory = new ConnectionFactory();
ConnectionDescriptor conDesc = null;
try{
conDesc = conFactory.getConnection("https://www.pmamsmartselect.com/PMAMSS-Webservices/MobileService.asmx/LoginCheck;deviceside=true");
}catch(Exception e){
System.out.println(e.toString()+":"+e.getMessage());
}
String response = ""; // this variable used for the server response
// if we can get the connection descriptor from ConnectionFactory
if(null != conDesc){
try{
HttpConnection connection = (HttpConnection)conDesc.getConnection();
//set the header property
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("Content-Length", Integer.toString(postData.size())); //body content of post data
connection.setRequestProperty("Connection", "close"); // close the connection after success sending request and receiving response from the server
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // we set the content of this request as application/x-www-form-urlencoded, because the post data is encoded as form-urlencoded(if you print the post data string, it will be like this -> q=remoQte&ie=UTF-8).

//now it is time to write the post data into OutputStream
OutputStream out = connection.openOutputStream();
out.write(postData.getBytes());
out.flush();
out.close();

int responseCode = connection.getResponseCode(); //when this code is called, the post data request will be send to server, and after that we can read the response from the server if the response code is 200 (HTTP OK).
if(responseCode == HttpConnection.HTTP_OK){
//read the response from the server, if the response is ascii character, you can use this following code, otherwise, you must use array of byte instead of String
InputStream in = connection.openInputStream();
StringBuffer buf = new StringBuffer();
int read = -1;
while((read = in.read())!= -1)
buf.append((char)read);
response = buf.toString();
}
Dialog.inform(response);
//don’t forget to close the connection
connection.close();

}catch(Exception e){
System.out.println(e.toString()+":"+e.getMessage());
}
}
}

Tuesday, October 18, 2011

set hint text in Editfield using in blackberry


usernameField = new EditField()
        {
        protected void paint(Graphics g) {
                if (getTextLength() == 0) {
                    g.setColor(Color.LIGHTGRAY);
                    g.drawText("Username", 0, 0);
                }

                g.setColor(Color.BLACK);
                super.paint(g);
            }
        };

load http image in blackberry


 ConnectionFactory _factory = new ConnectionFactory();


ConnectionDescriptor cd = _factory
.getConnection(Enter image url);

Connection c = cd.getConnection();
String result = "";
OutputStream os = null;
InputStream is = null;
try {

OutputConnection outputConn = (OutputConnection) c;
os = outputConn.openOutputStream();
String getCommand = "GET " + "/" + " HTTP/1.0\r\n\r\n";
os.write(getCommand.getBytes());
os.flush();

InputConnection inputConn = (InputConnection) c;

is = inputConn.openInputStream();
byte[] data = net.rim.device.api.io.IOUtilities
.streamToBytes(is);
result = new String(data);

byte[] dataArray = result.getBytes();
EncodedImage bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
Bitmap bit = bitmap.getBitmap();


}
catch (Exception e)
{
result = "ERROR fetching content: " + e.toString();
}

Saturday, October 15, 2011

QR code scanning in blackberry


import java.util.Hashtable;
import java.util.Vector;

import net.rim.blackberry.api.browser.Browser;
import net.rim.blackberry.api.browser.BrowserSession;
import net.rim.device.api.barcodelib.BarcodeBitmap;
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.command.Command;
import net.rim.device.api.command.CommandHandler;
import net.rim.device.api.command.ReadOnlyCommandMetadata;
import net.rim.device.api.system.Bitmap;
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.XYEdges;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
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 net.rim.device.api.ui.decor.BorderFactory;
import net.rim.device.api.ui.toolbar.ToolbarButtonField;
import net.rim.device.api.ui.toolbar.ToolbarManager;
import net.rim.device.api.util.StringProvider;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.common.ByteMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;

public class BarcodeAPISample extends UiApplication {

//This controls how big barcode we will display is to be
private static final int BARCODE_WIDTH = 300;

// This is the app itself
private static BarcodeAPISample _app;

// Errors will be logged here
private LabelField _logField;

// The main screen which holds the toolbar and displayed barcode
private MainScreen _mainScreen;

// The barcode is displayed here
private BitmapField _barcodeField;
// The text stored here is converted into a barcode by the user
private EditField _barcodeTextField;

// This controls the scanning of barcodes
private BarcodeScanner _scanner;

// This screen is where the viewfinderf or the barcode scanner is displayed
private FullScreen _barcodeScreen;

public BarcodeAPISample() {
// New screen
_mainScreen = new MainScreen();

// Create the log field so it can be used in this constructor
_logField = new LabelField("Log: ");

// Create the place-holder for the barcode image and add it to the main
// screen
_barcodeField = new BitmapField(new Bitmap(BARCODE_WIDTH, BARCODE_WIDTH), Field.FIELD_HCENTER);
_barcodeField.setBorder(BorderFactory.createBevelBorder(new XYEdges(2, 2, 2, 2)));
_mainScreen.add(_barcodeField);

// Create and add the field to store the barcode contents
_barcodeTextField = new EditField("Barcode text: ", "http://devblog.blackberry.com");
_mainScreen.add(_barcodeTextField);

ButtonField d=new ButtonField("Display");
d.setChangeListener(new FieldChangeListener() {

public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
displayBarcode();
}
});

ButtonField s=new ButtonField("scan");
s.setChangeListener(new FieldChangeListener() {

public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
scanBarcode();
}
});

_mainScreen.add(d);
_mainScreen.add(s);

// Add "display barcode" and "scan barcode" toolbar buttons
/**
* This is a quick example of the new (in 6.0)
* net.rim.device.api.command package and the
* net.rim.device.api.ui.toolbar package. All it does is invoke the
* displayBarcode() or scanBarcode() method when you click the
* corresponding button. For more details on this package, see the
* JavaDocs or elsewhere in the Developer Resource Center
*/
ToolbarManager toolbar = new ToolbarManager();

ToolbarButtonField displayBarcodeToolbarButtonField = new ToolbarButtonField(new StringProvider("Display"));
displayBarcodeToolbarButtonField.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata arg0, Object arg1) {
displayBarcode();
}
}));
toolbar.add(displayBarcodeToolbarButtonField);

ToolbarButtonField scanBarcodeToolbarButtonField = new ToolbarButtonField(new StringProvider("Scan"));
scanBarcodeToolbarButtonField.setCommand(new Command(new CommandHandler() {
public void execute(ReadOnlyCommandMetadata arg0, Object arg1) {
scanBarcode();

}
}));
toolbar.add(scanBarcodeToolbarButtonField);

_mainScreen.setToolbar(toolbar);

// Add the log field to the bottom
_mainScreen.add(_logField);

pushScreen(_mainScreen);
}

// Simply create the the app and enter the event dispatcher
public static void main(String[] args) {
_app = new BarcodeAPISample();
_app.enterEventDispatcher();

}

/**
* displayBarcode
* <p>
* This method will take the text in the _barcodeTextField, convert it into
* a QRCode and display it on the main screen. It could be easily modified
* to use a different barcode format or to get the text from somewhere else.
*/
private void displayBarcode() {
try {
QRCode qrCode = new QRCode();

// This encodes the text with a low level (%7) of error correction
Encoder.encode(_barcodeTextField.getText(), ErrorCorrectionLevel.L, qrCode);

// From there we get the actual data matrix and convert it into a
// bitmap
ByteMatrix barcode = qrCode.getMatrix();
Bitmap bitmap = BarcodeBitmap.createBitmap(barcode, BARCODE_WIDTH);

_barcodeField.setBitmap(bitmap);

} catch (Exception e) {
log("Exception: " + e);
}
}

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.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
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) {
log("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();
_app.pushScreen(_barcodeScreen);
} catch (Exception e) {
log("Could not start scan: " + e);
}

}

/***
* 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
_app.invokeLater(new Runnable() {
public void run() {
_app.popScreen(_barcodeScreen);

}
});

// We will use a StringBuffer to create our message as every String
// concatenation creates a new Object
final StringBuffer message = new StringBuffer("Would you like to open the browser pointing to \"");
message.append(rawText);
message.append("\"?");
log(message.toString());
_barcodeScreen.invalidate();

// Prompt the user to open the browser pointing at the URL we
// scanned
_app.invokeLater(new Runnable() {
public void run() {
if (Dialog.ask(Dialog.D_YES_NO, message.toString()) == Dialog.YES) {

// Get the default sessionBrowserSession
BrowserSession browserSession = Browser.getDefaultSession();
// Launch the URL
browserSession.displayPage(rawText);
}
}
});
}

}

/***
* 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) {
log("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) {
log("Error stopping scan: " + e);
}
_app.invokeLater(new Runnable() {
public void run() {
_app.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;
}

}
}

/***
* log
* <p>
* Writes a message to an edit field for debug purposes. Also sends to
* STDOUT.
* <p>
*
* @param msg
*            - The String to log
*/
public void log(final String msg) {
invokeLater(new Runnable() {
public void run() {
_logField.setText(_logField.getText() + "\n" + msg);
System.out.println(msg);
}
});
}
}

Friday, October 14, 2011

asmx (ksoap) webservice example in j2me



import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;


public class asmx extends MIDlet implements CommandListener{
    Form f;
    Display display;
    Command com;

    TextField txx;

    public void startApp()
    {
        f=new Form("asmx");
        txx=new TextField("Celsius:", "", 100, TextField.NUMERIC);
         f.append(txx);
        com =new Command("ok", Command.OK, 0);
        f.addCommand(com);
        display=Display.getDisplay(this);
        f.setCommandListener(this);
        display.setCurrent(f);

    }

    public void pauseApp()
    {

    }

    public void destroyApp(boolean unconditional)
    {

    }

    public void commandAction(Command c, Displayable d) {

        if(c==com)
        {
           // services2();
            service();
        }

        throw new UnsupportedOperationException("Not supported yet.");
    }
   
    public void service()
    {
        Thread ss=new Thread()
        {
           public void run()

        {
        System.out.println("Entrando a Services2");
    String serviceUrl = "http://www.w3schools.com/webservices/tempconvert.asmx";
    String serviceNameSpace = "http://tempuri.org/";
    String soapAction = "http://tempuri.org/CelsiusToFahrenheit";
    String methodName = "CelsiusToFahrenheit";
    SoapObject rpc = new SoapObject(serviceNameSpace, methodName);
    rpc.addProperty ("Celsius", txx.getString().trim());
   
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.bodyOut = rpc;
    envelope.dotNet = true;//<strong>IF you are accessing .net based web service this should be true</strong>
    envelope.encodingStyle = SoapSerializationEnvelope.XSD;
    HttpTransport ht = new HttpTransport(serviceUrl);
    ht.debug = true;
    ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    String result = null;
   
    try
    {
   
    ht.call(soapAction, envelope);
       
    Alert alert = new Alert("Result",
                        ht.responseDump,
                        null, AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert, f);
     
    }
    catch(org.xmlpull.v1.XmlPullParserException ex2)
    {
    Alert alert = new Alert("Error",
                        ex2.getMessage(),
                        null, AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert, f);
    }
    catch(Exception ex)
    {
    Alert alert = new Alert("Error",
                        ex.getMessage(),
                        null, AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert, f);
    }
        }
        };
        ss.start();
    }
}

asmx (ksoap) web service example in Blackberry


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

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;
import org.xml.sax.InputSource;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class MyScreen extends MainScreen
{
   LabelField lbl_UserName,lbl_Password;
   EditField edf_UserName,edf_Password;
   CheckboxField chk_Remember;
   ButtonField btn_Login;
 
   VerticalFieldManager vm_MainFieldManager,vm_btnFieldManager;
 
   int deviceWidth = Display.getWidth();
   int deviceHeight = Display.getHeight();
 
   allmethods all_layout=new allmethods();
    public MyScreen()
    {      
        setTitle("Login Screen");
       
        vm_MainFieldManager=all_layout.getCustomVerticalManager2(deviceWidth, deviceHeight);
       
        lbl_UserName = new LabelField("UserName :");
        lbl_Password = new LabelField("Password :");
        edf_UserName = new EditField();
        edf_Password = new EditField();
        chk_Remember = new CheckboxField("Remember me", false);
       
        XYEdges xy=new XYEdges(12, 12, 12, 12);
        Bitmap bit_Rount = Bitmap.getBitmapResource("rounded.png");
        Border brd_Rount = BorderFactory.createBitmapBorder(xy, bit_Rount);
       
        edf_UserName.setBorder(brd_Rount);
        edf_Password.setBorder(brd_Rount);
       
        vm_btnFieldManager = new VerticalFieldManager(Field.FIELD_RIGHT);
       
        btn_Login = new ButtonField("Login");
       
        btn_Login.setChangeListener(new FieldChangeListener() {

public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
loginPArse();
}
});
       
        vm_btnFieldManager.add(btn_Login);
        vm_MainFieldManager.add(lbl_UserName);
        vm_MainFieldManager.add(edf_UserName);
        vm_MainFieldManager.add(lbl_Password);
        vm_MainFieldManager.add(edf_Password);
        vm_MainFieldManager.add(chk_Remember);
        vm_MainFieldManager.add(vm_btnFieldManager);
        add(vm_MainFieldManager);
             
    }
   
    public void loginPArse()
    {
    System.out.println("Entrando a Services2");
    String serviceUrl = "http://45.pmam.com/PMAMSS-Webservices/MobileService.asmx;interface=wifi";
    String serviceNameSpace = "http://tempuri.org/";
    String soapAction = "http://tempuri.org/LoginCheck";
    String methodName = "LoginCheck";
    SoapObject rpc = new SoapObject(serviceNameSpace, methodName);
    rpc.addProperty ("UserName".trim(), edf_UserName.getText().trim());
    rpc.addProperty ("Password".trim(), edf_Password.getText().trim());
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.bodyOut = rpc;
    envelope.dotNet = true;//<strong>IF you are accessing .net based web service this should be true</strong>
    envelope.encodingStyle = SoapSerializationEnvelope.XSD;
    HttpTransport ht = new HttpTransport(serviceUrl);
    ht.debug = true;
    ht.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    String result = null;
   
    try
    {
   
    ht.call(soapAction, envelope);
    //Dialog.inform(ht.responseDump);
    //result = (envelope.getResponse()).toString();
    result = (envelope.getResult()).toString();
    SoapObject body = (SoapObject)envelope.bodyIn;
   
result = (String)body.getProperty("LoginCheckResult").toString();
   
    Dialog.inform(result);
     
    }
    catch(org.xmlpull.v1.XmlPullParserException ex2)
    {
    Dialog.inform(ex2.getMessage());
    }
    catch(Exception ex)
    {
    Dialog.inform(ex.getMessage());
    }
   
    }
   
    public void xml()throws IOException
    {
   
    }
   
 
}

Tuesday, October 4, 2011

device configuration in j2me



import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class LoginScreen extends MIDlet{
private Display display;
private Command cExit;

public void startApp(){
display = Display.getDisplay(this);

cExit = new Command("Quit", Command.EXIT, 0);

Canvas canvas = new DummyCanvas();

Runtime runtime = Runtime.getRuntime();
Form form = new Form("Attributes");

form.append(new StringItem("Know Your Mobile", ""));
form.append(new StringItem("Total Memory:", String.valueOf(runtime.totalMemory()/1024)+"Kb"));
form.append(new StringItem("Free Memory:", String.valueOf(runtime.freeMemory()/1024)+"Kb"));
form.append(new StringItem("n", null));
form.append(System.getProperty("microedition.configuration"));
form.append(System.getProperty("microedition.profiles"));

boolean isColor = display.isColor();

form.append(new StringItem(isColor ? "Colors:": "Grays:", String.valueOf(display.numColors())));
form.append(new StringItem("Width: ", String.valueOf(canvas.getWidth())));
form.append(new StringItem("Height:", String.valueOf(canvas.getHeight())));
form.append(new StringItem("Repeat:", String.valueOf(canvas.hasRepeatEvents())));
form.append(new StringItem("Double Buff:", String.valueOf(canvas.isDoubleBuffered())));

form.addCommand(cExit);
form.setCommandListener(
new CommandListener(){
public void commandAction(Command c, Displayable d){
if (c == cExit){
destroyApp(false);
notifyDestroyed();
}
}
}
);

display.setCurrent(form);
}
public void pauseApp(){
}
public void destroyApp(boolean unconditional){
}
}

class DummyCanvas extends Canvas{
public void paint(Graphics g){
;
}
}

BlackBerry Sqlite Database Sample


import net.rim.device.api.database.Cursor;
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;

public class database extends MainScreen {
Database sqliteDB;
URI uri;
public void base()
{
try{
uri = URI.create("file:///SDCard/Databases/sample/sample4.db");
sqliteDB = DatabaseFactory.create(uri);

Statement st = sqliteDB.createStatement("CREATE TABLE joke(name)");
st.prepare();
st.execute();
st.close();

 Statement st1 = sqliteDB.createStatement("INSERT INTO joke VALUES ('Thirumoorthy')");
st1.prepare();
st1.execute();
st1.close();
sqliteDB.close();


//add(new RichTextField("Status: Database was created and inserted the values successfully"));

}
catch (Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}

}

xml parsing in j2me


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;
import org.kxml.Xml;
import org.kxml.kdom.Document;
import org.kxml.kdom.Element;
import org.kxml.parser.XmlParser;

/**
 * @author bliss
 */
public class xmlparse extends MIDlet {
    public static final String resfile_name = "test.xml";
    Vector v=new Vector();
    StringBuffer s=null;

    public void startApp() {

        beginParse();
        Display display=Display.getDisplay(this);
        Form f=new Form("ddddd");
        f.append(v.firstElement().toString());
        display.setCurrent(f);
       
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void beginParse()
    {

        try
            {
               

                 XmlParser parser = null;
Document doc = new Document();

try
                  { //This is used for getting the file from same folder in which the code is present.
InputStream in = this.getClass().getResourceAsStream(resfile_name);
                        InputStreamReader isr = new InputStreamReader(in);
parser = new XmlParser( isr );
doc.parse( parser );
parser = null;
}
                 catch (IOException ioe)
                  {

                    parser = null;
doc = null;
return;
}

Element root = doc.getRootElement();
                int child_count = root.getChildCount();
                for (int i = 0; i < child_count ; i++ )
                  {
   if (root.getType(i) != Xml.ELEMENT)
                     {
continue;
            }
   s=new StringBuffer();
   Element kid = root.getElement(i);

   if(root.getElement(i).toString()!=null)
                        {}
                    if(kid.getName().equals("User"))   //Get Attributes from Name
                     {
                       s.append(kid.getAttribute(0).getValue());
                       v.addElement(kid.getAttribute(0).getValue());

                     }

   if (!kid.getName().equals("User"))
                     {
continue;
                     }

   int address_item_count = kid.getChildCount();
                    for (int j = 0; j < address_item_count ; j++)
                      {

      if (kid.getType(j) != Xml.ELEMENT)
                           {
     continue;
  }

Element item = kid.getElement(j);
                        if(item.getName().equals("Work")) // Different Tags
                           {
                              s.append(":"+item.getText());
                           }
                        if(item.getName().equals("City"))
                           {
                              s.append("-"+item.getText());
                           }
                        if(item.getName().equals("Amount"))
                           {
                              if(item.getText()!=null)
                                {
                                   s.append("-"+item.getText());
                                }

                           }
                        item = null;

}


                   System.out.println(s.toString()); //Just Print the Data at your Output Window
                   s=null;
   kid = null;
 }
            }
        catch(Exception e){}
    }
}

/*
<?xml version="1.0" encoding="utf-8"?>
<UserData>
  <User Name="ABC">
    <Work>Job</Work>
    <City>fsfjk</City>
    <Amount>200</Amount>
  </User>
  <User Name="XYZ">
   <Work>Labour</Work>
    <City>sdfdsf</City>
    <Amount>1000</Amount>
  </User>
  </UserData>
*/

steps:

1.download the kxml package 
2.open netbeans after create the mobile project(j2me)
3. Right click in your project on   project tree after select properties
4.select the Build->Libraries & Resources 
5.clck Add jar/zip button after select your kxml package 
6.use this code run successfully.