Thursday, April 11, 2013

On change ObectChoiceField, change it relative ObjectChoiceField Value


Blackberry we use ObjectChoiceField this example demo for check one choice field value change then it will effect other relatively choice field. Like when you change country then it should be change state and it city. Please see in code that help full and save lot of time.

ocfCountry.setChangeListener(new FieldChangeListener() {
   
 public void fieldChanged(Field field, int context) {
  // TODO Auto-generated method stub
  //ObjectChoiceField test= (ObjectChoiceField)field;
    
  int curInx = ocfCountry.getSelectedIndex();
  if(previIndexOfCountry != curInx && lolPre != curInx){
   System.out.println("Change Call.."+curInx);
   stateArray = setStateFromCountry(countryArray[curInx]);
   ocfState.setChoices(stateArray);
   cityArray = setCityFromState(stateArray[0]);
   ocfCity.setChoices(cityArray);
   invalidate();
  }
  if(curInx==0){
   System.out.println("Change Call.."+curInx);
   stateArray = setStateFromCountry(countryArray[curInx]);
   ocfState.setChoices(stateArray);
   cityArray = setCityFromState(stateArray[0]);
   ocfCity.setChoices(cityArray);
   invalidate();
  } 
  lolPre = ocfCountry.getSelectedIndex();
 }
});

Hope it will save your development time.

Monday, March 25, 2013

Call HTTP Post method on Blackberry

As Continues work on Blackberry today i need to integrated http POST method on blackberry. If you want to implement POST method on Blackberry following code will very help full to you. Nothing you have to do anything just parse parameter one is Post URL. you can use URL as following format.

http://yourdomainname/webservicenamehere.php

public StringBuffer httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {
  
  StringBuffer bodyData = new StringBuffer(256);
  ConnectionFactory conFactory = new ConnectionFactory();
  conFactory.setTimeLimit(1000);
  HttpConnection conn = (HttpConnection) conFactory.getConnection(urlStr)
    .getConnection();
  conn.setRequestMethod(HttpConnection.POST);
  conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");

  StringBuffer sb = new StringBuffer();
  for (int i = 0; i < paramName.length; i++) {
   sb.append(paramName[i]);
   sb.append("=");
   sb.append(paramVal[i]);
   sb.append("&");
  }
  byte[] postData = sb.toString().getBytes("UTF-8");
  conn.setRequestProperty("Content-Length",
    new Integer(postData.length).toString());

  OutputStream out = conn.openOutputStream();
  out.write(postData);
  out.close();

  // This writes to our connection and waits for a response
  if (conn.getResponseCode() != 200) {
   throw new Exception(conn.getResponseMessage());
  }
  InputStream inputStream = conn.openInputStream();
  byte[] data = new byte[256];
  int len = 0;
  int size = 0;
  while (-1 != (len = inputStream.read(data))) {
   bodyData.append(new String(data, 0, len, "UTF-8"));
   size += len;
  }

  if (inputStream != null) {
   inputStream.close();
  }
  return bodyData;
 }
Hope it will help full. don't forget to write comment.

Read All Blackberry Contact using PIM


It easy to read contact on blackberry mobile plz use this following code that read most of parameter that we need to developed mobile app.

System.out.println("********************************************");
  try{
  String numberWork="",numberHome="",numberMobile="",numberOther="",numberPager="",numberFax="";
  BlackBerryContactList contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
  Enumeration enumContacts = contactList.items();
  while (enumContacts.hasMoreElements()) {
   BlackBerryContact c = (BlackBerryContact) enumContacts.nextElement();
   if ((contactList.isSupportedField(BlackBerryContact.NAME))
     && (c.countValues(BlackBerryContact.NAME) > 0)) {
    name = c.getStringArray(BlackBerryContact.NAME, 0);
    String firstName = name[BlackBerryContact.NAME_GIVEN];
    String lastName = name[BlackBerryContact.NAME_FAMILY];
    String fullname = "";
    if (firstName != null) {
     fullname += firstName + " ";
    }

    if ((contactList.isSupportedField(BlackBerryContact.TEL))
      && (c.countValues(BlackBerryContact.TEL) > 0)) {
     int numValues = 0;
     try {
      numValues = c.countValues(BlackBerryContact.TEL);
     } catch (Exception localException) {
     }
     
     for (int i = 0; i < numValues; ++i) {
      if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_WORK)
        numberWork = c.getString(BlackBerryContact.TEL, i);
      else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_HOME)
        numberHome = c.getString(BlackBerryContact.TEL, i);
      else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_MOBILE)
       numberMobile = c
         .getString(BlackBerryContact.TEL, i);
      else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_OTHER)
       numberOther = c.getString(115, i);
      else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_PAGER)
       numberPager = c.getString(BlackBerryContact.TEL, i);
      else if (c.getAttributes(BlackBerryContact.TEL, i) == BlackBerryContact.ATTR_FAX) {
       numberFax = c.getString(BlackBerryContact.TEL, i);
      }
     }

     System.out.println("Mobile Number: "+ numberMobile);
     System.out.println("Work Number: " + numberWork);
     System.out.println("Home Number: " + numberHome);
     System.out.println("Numebr Pager " + numberPager);
     System.out.println("Fax Number" + numberFax);
     System.out.println("Other Number" + numberOther);
    }

   }

  }
  }catch(Exception e){
   System.out.println(e);
  }
  System.out.println("********************************************");
Hope it save your development time.

Parsing JSON object in Blackberry

Some time on sending http request server return JSON object so on blackberry side we need to write code that we can parse that object in display value on screen.

Following code is use full for parsing Json object in blackberry
To implement this code you need following lib on your project so plz download it from github.

https://github.com/upictec/org.json.me/

void parseJSONResponceInBB(String jsonStrFormat){  
     String[] readObject = {"Action"}; // Here my Json have "Action" Object to read you can change according your value.
        try {  
            JSONObject json = new JSONObject(jsonInStrFormat);  
            JSONObject jsonObj  = (JSONObject) json.get("result"); // You can change value according your return object.
            add(new LabelField(jsonObj.get(readObject[1])));
           
        } catch (JSONException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
    }

Hope this code help full.
There are some application we need to set GMT instated to sent current time. Following code will help to get accurate Blackberry GMT hours.

Calendar rightnow = Calendar.getInstance(TimeZone.getDefault());
int offsetDST = TimeZone.getDefault().getOffset(1, rightnow.get(Calendar.YEAR), rightnow.get(Calendar.MONTH), rightnow.get(Calendar.DAY_OF_MONTH), rightnow.get(Calendar.DAY_OF_WEEK), rightnow.get(Calendar.MILLISECOND));
System.out.println("Offset (Daylight Savings): "+ offsetDST);
System.out.println(("Offset (Without Daylight Savings): "+ TimeZone.getDefault().getRawOffset()));
System.out.println("GNT Time: "+(float)offsetDST/3600000);
  
this.timezone = ""+(float)offsetDST/3600000;

System.out.println("GMT: "+timezone);

Hope this code will help full.

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/