A Guide to Mobile and Web Technology(LAMP)

Archive for March, 2011

How to split a string in to array of strings in Blackberry

The following code block shows how to split a string in to array of strings in blackberry.

private String[] split(String strString, String strDelimiter) {
        String[] strArray;
        int iOccurrences = 0;
        int iIndexOfInnerString = 0;
        int iIndexOfDelimiter = 0;
        int iCounter = 0;
    
        //Check for null input strings.
        if (strString == null) {
            throw new IllegalArgumentException("Input string cannot be null.");
        }
        //Check for null or empty delimiter strings.
        if (strDelimiter.length() <= 0 || strDelimiter == null) {
            throw new IllegalArgumentException("Delimeter cannot be null or empty.");
        }
    
        if (strString.startsWith(strDelimiter)) {
            strString = strString.substring(strDelimiter.length());
        }
    
        //If strString does not end with the delimiter then add it
        //to the string in order to comply with the desired format.
        if (!strString.endsWith(strDelimiter)) {
            strString += strDelimiter;
        }
    
        //Count occurrences of the delimiter in the string.
        //Occurrences should be the same amount of inner strings.
        while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
            iIndexOfInnerString)) != -1) {
            iOccurrences += 1;
            iIndexOfInnerString = iIndexOfDelimiter +
                strDelimiter.length();
        }
    
        //Declare the array with the correct size.
        strArray = new String[iOccurrences];
    
        //Reset the indices.
        iIndexOfInnerString = 0;
        iIndexOfDelimiter = 0;
    
        //Walk across the string again and this time add the
        //strings to the array.
        while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
            iIndexOfInnerString)) != -1) {
    
            //Add string to array.
            strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter);
    
            //Increment the index to the next character after
            //the next delimiter.
            iIndexOfInnerString = iIndexOfDelimiter +
                strDelimiter.length();
    
            //Inc the counter.
            iCounter += 1;
        }
    
        return strArray;
    }//fn split

To make the function call

String delimit = ",";
String mainStr = "apple, banana, orange, pineapple, cherry";
String[] fruits = split(mainStr , delimit); 

How to convert a byte Array to Base64 String in Blackberry

The following code block shows how to convert a byte array in to base64 string

private String encodeBase64( byte[] toEncode, int offset, int length ) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(length);
        Base64OutputStream base64OutputStream = new Base64OutputStream( byteArrayOutputStream );
        try{
            base64OutputStream.write( toEncode, offset, length );
            base64OutputStream.flush();
            base64OutputStream.close(); 
        }
        catch (IOException ioe){
            System.out.println("Error in encodeBase64() : "+ioe.toString());
            return null;
        }
        return byteArrayOutputStream.toString();
}//fn encodeBase64

The following code shows how how to convert base64 encoded string to bytes

byte[] decoded = Base64InputStream.decode(base64str);

How to convert a Byte Array to Hex String

The following code block helps you to convert a byte array to hex string format.

private String byteArrayToHexString(byte in[]){
        byte ch = 0x00;
        int i = 0;
        if (in == null || in.length <= 0){
            return null;
        }
        String pseudo[] = {"0", "1", "2","3", "4", "5", "6", "7", "8","9", "A", "B", "C", "D", "E", "F"};
        StringBuffer out_str_buf = new StringBuffer(in.length * 2);
        while (i < in.length){
            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
            ch = (byte) (ch >>> 4);     // shift the bits down
            ch = (byte) (ch & 0x0F);    // must do this is high order bit is on!
            out_str_buf.append(pseudo[ (int) ch]); // convert the nibble to a String Character
            ch = (byte) (in[i] & 0x0F); // Strip off low nibble
            out_str_buf.append(pseudo[ (int) ch]); // convert the nibble to a String Character
            i++;
        }
        String rslt = new String(out_str_buf);
        return rslt;
    }

How to do file operations in BlackBerry

Code to read data from a file

byte[] fulldata = null;
//Assign the name of the file to read the contents with full path
String filename = "/store/home/user/pictures/test.txt";
if (filename != null) {
    FileConnection file = (FileConnection) Connector.open("file://" +filename, Connector.READ);
    //Get the file size
    int fileSize = (int) file.fileSize();
    if (fileSize > 0) {
	fulldata = new byte[fileSize];
	InputStream input = file.openInputStream();    
	try{
	   input.read(fulldata);
	}
	catch(Exception sfg){
	    System.out.println(sfg.toString());
	}
	input.close();   
    }
    file.close();
}

Code to write data to a file

This function allows you to write byte array to the file specified.

//data -> byte array (Original data to be  written)
//filename -> name of the file in which those data has to be written

public static void writeFileData(byte[] data, String filename) {
        FileConnection file = null;
        OutputStream out = null;
        try {
            file = (FileConnection) Connector.open("file:///store/home/user/pictures/" + filename, Connector.READ_WRITE);
            if (file.exists())
                file.delete();
            
            file.create();
            out = file.openOutputStream();
            out.write(data);
        } 
        catch (IOException e) {
            System.out.println("Problem in writeFile : " + e.toString());
        } 
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (file != null && file.exists()) {
                    if (file.isOpen()) {          
                        file.close();
                    }
                }
            } 
            catch (IOException ioe) {
                System.out.println("Error while closing file: " + ioe);
            }
        }
    }//fn writeFileData

Code to delete a file


String filename = "/store/home/user/pictures/test.txt";
FileConnection file = null;
try {
    file = (FileConnection) Connector.open("file://" + filename, Connector.READ_WRITE);
} 
catch (IOException e) {
    System.out.println("Error in file connection : "+e.toString());
} 
finally {
    try {
	if (file != null && file.exists()) {                        
	    file.delete();
	}
    } 
    catch (IOException ioe) {
	System.out.println("Error in file deletion : "+ioe.toString());
    }
}
Follow

Get every new post delivered to your Inbox.

Join 38 other followers