Saturday, July 14, 2012

Reading Bytes from InputStream

To develop blackberry application we continues need to reading file and communication to socket server. Today we study simple utility to reading bytes from input stream. Because inputstream use to read data from file as well as socket(TCP) connection.

Here we believe that "in" is Inputstream variable.

1. Read fully inputstream from file:

long dataLength = is.available();// here we get length of readable data on inputstream

byte[] bytes = new byte[(int) dataLength];
is.read(bytes);
String fileData = new String(bytes);
System.out.println(fileData);
This example we can't read socket inputstream. Following example use to read socket inputstream.

2. Read fully inputstream form TCP/Socket connection:

public byte[] getBytesFromInputStream(InputStream is){ 
 try{
 byte[] bytes = null;
  try {
    int dataLength = input.readInt();
    System.out.println("Read Data: "+dataLength);
    bytes = new byte[dataLength];
    int totalRead = 0;
    while(totalRead < dataLength){
      int read = input.read(bytes,totalRead,dataLength-totalRead);
      totalRead+=read;
    }
 System.out.println("Size of Byte Array: "+bytes.length +" Data "+bytes);
 }catch (Exception e) {
    System.out.println(">>>>>>>" + e);
 }
 return bytes;
}
Hope helpfull..

Friday, July 6, 2012

Blackberry Reliable Network Connection

Now a day so many application require to establish network connection In Blackberry there are no simple way to pass only URL and get connection. In blackberry there are more then Five type of connection available. Developer have to confirm which connection available so that can use on application. On Blackberry developer have to pass suffix after URL if device have wifi connection available then "interface=wifi" suffix is use.

Following Type of Connection available:

1. Blackberry Enterprise server using Blackberry Mobile Data System(MSD)

2. Blackberry Internet Service

3. Wireless(WiFi)

4. WAP 1.x

5. WAP 2.0

There are lot of problem when you establish connection on blackberry following example will resolve most of connection problem.


/**


* Determines what connection type to use and returns the necessary string
* to use it.
* @return A string with the connection info
*/

private String getConnectionString() {

// This code is based on the connection code developed by Mike Nelson of AccelGolf.
// http://blog.accelgolf.com/2009/05/22/blackberry-cross-carrier-and-cross-network-http-connection

String connectionString = null;
// Simulator behavior is controlled by the USE_MDS_IN_SIMULATOR
// variable.


if (DeviceInfo.isSimulator()) {

    logMessage("Device is a simulator and USE_MDS_IN_SIMULATOR is false");
    connectionString = ";deviceside=true";
}

// Wifi is the preferred transmission method

else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
    logMessage("Device is connected via Wifi.");
    connectionString = ";interface=wifi";
}

// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) ==  CoverageInfo.COVERAGE_DIRECT) {
    logMessage("Carrier coverage.");

String carrierUid = getCarrierBIBSUid();

if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP  network
    logMessage("No Uid");
    connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS request
    logMessage("uid is: " + carrierUid);
    connectionString = ";deviceside=false;connectionUID="+ carrierUid + ";ConnectionType=mds-public";
}

}

// Check for an MDS connection instead (BlackBerry Enterprise Server)

else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {

    logMessage("MDS coverage found");
    connectionString = ";deviceside=false";
}

// If there is no connection available abort to avoid bugging the user unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
    logMessage("There is no available connection.");
}

// In theory, all bases are covered so this shouldn't be reachable.
else {
    logMessage("no other options found, assuming device.");
    connectionString = ";deviceside=true";
}
return connectionString;

}


/**
* Looks through the phone's service book for a carrier provided BIBS
* network
* 
* @return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid() {

    ServiceRecord[] records = ServiceBook.getSB().getRecords();
    int currentRecord;

   for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
     if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
      if (records[currentRecord].getName().toLowerCase().indexOf("bibs") >= 0) {
        return records[currentRecord].getUid();

      }

   }

 }

return null;
}

private void logMessage(String msg){
   System.out.println(msg);
}


Help and Source from: http://www.localytics.com/blog/2009/how-to-reliably-establish-a-network-connection-on-any-blackberry-device/

Tuesday, June 19, 2012

Blackberry Indicator Icon and Notification message

Today I want to share some interesting topic was display indicator icon and notification message on blackberry. That is use to display push notification, custom alert, reminder etc. I have user to notification and indicator icon on task management application.

1. Create Blackberry application new project ex: "testmessageIndicator".

2. Create new class "DemoMessage.java" and copy following code
package mypackage;

import java.util.Date;

import net.rim.blackberry.api.messagelist.ApplicationMessage;
import net.rim.device.api.system.*;


/**
 * This class provides a sample implementation of the ApplicationMessage
 * interface. It demonstrates how an application can define its own message
 * formats for use with the message store.
 */
