List of all Iphone and Blackberry Development codes in a one click Iphone,objective C,xcode,blackberry Development,iOS Development

Tuesday, December 11, 2012

Blackberry In-App Payment

The Payment Service enables you to leverage a range of business models through the sale of digital goods within your applications. The Payment Service is easy to implement and provides end users with a fast, consistent, and secure purchase experience.
The Payment Service is flexible, and enables you to implement a variety of subscription and renewal options in your apps. For example, you can offer auto-renewing subscriptions, free renewals for a specified period of time, or reduced-rate renewals.

 First download and add the payment sdk jar file to your project click here.
  1. Setup a 'sandbox' account using the BlackBerry App World vendor portal
  2. Upload your app into BlackBerry App world but don't publish it, just save it and leave it in draft state
  3. Also in the vendor portal, set up your digital goods (the things available for in-app purchase)
  4. On your BlackBerry, load App World and login with your sandbox account email address.
  5. Within any screen in App World press ALT+TST and enter the SKU or ID of your test app.
  6. You can then download the test version of your app (which is not available to anyone else)
  7. Once the app is downloaded and installed you will be able to test your in app payments.
 Use the following codes for the payment-


 private PaymentEngine engine = PaymentEngine.getInstance();

 PurchaseArgumentsBuilder arguments = new PurchaseArgumentsBuilder().withDigitalGoodSku( "sku-from the appworld").withDigitalGoodName( "name of the good").withMetadata( ""name of the good") .withPurchasingAppName( "Payment Service SDK Demo" );
                   

                            try
                           {
                               Purchase purchase = engine.purchase(arguments.build());
                               Dialog.inform("Purchase of " + purchase.getMetadata()
                                   + " is successful.");
                           }
                           catch (IllegalArgumentException e)
                           {
                               Dialog.inform(e.getMessage());
                           }
                           catch (PaymentException e)
                           {
                               Dialog.inform(e.getMessage());
                           }


                          




        

Tuesday, October 30, 2012

Android Toast like popup in Blackberry

 http://i.stack.imgur.com/DslJw.png
 
 // show a status message for 3 seconds (3000 msec)
Status.show("Hello Toast", Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), 3000);



        

Tuesday, August 21, 2012

Phone Call in Blackberry

The following code will help to call a mobile number programatically.

PhoneArguments callArgs = new PhoneArguments(PhoneArguments.ARG_CALL,"mobile number to make call");
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, callArgs);


        

Automatically Taking Picture in Blackberry

