A Guide to Mobile and Web Technology(LAMP)

Posts tagged ‘blackberry’

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

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

Upload files from Mobile using Android

create a folder name uploads with 777 permission.

create a file name upload.php in the same folder where the uploads folder is created.

Place the code in the file named upload.php


$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}

Client side code that is used to send file to a server. please include the following code in our client program.


private void doFileUpload(){

  HttpURLConnection conn = null;
  DataOutputStream dos = null;
  DataInputStream inStream = null;

 // The full path of filename which is to be uploaded to server
  String exsistingFileName = "test.mp3";
 
  String lineEnd = "\r\n";
  String twoHyphens = "--";
  String boundary =  "*****";


  int bytesRead, bytesAvailable, bufferSize;

  byte[] buffer;

  int maxBufferSize = 1*1024*1024;


  String responseFromServer = "";

  //Server path to the upload.php
  String urlString = "http://xxx.xxx.xxx.xxx/upload.php";


  try
  {
   //------------------ CLIENT REQUEST

  FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

   // open a URL connection to the Servlet

   URL url = new URL(urlString);


   // Open a HTTP connection to the URL

   conn = (HttpURLConnection) url.openConnection();

   // Allow Inputs
   conn.setDoInput(true);

   // Allow Outputs
   conn.setDoOutput(true);

   // Don't use a cached copy.
   conn.setUseCaches(false);

   // Use a post method.
   conn.setRequestMethod("POST");

   conn.setRequestProperty("Connection", "Keep-Alive");

   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

   dos = new DataOutputStream( conn.getOutputStream() );

   dos.writeBytes(twoHyphens + boundary + lineEnd);
   dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
   dos.writeBytes(lineEnd);

   System.out.println("Headers are written");

   // create a buffer of maximum size

   bytesAvailable = fileInputStream.available();
   bufferSize = Math.min(bytesAvailable, maxBufferSize);
   buffer = new byte[bufferSize];

   // read file and write it into form...

   bytesRead = fileInputStream.read(buffer, 0, bufferSize);

   while (bytesRead &gt; 0)
   {
    dos.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
   }

   // send multipart form data necesssary after file data...

   dos.writeBytes(lineEnd);
   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

   // close streams
   System.out.println("File is written");
   fileInputStream.close();
   dos.flush();
   dos.close();


  }
  catch (MalformedURLException ex)
  {
      System.out.println(ex.toString());
  }

  catch (IOException ioe)
  {
      System.out.println(ioe.toString());
  }


  //------------------ read the SERVER RESPONSE


  try {
        inStream = new DataInputStream ( conn.getInputStream() );
        String str;
      
        while (( str = inStream.readLine()) != null)
        {
            //the str contains the server response   
         System.out.println("Server Response"+str);
        }
        inStream.close();   
  }
  catch (IOException ioex){
       System.out.println(ioe.toString());
  }

}

If the file is sucessfully uploaded the response will be

The file test.mp3 has been uploaded.

otherwise the response will be

There was an error uploading the file, please try again!