public final class DemoMessage implements ApplicationMessage
{
    static final int DEMO_MESSAGE_TYPE = 0x01;

    private String _sender;
    private String _subject;
    private String _message;
    private long _receivedTime;
    private boolean _isNew;
    private boolean _deleted;
    private String _replyMessage;
    private long _replyTime;
    private EncodedImage _previewPicture;


    /**
     * Creates a new DemoMesage object
     */
    public DemoMessage()
    {
        _isNew = true;
    }


    /**
     * Constructs a DemoMessage object with specified properties
     * 
     * @param sender The name of the sender
     * @param subject The subject of the message
     * @param message The body of the message
     * @param receivedTime The time stamp for when the message was received
     */
   public DemoMessage(String sender, String subject, String message, long receivedTime)
    {
        _sender = sender;
        _subject = subject;
        _message = message;
        _receivedTime = receivedTime;
        _isNew = true;
    }


    /**
     * Stores the reply message and sets the reply time
     * 
     * @param message The reply message
     */
    void reply(String message)
    {
        markRead();
        _replyMessage = message;
        _replyTime = System.currentTimeMillis();
    }


    /**
     * Marks this message as deleted
     */
    void messageDeleted()
    {
        _isNew = false;
        _deleted = true;
    }


    /**
     * Marks this message as new
     */
    void markAsNew()
    {
        _isNew = true;
        _replyMessage = null;
    }


    /**
     * Marks this message as read
     */
    void markRead()
    {
        _isNew = false;
    }


    /**
     * Indicates whether this message is new or not
     * 
     * @return True if the message is new, false otherwise
     */
    boolean isNew()
    {
        return _isNew;
    }


    /**
     * Indicates whether this message has been replied to or not
     * 
     * @return True if the message has been replied to, false otherwise
     */
    boolean hasReplied()
    {
        return _replyMessage != null;
    }


    /**
     * Sets the name of the sender who sent this message
     * 
     * @param sender The name of the sender
     */
    void setSender(String sender)
    {
        _sender = sender;
    }


    /**
     * Sets the subject of this message
     * 
     * @param subject The subject of this message
     */
    void setSubject(String subject)
    {
        _subject = subject;
    }


    /**
     * Sets the time at which this message was received
     * 
     * @param receivedTime The time at which this message was received
     */
    void setReceivedTime(long receivedTime)
    {
        _receivedTime = receivedTime;
    }


    /**
     * Sets the message body
     * 
     * @param message The message body
     */
    void setMessage(String message)
    {
        _message = message;
    }


    /**
     * Retrieves the message body
     * 
     * @return The message body
     */
    String getMessage()
    {
        return _message;
    }


    /**
     * Sets the preview picture for this message
     * 
     * @param image The desired preview picture of this message
     */
    void setPreviewPicture(EncodedImage image)
    {
        _previewPicture = image;
    }


    // Implementation of ApplicationMessage ------------------------------------
    /**
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getContact()
     */
    public String getContact()
    {
        return _sender;
    }


    /**
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getStatus()
     */
    public int getStatus()
    {  // Form message list status based on current message state
        if(_isNew)
        {
            return MyApp.STATUS_NEW;
        }
        if(_deleted)
        {
            return MyApp.STATUS_DELETED;
        }
        if(_replyMessage != null)
        {
            return MyApp.STATUS_REPLIED;
        }
        return MyApp.STATUS_OPENED;
    }


    /**
     * 
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getSubject()
     */
    public String getSubject()
    {
        if(_replyMessage != null)
        {
            return "Re: " + _subject;
        }
        else
        {
            return _subject;
        }
    }


    /**
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getTimestamp()
     */
    public long getTimestamp()
    {
        return _receivedTime;
    }


    /**
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getType()
     */
    public int getType()
    {
        // All messages have the same type
        return DEMO_MESSAGE_TYPE;
    }