The following code will automatically take pictures without any user interactions. It also displays the taken picture in the screen.

    private Field _videoField;
    private Player _player;
    private VideoControl _videoControl;
    byte[] image;

 try{
        _player = Manager.createPlayer( "capture://video??encoding=jpeg&width=240&height=240" );
        _player.realize();
        _player.prefetch();
        _videoControl = (VideoControl)_player.getControl("VideoControl");
        _player.start();               
        if (_videoControl != null){

            _videoField = (Field) _videoControl.initDisplayMode (GUIControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
            _videoControl.setDisplayFullScreen(true);
            add(_videoField);
        }
    }
    catch(Exception e)
    {
       //show error
    }
         

         try {
                image = _videoControl.getSnapshot(null);
                 _player.close();
               
                EncodedImage bitmap = EncodedImage.createEncodedImage(image, 0, image.length); 
                BitmapField field1 = new BitmapField();
                field1.setImage(bitmap);
                add(field1);
            } catch (MediaException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        

Play Audio From URL in Blackberry

The following code will help you to playing an audio from url.

                       try {
                         String httpURL="http://www.yourwebsite.com/audio.mp3";
                         if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
                                    && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
                                httpURL += ";interface=wifi";
                            }
                       
                            Player player;
                            player =Manager.createPlayer(httpURL);
                            player.realize();
                            player.prefetch();
                            player.start();
                           
                        } catch (Exception me) {
                            Dialog.alert(me.toString());
                           
                        }


        

Thursday, July 26, 2012

Gauge Field in Blackberry(Like download status bar)

The following code will display a Download status Bar like Gauge field in Blackberry.




GaugeField gField;
 gField = new CustomGaugeField();
add(gField);
startProgressTimer();

private void startProgressTimer() {
       ttask = new TimerTask() {
            public void run() {
                Field f;
                for (int i = 0; i < getFieldCount(); i++) {
                    f = getField(i);
                    if (f instanceof CustomGaugeField) {
                        final CustomGaugeField gField = (CustomGaugeField) f;
                        final int increment = (i + 1) * 2;
                     
                        UiApplication.getUiApplication().invokeLater(
                            new Runnable() {
                                public void run() {
                                     
                                    if(gField.getValue()>=100)
                                    {
                                    ttask.cancel();
                                    //Implement your action here
                                    }
                                    else{
                                    gField.setValue((gField.getValue() + increment) % 101);
                                    }
                                   
                                }
                            }
                        );
                    }
                       
                }

            }
        };

        Timer ttimer = new Timer();
        ttimer.schedule(ttask, 1000, 300);
    }

//custom Gauge Field Class

import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.GaugeField;

class CustomGaugeField extends GaugeField {
    // Default constructor, need improvement
    public CustomGaugeField() {
        super("", 0, 100, 0, GaugeField.PERCENT);
    }

    // Colors
    private static final int BG_COLOR = 0xd6d7d6;
    private static final int BAR_COLOR = 0x63cb52;
    private static final int FONT_COLOR = 0x5a55c6;

    protected void paint(Graphics graphics) {
        int xProgress = (int) ((getWidth() / 100.0) * getValue());
        int xProgressInv = getWidth() - xProgress;

        // draw background
        graphics.setBackgroundColor(BG_COLOR);
        graphics.clear();

        // draw progress bar
        graphics.setColor(BAR_COLOR);
      
        graphics.fillRect(0, 0, xProgress, getHeight());//left to right
        //graphics.fillRect(xProgressInv, 0, xProgress, getHeight());//right to left

        // draw progress indicator text
        String text = getValue() + "%";
        Font font = graphics.getFont();
        int xText = (getWidth() - font.getAdvance(text)) / 2;
        int yText = (getHeight() - font.getHeight()) / 2;
        graphics.setColor(FONT_COLOR);
        graphics.drawText(text, xText, yText);
    }
   
    protected void layout(int width, int height) {
        super.layout(width, height);
        setExtent (width, 15);
        }
}


        

Tuesday, July 24, 2012

Push Notification in Blackberry

The BlackBerry Push Service is an essential component of the real-time, always-on experience of BlackBerry smartphones. It offers an efficient and reliable way of sending information to your users. It also lets your application process information in the background and notify users when their attention is required.

Refer this - developer.blackberry.com
First register for push Credentials.  (See the above link).
Use Alternate Entry Point Application. The Background app will listen for the push notifications. The UI Application is used to register the device for getting the push notification. You need to activate the BIS(Blackberry Internet Service) on your device.

Client app will be given upon requests (rincethomas33@gmail.com)

Client side code -

// Main Class-
class App extends UiApplication {
 private static App theApp;
  public App() {
       pushScreen(new register());    
    }

  public static void main(String[] args) {
          if (args.length > 0 && args[0].equals("push_msg") ){
             theApp = new App();
             theApp.enterEventDispatcher();   
       
            }
        else {      
            BackgroundApplication backApp=new BackgroundApplication();
            backApp.setupBackgroundApplication();
            backApp.enterEventDispatcher();
          
       }       
    }  
}

//Register Class-
public class register extends MainScreen{
    public register(){
    final ButtonField btn=new ButtonField("Register");
        add(btn);
     FieldChangeListener listener=new FieldChangeListener() {
                   public void fieldChanged(Field field, int context) {
                      
                       if(field==btn){
                          
                         registerBpas();
                          
                       }
                  
                   }};
        btn.setChangeListener(listener);
       
    }
}


public static void registerBpas() {

    new Thread() {
        public void run() {
            try {
                final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + ";deviceside=false;ConnectionType=mds-public";
                System.out.println("\n\n\n msg registerBPAS URL is:  "+ registerUrl);
                HttpConnection httpConnection = (HttpConnection) Connector.open(registerUrl);
                InputStream is = httpConnection.openInputStream();
                String response = new String(IOUtilities.streamToBytes(is));
                System.out.println("\n\n\n\n\n\n msg RESPOSE CODE :    " + response);
                httpConnection.close();
                String nextUrl = formRegisterRequest(BPAS_URL, APP_ID, response) + ";deviceside=false;ConnectionType=mds-public";
                System.out.println("\n\n\n\n\n\n msg nextUrl :    " + nextUrl);
                HttpConnection nextHttpConnection = (HttpConnection) Connector.open(nextUrl);
                InputStream nextInputStream = nextHttpConnection.openInputStream();
                response = new String(IOUtilities.streamToBytes(nextInputStream));
                System.out.println("\n\n\n\n\n\n msg RESPOSE CODE 1:    " + response);
                nextHttpConnection.close();
                if (REGISTER_SUCCESSFUL.equals(response) || USER_ALREADY_SUBSCRIBED.equals(response)) {
                    Dialog.alert("msg Registered successfully for BIS push");
                   
                   
                    System.out.println("msg Registered successfully for BIS push");
                } else {
                    Dialog.alert("msg BPAS rejected registration");
                    System.out.println("msg BPAS rejected registration");
                }
            } catch (final IOException e) {
                Dialog.alert("msg IOException on register() " + e + " " + e.getMessage());
                System.out.println("msg IOException on register() " + e + " " + e.getMessage());
            }
        }
    }.start();
}

private static 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();
}
}

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) {
        }
    }
}

//Background listener class