    /**
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getPreviewText()
     */
    public String getPreviewText()
    {
        if(_message == null)
        {
            return null;
        }

        StringBuffer buffer = new StringBuffer(_message);

        if(_replyMessage != null)
        {
            buffer.append(". You replied on ").append(new Date(_replyTime)).append(": ").append(_replyMessage);
        }

        return buffer.length() > 100 ? buffer.toString().substring(0, 100) + " ..." : buffer.toString();
    }


    /**
     *@see net.rim.blackberry.api.messagelist.ApplicationMessage#getCookie(int)
     */
    public Object getCookie(int cookieId)
    {
        return null;
    }


    /**
     * 
     * @see net.rim.blackberry.api.messagelist.ApplicationMessage#getPreviewPicture()
     */
    public Object getPreviewPicture()
    {
        return _previewPicture;
    }
}

@source form MessageListDemo Demo example. This example you can also download from github.

3. Create new class " MyApp.java" and copy following code this is main class of application.
package mypackage;

import net.rim.blackberry.api.messagelist.ApplicationMessage;
import net.rim.device.api.ui.UiApplication;

/**
 * This class extends the UiApplication class, providing a
 * graphical user interface.
 */
public class MyApp extends UiApplication
{
    /**
     * Flag for replied messages. The lower 16 bits are RIM-reserved, so we have
     * to use higher 16 bits.
     */
    static final int FLAG_REPLIED = 1 << 16;

    /**
     * Flag for deleted messages. The lower 16 bits are RIM-reserved, so we have
     * to use higher 16 bits.
     */
    static final int FLAG_DELETED = 1 << 17;
 static final int BASE_STATUS = ApplicationMessage.Status.INCOMING;
    static final int STATUS_NEW = BASE_STATUS | ApplicationMessage.Status.UNOPENED;
    static final int STATUS_OPENED = BASE_STATUS | ApplicationMessage.Status.OPENED;
    static final int STATUS_REPLIED = BASE_STATUS | ApplicationMessage.Status.OPENED | FLAG_REPLIED;
    static final int STATUS_DELETED = BASE_STATUS | FLAG_DELETED;

    /**
     * Entry point for application
     * @param args Command line arguments (not used)
     */ 
    public static void main(String[] args)
    {
        // Create a new instance of the application and make the currently
        // running thread the application's event dispatch thread.
        MyApp theApp = new MyApp();       
        theApp.enterEventDispatcher();
    }
    

    /**
     * Creates a new MyApp object
     */
    public MyApp()
    {        
        // Push a screen onto the UI stack for rendering.
        pushScreen(new MyScreen());
    }    
}
4. Now create MyScreen.java and copy following code this is display screen and initialize icon and message indicator. 5. Set Indicator icon on /img folder please set name "Indicator.png" if image name different then please specify on code.
import java.util.Vector;