class BackgroundApplication extends Application {  
   
    public BackgroundApplication() {
        // TODO Auto-generated constructor stub
    }
    public void setupBackgroundApplication(){
       
        MessageReadingThread messageReadingThread = new MessageReadingThread();
        messageReadingThread.start();
       
    }  
   
    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://:" + Port;
             url += ";deviceside=false;ConnectionType=mds-public";
             if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
                 url += ";interface=wifi";
                 }
           
            try {
                socket = (ServerSocketConnection) Connector.open( url );
            } catch( IOException ex ) {
                // can't open the port, probably taken by another application
                onListenError( 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 ) {
                      //  Logger.warn( "Failed to read push message, caused by " + e.getMessage() );
                        running = false;
                    }
                } finally {
                   // PushUtils.close( conn, pushInputStream, null );
                }
            }

          //  Logger.log( "Stopped listening for push messages" );
        }

        public void stopRunning() {
            running = false;
            //PushUtils.close( socket, null, null );
        }

        private void onListenError( final Exception ex ) {
           // Logger.warn( "Failed to open port, caused by " + ex );
          System.out.println(ex);
        }
    }
   
}
//push message reader class -

// HTTP header property that carries unique push message ID
    private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
    // content type constant for text messages
    private static final String MESSAGE_TYPE_TEXT = "text";
    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];
public static void process(PushInputStream pis, Connection conn) {
        System.out.println("Reading incoming push message ...");

        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();

            System.out.println("Message props: ID=" + msgId + ", Type=" + msgType + ", Encoding=" + encoding);

           
            boolean accept = true;
            if (!alreadyReceived(msgId)) {
                byte[] binaryData;

                if (msgId == null) {
                    msgId = String.valueOf(System.currentTimeMillis());
                }

                if (msgType == null) {
                    System.out.println("Message content type is NULL");
                    accept = false;
                } else if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
                    // a string
                    int size = pis.read(buffer);
                    binaryData = new byte[size];
                    System.arraycopy(buffer, 0, binaryData, 0, size);   
                   
                    PushMessage message = new PushMessage(msgId, System.currentTimeMillis(), binaryData, true, true );
                    String text = new String( message.getData(), "UTF-8" );
                     try{
                            final Dialog screen = new Dialog(Dialog.D_OK_CANCEL, " "+text,
                                    Dialog.OK,
                                    //mImageGreen.getBitmap(),
                                    null, Manager.VERTICAL_SCROLL);
                            final UiEngine ui = Ui.getUiEngine();
                            Application.getApplication().invokeAndWait(new Runnable() {
                                public void run() {
                                    NotificationsManager.triggerImmediateEvent(0x749cb23a76c66e2dL, 0, null, null);
                                    ui.pushGlobalScreen(screen, 0, UiEngine.GLOBAL_QUEUE);
                                   
                                }
                            });
                            screen.setDialogClosedListener(new MyDialogClosedListener());
                            }
                            catch (Exception e) {
                                // TODO: handle exception
                            }
                           
                   
                    // TODO report message
                }  else {
                    System.out.println("Unknown message type " + msgType);
                    accept = false;
                }
            } else {
                System.out.println("Received duplicate message with ID " + msgId);
            }
            pis.accept();
        } catch (Exception e) {
            System.out.println("Failed to process push message: " + e);
        }
    }



private static boolean alreadyReceived(String id) {
        if (id == null) {
            return false;
        }

        if (Arrays.contains(messageIdHistory, id)) {
            return true;
        }

        // new ID, append to the history (oldest element will be eliminated)
        messageIdHistory[historyIndex++] = id;
        if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
            historyIndex = 0;
        }
        return false;
    }



public class PushMessage{

    private String id;
    private long timestamp;
    private byte[] data;
    private boolean textMesasge;
    private boolean unread;

    public PushMessage( String id, long timestamp, byte[] data, boolean textMesasge, boolean unread ) {
        super();
        this.id = id;
        this.timestamp = timestamp;
        this.data = data;
        this.textMesasge = textMesasge;
        this.unread = unread;
    }

    public String getId() {
        return id;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public byte[] getData() {
        return data;
    }

    public boolean isTextMesasge() {
        return textMesasge;
    }

    public boolean isUnread() {
        return unread;
    }

    public void setUnread( boolean unread ) {
        this.unread = unread;
    }

}

public class MyDialogClosedListener implements DialogClosedListener
    {

    public void dialogClosed(Dialog dialog, int choice)
    {
        if(dialog.equals(dialog))
        {
           if(choice == -1)
            {
                //Your code for Press OK
            }
            if(choice == 1)
            {
                //Your code for Press Cancel
               
            }
                   }
   }
}

For setting alternate entry point - Refer below images -


Server sode PHP code is given Below -

//
ini_set('display_errors','1');
error_reporting(E_ALL);

    // APP ID provided by RIM
$appid = 'app id';
// Password provided by RIM
$password = 'password';
//Deliver before timestamp
$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+time minutes'));

//An array of address must be in PIN format or "push_all"
$addresstosendto[] = 'your pin';

$addresses = '';
foreach ($addresstosendto as $value) {
$addresses .= '
';
}

// create a new cURL resource
$err = false;
$ch = curl_init();
$messageid = microtime(true);

$data = '--mPsbVQo0a68eIL3OAxnm'. "\r\n" .
'Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n" .
'
'
. $addresses .
'
' . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm' . "\r\n" .
'Content-Type: text/plain' . "\r\n" .
'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
stripslashes('r') . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm--' . "\n\r";

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://pushapi.eval.blackberry.com/mss/PD_pushRequest");//"https://cp2991.pushapi.eval.blackberry.com/mss/PD_pushRequest"
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Hallgren Networks BB Push Server/1.0");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/related; boundary=mPsbVQo0a68eIL3OAxnm; type=application/xml", "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Connection: keep-alive"));

// grab URL and pass it to the browser
echo $xmldata = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

//Start parsing response into XML data that we can read and output
$p = xml_parser_create();
xml_parse_into_struct($p, $xmldata, $vals);
$errorcode = xml_get_error_code($p);
if ($errorcode > 0) {
echo xml_error_string($errorcode);
$err = true;
}
xml_parser_free($p);

echo 'Our PUSH-ID: ' . $messageid . "
\n";
if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "
\n";
echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "
\n";
echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "
\n";
echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "
\n";
} else {
echo 'An error has occured
' . "\n";
echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "
\n";
echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "
\n";
}

?>



OR Server sode C# code is given Below -