import net.rim.blackberry.api.messagelist.ApplicationFolderIntegrationConfig;
import net.rim.blackberry.api.messagelist.ApplicationIcon;
import net.rim.blackberry.api.messagelist.ApplicationIndicator;
import net.rim.blackberry.api.messagelist.ApplicationIndicatorRegistry;
import net.rim.blackberry.api.messagelist.ApplicationMessageFolder;
import net.rim.blackberry.api.messagelist.ApplicationMessageFolderRegistry;
import net.rim.device.api.collection.ReadableList;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.container.MainScreen;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class MyScreen extends MainScreen
{
    /**
     * Creates a new MyScreen object
     */
    public MyScreen()
    {        
     
        setTitle("Title");
        
  ReadableListImpl mylist= new ReadableListImpl();
        ApplicationMessageFolder folder = null;
        ApplicationFolderIntegrationConfig config = new   ApplicationFolderIntegrationConfig(true, true, ApplicationDescriptor.currentApplicationDescriptor());
        
        if(ApplicationMessageFolderRegistry.getInstance().getApplicationFolder(0x33c7ce29883abe5fL)==null){
             folder = ApplicationMessageFolderRegistry.getInstance().registerFolder(0x33c7ce29883abe5fL, "Test Folder", new ReadableListImpl(),config );

        }else {
             folder = ApplicationMessageFolderRegistry.getInstance().getApplicationFolder(0x33c7ce29883abe5fL);
        }
        
        //DemoMessage source is available in the messagelistdemo.
        DemoMessage msg = new DemoMessage("me@here.com", "Pizza Toppings","What would you like on your pizza?", System.currentTimeMillis());

        mylist.addMessage(msg);

        folder.fireElementAdded(msg,true);
        System.out.println("nr of messages"+folder.hasNewMessages());

        ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
         EncodedImage image = EncodedImage.getEncodedImageResource("Indicator.png" );
            ApplicationIcon icon = new ApplicationIcon( image );
        ApplicationIndicator indicator = reg.register( icon, false, true);
        
        indicator.setNotificationState(true);
        ApplicationIndicator appIndicator = reg.getApplicationIndicator();
        
        
        appIndicator.setIcon(icon);
        appIndicator.setValue(appIndicator.getValue() + 1);
       // appIndicator.setNotificationState(true);
        appIndicator.setVisible(true);

    }
    
    /**
     * This is an implementation of the ReadableList interface which stores the
     * list of messages using a Vector.
     */
    static class ReadableListImpl implements ReadableList
    {
        private Vector messages;

        /**
         * Creates a empty instance of ReadableListImpl
         */
        ReadableListImpl()
        {
            messages = new Vector();
        }


        /**
         * @see net.rim.device.api.collection.ReadableList#getAt(int)
         */
        public Object getAt(int index)
        {
            return messages.elementAt(index);
        }


        /**
         * @see net.rim.device.api.collection.ReadableList#getAt(int, int, Object[], int)
         */
        public int getAt(int index, int count, Object[] elements, int destIndex)
        {
            return 0;
        }


        /**
         * @see net.rim.device.api.collection.ReadableList#getIndex(Object)
         */
        public int getIndex(Object element)
        {
            return messages.indexOf(element);
        }


        /**
         * @see net.rim.device.api.collection.ReadableList#size()
         */
        public int size()
        {
            return messages.size();
        }


        /**
         * Add a message to this list
         * 
         * @param message The message to add to this list
         */
        void addMessage(DemoMessage message)
        {
            messages.addElement(message);
        }
        

        /**
         * Removes a message from this list
         * 
         * @param message The message to remove from this list
         */
        void removeMessage(DemoMessage message)
        {
            messages.removeElement(message);
        }
    }
}

6. Run application.
7. Output
Indicator Icon display:



















Notification Icon display:



Saturday, May 5, 2012

Getting start with Blackberry 10 and Tablet development with HTML/WebWorks.


1. What's the WebWorks Application?
A Blackberry WebWorks application is simply a standalone web application that you can deploy to a Blackberry smartphone or tablet.

2. Process of creating application.

i) Create your application web file(like HTML, CSS, JavaScript).
ii) Test and debug your application with the Ripple emulator.
iii) Create a WebWorks configuration documents (config.xml) that contains details of your application like App name, App description, icon etc.
iv) Package you application using the Ripple emulator.
v) For Blackberry 10 application or Blackberry tablet application deploy the .bar file to a Blackberry device or simulator. We are go through Blackberry 10 and Tablet development.

3. Download/Install WebWorks SDK:
  1. Download the BlackBerry WebWorks SDK for BlackBerry Tablet OS from the Downloads page.
  2. In the folder where you downloaded the BlackBerry WebWorks SDK, double-click the installation file.
  3. On the Introduction screen, click Next.
  4. On the License Agreement screen, accept or decline the terms of the license agreement and click Next.
  5. On the Choose Install Folder screen, select a location to install the BlackBerry WebWorks SDK and click Next.
  6. On the Choose Adobe AIR SDK Install Folder screen, select the location where the AIR SDK is installed, and click Next.
  7. On the Pre-Installation Summary screen, click Install.
  8. When the installation completes, click Done to close the installer.
Now Install Blackberry webworks install process completed.

     4.   Download/Install Ripple emulator on windows?

Note: Before you install a newer version of the Ripple Emulator, uninstall the previous version.
  1. Locate the Ripple installer file that you downloaded to your computer, and run the installer.
  2. Click Next to start the installation process.
  3. Review the license agreement, and if you agree to the terms, select the I accept the terms of the License Agreement option and click Next.
  4. Specify a location where you want to install the Ripple Emulator, and click Next.
  5. Review the pre-installation summary, and then click Install.
  6. Click Done when the installation process completes.

Configure Ripple Emulator on Chrome Browser if you have not Chrome browser please download it.
1. From the installation folder, click the ripple_ui.crx file and drag it into the browser window.
2. Please press Add.
3. Display Output.
 

Now  Ripple Emulator process completed..


2.       Create Configuration:
3.       Package and Deploy:

More Info:
https://bdsc.webapps.blackberry.com/html5/documentation/ww_getting_started/What_Is_A_WebWorks_App_1845471_11.html