private void pushMessageSample(string pushedMessage)
    {
        String appid="xxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx";
        String password = "xxxxxx";
        String deliverbefore = DateTime.UtcNow.AddMinutes(5).ToString("s",System.Globalization.CultureInfo.InvariantCulture) + "Z";
        String pushPin = "xxxxxxxx";
        String Boundary = "mPsbVQo0a68eIL3OAxnm";

 StringBuilder dataToSend = new StringBuilder();

 dataToSend.AppendLine("--" + Boundary);
 dataToSend.AppendLine("Content-Type: application/xml; charset=UTF-8");

 dataToSend.AppendLine("");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("");
 string myPushId = DateTime.Now.ToFileTime().ToString();
 dataToSend.AppendLine("");
 //dataToSend.AppendLine("");
 dataToSend.AppendLine("

");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("
");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("--" + Boundary);

 dataToSend.AppendLine("Content-Type: text/plain");
 dataToSend.AppendLine("Push-Message-ID: " + myPushId);
 dataToSend.AppendLine("");

 dataToSend.AppendLine(pushedMessage);

 dataToSend.AppendLine("--" + Boundary + "--");
 dataToSend.AppendLine("");

 byte[] bytes = Encoding.ASCII.GetBytes(dataToSend.ToString());
        String httpURL = "https://cpxxxx.pushapi.eval.blackberry.com/mss/PD_pushRequest";

            WebRequest tRequest;
            tRequest = WebRequest.Create(httpURL);
            //SetProxy(tRequest);
            tRequest.Method = "POST";
            //tRequest.ContentType = "text/plain";

            //tRequest.ContentLength = bytes.Length;
            tRequest.Credentials = new NetworkCredential(appid, password);

            tRequest.PreAuthenticate = true;
            tRequest.ContentType = "multipart/related; boundary=" + Boundary + "; type=application/xml";
            tRequest.ContentLength = bytes.Length;
            string rawCredentials = string.Format("{0}:{1}", appid, password);
            tRequest.Headers.Add("Authorization",
                string.Format(
                    "Basic {0}",
                    Convert.ToBase64String(Encoding.UTF8.GetBytes(rawCredentials))));

            SetBasicAuthHeader(tRequest, appid, password);

            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(bytes, 0, bytes.Length);
            dataStream.Close();

            WebResponse tResponse = tRequest.GetResponse();

            dataStream = tResponse.GetResponseStream();

            StreamReader tReader = new StreamReader(dataStream);

            String sResponseFromServer = tReader.ReadToEnd();

            tReader.Close();
            dataStream.Close();
            tResponse.Close();
    }

public static void SetBasicAuthHeader(WebRequest req, String appID, String userPassword)
    {
        string authInfo = appID + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        req.Headers["Authorization"] = "Basic " + authInfo;
    }






        

Friday, May 18, 2012

Blackberry Knowledge Base Articles


     
1. Application Deployment

Genaral Topics
--------------
How To - Define the position of an application icon on the BlackBerry smartphone Home screen How To - Handle stored data when removing an application
How To - Load applications onto a BlackBerry smartphone
Support - A module with that name already exists in the application
Support - Application installation errors
Support - BlackBerry MDS Runtime 1.1.2 with BlackBerry Device Software 4.3.0 stops responding when an application calls from the on_init script
Support - MIDlet has verification error at offset
Support - Module net_rim_bbapi_mail not found
Support - Protocol not found- null error
Support - Unable to activate custom theme or theme not listed
Support - Version 4.0 applications do not run on the device
What Is - Indications of insufficient space to install an application on the BlackBerry device
What Is - JVM error codes
What Is - JVM error codes for BlackBerry Device Software 4.2 and later


OTA Download
------------
How To - Programmatically read the attributes of a JAD file
Support - 907 Invalid Jar Error when installing an application wirelessly
Support - Warning - This application does not contain a signature. It might not be from a trusted source.
What Is - The file size limit for wireless downloads
What Is - The required MIME types for a web server to serve BlackBerry applications


Desktop Loading
---------------
How To - Configure ALX files to make an application 'required'
How To - Create a single ALX file to install multiple versions of an application
How To - Install the BlackBerry API update via Desktop Manager or wirelessly
How To - Remove wirelessly downloaded applications
How To - Update the registry to deploy Java applications using Desktop Manager
Support - Handheld displays net_rim_xml not found error
Support - Invalid digital signature errors when installing an application
Support - No system software was found for your device
Support - Unspecified error encountered [J-0x00000011] when upgrading a third-party application
What Is - An .alx file


Enterprise server application push
-----------------------------------
How To - Deploy an icon to the BlackBerry smartphone for a web application or URL


Blackberry Application Web Loader
-----------------------------------
Support - The BlackBerry Application Web Loader is unable to create a local copy of files


2. Java APIs & Samples

Memory Management
-----------------
How To - Download large files using the BlackBerry Mobile Data System
How to - Prevent a memory leak when implementing an ApplicationMenuItem
Sample Code ---- Object Groups - Why and How to Use Them
What Is - File storage limits in the Content Store
What Is - Object Grouping - Using resources effectively

Mail
------
How To - Retrieve the default email address for the device
How To - Access HTML email messages
How To - Capture the contents of email and PIN messages before sending
How To - Create a custom Attachment Handler on the BlackBerry device
How To - Create an Attachment
How To - Create and send messages
How To - Display a PopupScreen from a SendListener
How To - Implement the ViewListener interface
How To - Programmatically send a PIN message
How To - Retrieve More of a Message
How To - Send a message from a non-default email address
Support - Error when sending a PIN message - MessagingExceptionPin message not sent. Do not have the permissions to send the message.
Support - Transport.more fails to retrieve all of a message
What Is - Application is not notified when new messages arrive


Invoking Blackberry Application
-------------------------------
How To - Invoke applications
How to - Make a running UI application go to the background and resume in the foreground
How To - Open a file in a Documents To Go application
What Is - Application does not provide invocation feedback

GPS
----
How To - Add an ApplicationMenuItem to BlackBerry Map
How To - Configure a Bluetooth GPS Receiver for use with the Location API
How To - Define criteria to retrieve a GPS fix
How To - Detect when GPS is no longer available and when to reset the LocationProvider
How To - Invoke BlackBerry Maps
How To - Manage simultaneous GPS and phone usage on the BlackBerry 8703e and the 7130e smartphones
Support - Cellsite fix prevents acquiring autonomous GPS fixes
Support - Incorrect network time
Support - Invoking BlackBerry Maps throws unexpected runtime exception
What Is - Best practices for designing GPS applications for BlackBerry smartphones operating on CDMA networks
What Is - BlackBerry Maps location document format
What Is - The BlackBerry smartphone models and their corresponding GPS capabilities
What Is - Verizon GPSSettings signing requirement


Cryptography APIs and Security
------------------------------
How To - Save requested application permissions in the Application Permissions screen
How To - Create a Unique long from a String
How to - Use Advanced Encryption
How to - Use Basic Encryption
How To - Use Content Protection


Browser API
-----------

How To - Change the RenderingOptions of a RenderingSession
How To - Create a Fixed Size BrowserField
How To - Create a web icon
How to - Create a web signal registration application
How To - Enable cookies in BrowserField
How To - Invoke a non-default browser session
How To - Invoke the browser
How To - Invoke the browser with raw HTML
How To - Invoke the default browser
How To - Perform a browser push over SSL
What Is - A ControlledAccessException is thrown when using the HttpFilterRegistry
What Is - The Push notification format

Bluetooth - USB - Serial
-------------------------
How To - Run the BlackBerry Serial Port Demo
How To - Use the Bluetooth classes
How To - Use the ServiceRouting API
Support - IOException thrown when opening a server-side Bluetooth connection
What Is - Bluetooth support on BlackBerry devices


Audio & Video
--------------
How To - Invoke the media application
How To - Obtain the media playback time from a media application
How To - Play audio in an application
How To - Play video within a BlackBerry smartphone application
How To - Record audio on a BlackBerry smartphone
How To - Specify Audio Path Routing
How To - Support streaming audio to the media application
How To - Take a snapshot using the built-in camera of a BlackBerry smartphone
Known Issue - Delay in playing audio when streaming to a Bluetooth headset
Support - Alert.startBuzzer() does not work
Support - Playing audio in an application pauses the Media application on BlackBerry smartphones running on the CDMA network
What Is - Media application error codes
What Is - setMediaTime does not work for AMR files
What Is - Supported audio formats


Menu Item and Options
-----------------------
How To - Add a custom menu item to an existing BlackBerry application
How To - Add application options to the BlackBerry Options
How To - Handle ApplicationMenuItem Invocation


MIDP & CLDC APIs
----------------
How To - Access images in a MIDP application
How To - Capture volume keys in a MIDlet
How To - Create a MIDlet that uses custom animation
How To - Create an auto-start MIDlet using the PushRegistry
How To - Establish an HTTP connection
How To - Implement basic HTTP authentication
How To - Register a MIDlet with the PushRegistry
How To - Use RMS storage efficiently in BlackBerry applications
Support - Classname does not exist in the current application package
Support - Verification error using javax.microedition.rms.RecordStore on BlackBerry Device Software 3.8 and 4.0
What Is - Cannot run a MIDP 2.0 application in BlackBerry Device Software 4.0


Micellaneous
------------
How To - Access and Obtain Service Books on a device
How To - Capture Signature on the BlackBerry Storm
How to - Create a singleton using the RuntimeStore
How To - Detect Alt and Shift key clicks
How To - Determine if a BlackBerry smartphone supports Wi-Fi capabilities
How to - Display custom messages in the request permission dialog
How To - Format the electronic serial number (ESN)
How To - Get time zone offsets with DST
How To - Implement a Comparator to compare objects
How To - Implement a string splitter based on a given string delimiter
How To - Interpret wireless network signal levels How To - Write safe initialization code
Known Issue - The RadioStatusListener.mobilityManagementEvent method is not invoked
Support - Preventing verification errors
What is - Event injection
What Is - New and Deprecated APIs in BlackBerry Java Development Environment 4.0
What Is - New and Deprecated APIs in BlackBerry Java Development Environment 4.1
What Is - New and Deprecated APIs in BlackBerry Java Development Environment 4.2


Networking
----------
How to - Determine the country code of the current mobile subscriber  How To - Determine the MCC and MNC of the current network


Persistence
-----------
How To - Programmatically determine if a microSD card has been inserted

Phone
-----
How To - Implement the PhoneListener interface
How To - Log Phone Calls
Support - The getDevicePhone method returns null


PIM-PDAP
--------
How To - Access Address Book contacts
How To - Add a PIM item to a custom category
How To - Create an Event within the Calendar application
How To - Launch the Address Book and return a contact
How To - Use Remote Address Lookup through coding  Support - Application stops receiving event notifications when using the PIMListListener API


SVG Content
-----------
How to - Use Plazmic Content Developer's Kit in your BlackBerry Application
Known Issue - Irregular focus behaviour on first hotspot when loading PME content
Known Issue - Losing the anchor when rendering SVG images in MIDlets
What Is - Browser fails to retrieve resources using relative URLs in PME content


Synchronization APIs
--------------------
How To - Backup and restore small amounts of data using SyncItem
How To - Compile the Desktop Add-In sample
How To - Save data with RMS
How To - Store persistent data on the BlackBerry smartphone


System Classes
--------------
How To - Add plain text or binary files to an application
How To - Allow an application to restart itself
How to - Capture power change events
How to - Code time-sensitive applications
How To - Detect if the BlackBerry smartphone is holstered or flipped
How To - Display a GUI when the BlackBerry device starts up
How To - Enable the backlight and prevent the screen from turning off
How To - Launch a third-party application from another third-party application
How To - Obtain the operating system version of a BlackBerry wireless device
How to - Programmatically install and upgrade applications
How To - Retrieve the BlackBerry Device Software version
Support - An unsupported API was called by the JVM RadioGetGprsState
Support - getObjectSize and getAllocated return 0
What Is - Global Events and Global Event Listeners
What Is - Supported System.getProperty keys
What Is - System Global Events
What Is - The reason a reset is required when upgrading an application


Voice Notes
----------
How To - Use the Voice Notes APIs
Samples --- VoiceNotesDemo Sample Code


XML
---
How To - Control the behavior of white space when parsing an XML document
How To - Use the XML Parser


User Interface

Fields
-------
How To - Add a TreeField to a device screen
How To - Apply a phone number filter to an AutoTextEdit field
How To - Change the text color of a field
How To - Create a colour ListField
How To - Create a custom field using attributes of other UI objects
How To - Create a custom width for a ListField
How To - Create a ListField with check boxes
How To - Create a Scrollable Image Field
How To - Create custom fields
How To - Determine the number of visible items on the BlackBerry device screen
How To - Display a progress bar in handheld applications
How To - Display an animated GIF
How To - Display dates and times in handheld applications
How To - Format text in a RichTextField
How to - Make list items appear on a screen
How To - Show focus changes using BitmapField
How to - Use an image in an application
How To - Use the paint() method to draw objects to the screen
How To - Work around ListField painting issue in early versions of BlackBerry Device Software version 4.2.2
Support - A Field's font is displayed incorrectly when set in the paint method
Support - Error starting [Application Name].Symbol'DateField.[init] not found
Support - NullPointerException is thrown when the isEditable and fieldChangeNotify methods of EditField are overridden
Support - The Custom Field is not drawing properly


Managers
-----------
How To - Create a custom layout manager for a screen
How To - Create a screen with stationary headings
How To - Create tabbed view screens
How To - Manage bitmaps in an application using field managers
How to - Perform double buffering using the BlackBerry UI
How To - Place multiple UI fields on one line
How to - Use the User Interface API to create an editable table
Support - My scrollable manager is not scrolling



Screens
---------
How to - Change the background color of a screen
How To - Clear the status of a MainScreen
How To - Create a custom Dialog
How To - Create a File Selection Popup Screen
How To - Create a splash screen
How To - Have Your Application Perform an Action after a Global Alert
How to - listen for a dialog closed event
How To - Obtain the Height and Width of a Screen
How To - Prevent a UiApplication from being listed in the application switcher
How To - Properly Push and Pop Global Screens
How to - Protect BlackBerry applications with a password screen
How To - Remove the default "Close" or "Hide" MenuItems from a Screen
How to - Update a screen on the Main Event Thread
How To - Use a Backdoor Sequence



General
-------------
How To - Add Copy, Paste, and other context-specific items to a menu
How To - Alert a user from a Background application
How To - Capture and save a screen shot
How To - Change fonts in a BlackBerry application
How To - Control the screen orientation
How To - Create an icon for an application
How To - Define a rollover icon for an application
How To - Detect when an application or screen moves to the foreground or background
How To - Distinguish between a full menu and a primary actions menu
How to - Leverage pattern matching in BlackBerry smartphone applications to provide an integrated user experience
How to - Make your BlackBerry application more user-friendly
How to - Manage UI interactions
How To - Programmatically determine type of keyboard
How To - Use a background image in application screens
Known Issue - Screen.invalidate() does not cause a subsequent call to paint()
What Is - BlackBerry UI hierarchy
What Is - Image formats used in BlackBerry applications
What Is - Screen buffer size



3. Blackberry Administration API

How To - Get started with the BlackBerry Administration API
What Is - Sample application demonstrating BlackBerry Administration API technology



4. Blackberry JDE


Executing clean.bat does not delete third-party applications from the BlackBerry Smartphone Simulator
How To - Add a Certificate to DeviceKeyStore
How To - Add files to a project
How To - Compile a JAR file into a BlackBerry Library
How To - Compile a MIDlet into a COD file
How To - Compile an application
How To - Configure an application to start automatically when the device is turned on
How To - Configure multiple versions of BlackBerry JDE on the same computer
How To - Configure the BlackBerry Mobile Data Service Simulator to allow reliable push connections
How To - Connect the JDE to a specified simulator bundle
How To - Debug an application running on a live BlackBerry smartphone
How To - Detect a deadlock using the JDE
How to - Detect system availability on startup
How To - Determine the Current Network Name
How To - Enable a keyboard shortcut for an application
How To - Find memory leaks in code
How To - Gain access to the BlackBerry JDE
How To - Get started with the BlackBerry JDE
How To - Obfuscate code for a BlackBerry application
How To - Setup an alternate entry point for my application
How To - Update the Path environment variable
How To - Use Javaloader to take a screen shot
How To - Use the Coverage tool to provide code coverage when testing applications
How To - Use the Profiler tool to optimize application code
How To - Use the RAPC compiler
Support - BlackBerry Java Development Environment and supported locales
Support - BlackBerry JDE 3.7 IDE Fatal Error on startup
Support - BlackBerry JDE crashes when using the Objects view
Support - BlackBerry JDE fails to start
Support - BlackBerry JDE JAR files no longer function after WinRAR is installed
Support - BlackBerry JDE stops responding when viewing project properties
Support - Compiled application size is larger in BlackBerry JDE 4.3.0 or later
Support - Connection Timeout error when launching JDWP from Eclipse
Support - Error - com.sun.tools.javac.code.Symbol$CompletionFailure - file net\rim\device\internal\ui\Border.class not found
Support - Error cod data section too large
Support - Error when debugging - Cannot find RIMIDEWin32Util.dll. This is a required component of the IDE.
Support - How to fix BlackBerry JDE screen artifacts
Support - I/O Error CreateProcess
Support - I/O Error Import file not found appears when building an application
Support - Missing stack map at label
Support - Ordinal 11 could not be located in the dynamic link library DSound.dll
Support - Signing does not apply the RIM Runtime signature key
Support - Unable to Open Socket when running JDWP
Support - Vtable record size exceeds maximum record size
What Is - A library and how to use it
What Is - A stack trace
What Is - Appropriate version of the BlackBerry JDE
What Is - Control Flow Verification Information Too Large
What Is - Introduction to the BlackBerry JDE
What Is - 'javaw' error when starting the JDE after installation
What Is - Supported versions of Java for different BlackBerry JDE versions
What is - The Alias List for a project in the BlackBerry JDE
What Is - The debugger
What Is - The project size limit
What Is - Writing applications for the Java-based BlackBerry Wireless Handhelds in C and C++ native code
 


        

Tuesday, May 15, 2012

Draw painting and save as Image in Blackberry




Draw your paintings and save it as an image. This will help you for doing that.

















Background white image for drawing your paintings.

_bitmap= Bitmap.getBitmapResource("background.png");//white color background image
_signatureField = new SignatureField(_bitmap);
add(_signatureField);


When you press the capture button on the menu, it will save your painting as an image.

private MenuItem _captureItem = new MenuItem("Capture", 200000, 10) {
public void run() {
//Create a new instance of the encoder to encode the bitmap into an image
PNGEncoder encoder = new PNGEncoder(_bitmap, true);
try {
byte[] imageBytes = encoder.encode(true);
EncodedImage image = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
try {
FileConnection fconn = (FileConnection) Connector.open(
new StringBuffer().append("file:///store/home/user/").append("Signature-").append(System.currentTimeMillis()).append(".png").toString());
if (!fconn.exists())
fconn.create();
DataOutputStream ds = fconn.openDataOutputStream();
ds.write(image.getData());
ds.close();
fconn.close();
} catch (IOException e) {
Dialog.alert(e.getMessage());
e.printStackTrace();
}
} catch (IOException e) {
Dialog.alert(e.getMessage());
e.printStackTrace();
}
}
};

/**
* MenuItem to clear the signature field
*/
private MenuItem _clearItem = new MenuItem("Clear", 200000, 10) {
public void run() {
_signatureField.clear();
}

};

/**
* MenuItem to close the application
*/
private MenuItem _closeItem = new MenuItem("Close", 200000, 10) {
public void run() {
onClose();
}
};

/**
* Create the menu
*/
protected void makeMenu(Menu menu, int instance) {
menu.add(_captureItem);
menu.add(_clearItem);
menu.add(_closeItem);
}

final class SignatureField extends BitmapField {

private Graphics _graphics;

/**
* Constructor
*/
public SignatureField(Bitmap b) {
this.setBitmap(b);
_graphics = new Graphics(b);
}

/**
* Handle touch events
*/
protected boolean touchEvent(TouchEvent message) {
try {
if (message.getEvent() == TouchEvent.MOVE) { //Move event fired
//Get the move points
int pointsSize = message.getMovePointsSize();

if (pointsSize > 1)
{
int[] xPoints = new int[pointsSize];
int[] yPoints = new int[pointsSize];
message.getMovePoints(1, xPoints, yPoints, null);
drawPath(xPoints,yPoints);
}
} else if (message.getEvent() == TouchEvent.GESTURE) { //Gesture event fired
TouchGesture gesture = message.getGesture();
if (gesture.getEvent() == TouchGesture.TAP) { //Tap Gesture
//Since we have a tap only draw a single point
int xPoint = message.getX(1);
int yPoint = message.getY(1);
drawPoint(xPoint,yPoint);
} else if (gesture.getEvent() == TouchGesture.SWIPE) { //Swipe Gesture
//Get the move points
int pointsSize = message.getMovePointsSize();
int[] xPoints = new int[pointsSize];
int[] yPoints = new int[pointsSize];
message.getMovePoints(1, xPoints, yPoints, null);
drawPath(xPoints,yPoints);
}
}
} catch (Throwable e) {
throw new RuntimeException(e.toString());
}
return true;
}

/**
* Draw a path through the set of points
*/
private void drawPath(int[] xPoints, int[] yPoints) {
int oldColor = _graphics.getColor();
//Draw a path through the points
_graphics.setColor(Color.RED);
_graphics.drawPathOutline(xPoints,yPoints, null, null, false);
_graphics.setColor(oldColor);
//Repaint
invalidate();
}

/**
* Draw a point
*/
private void drawPoint(int xPoint, int yPoint) {
int oldColor = _graphics.getColor();
_graphics.setColor(0x000000);
_graphics.drawPoint(xPoint, yPoint);
_graphics.setColor(oldColor);
//Repaint
invalidate();
}

/**
* Clear the field
*/
private void clear() {
int oldColor = _graphics.getColor();
_graphics.setColor(0xFFFFFF);
_graphics.fillRect(0, 0, _bitmap.getWidth(), _bitmap.getHeight());
_graphics.setColor(oldColor);
invalidate();
}
}