Friday, April 27, 2012

Android: Playing with Services

Android Services is something that is pretty much similar to your windows background services. It is something that will be running in the background that requires an minimal amount of memory usage. The following would be a simple demo that I had created to help you to understand it better.

Shows a notification
appearing on the top menu bar
Shows the main notification.


Time for some crazy source codes...
SimpleServicesActivity.java
package zcs.simpleServices;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SimpleServicesActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Set the layout of this App
        setContentView(R.layout.main);
        
        //Send out this broadcast to check for our
        //BroadcastReceiver now.
        Intent intent = new Intent
          ("zcs.simpleServices.BroadcastFromApp");
        sendBroadcast(intent);
    }
}

MainReceiver.java
package zcs.simpleServices.broadcaster;

import zcs.simpleServices.service.zcsSimpleService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MainReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {  
  Intent service = new Intent(context, 
    zcsSimpleService.class);
  //Run the service 'zcsSimpleService' now.
  context.startService(service);
 }
}

zcsSimpleService.java
package zcs.simpleServices.service;

import java.util.Date;

import zcs.simpleServices.SimpleServicesActivity;

import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class zcsSimpleService extends Service {
 private static final int HELLO_ID = 1;

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) 
 {
  Date now = new Date();
  
  //If the number of minutes of the current time ends
  //with a multiple of 5
  if(now.getMinutes() % 5 == 0)
  {
   //Create an instance of NotificationManager
   NotificationManager notificationManager =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
   
   //Set a simple icon for the notification that appears
   //on the top thin bar of a Android phone
   int icon = R.drawable.alert_light_frame;
   //And a simple message
   CharSequence tickerText = "Message from ZCSSimpleServices";
   long when = System.currentTimeMillis();
   //Create an instance of Notification and assign the
   //values in to above to it
   Notification notification = 
     new Notification(icon, tickerText, when);

   //The subject of your message
   CharSequence contentTitle = "Hello there...";
   now.setSeconds(0);
   //The body of your message
   CharSequence contentText = "The time now is " + now.toGMTString();
   //What should this notification do upon clicking
   Intent notificationIntent = 
     new Intent(this, SimpleServicesActivity.class);
   //Giving NotificationManager the rights to run your actions
   PendingIntent pendingIntent = 
     PendingIntent.getActivity(this, 0, notificationIntent, 0);
   //populating notification will all the other info
   //Note: this is what you will be getting when you
   //drag the top menu bar to the bottom of the screen.
   notification.setLatestEventInfo(this, contentTitle, 
     contentText, pendingIntent);
   notification.flags = Notification.FLAG_AUTO_CANCEL;
   //Show the notification now.
   notificationManager.notify(HELLO_ID, notification);
  }
  
  return Service.START_NOT_STICKY;
 } 
 
 @Override
 public IBinder onBind(Intent intent) 
 {
  return null;
 }
}

FirstRunReceiver.java
package zcs.utility.receiver;

import zcs.simpleServices.broadcaster.MainReceiver;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class FirstRunReceiver extends BroadcastReceiver {
 
 // Restart service every minute
 private static final long REPEAT_TIME = 1000 * 60;
 
 @Override
 public void onReceive(Context context, Intent intent) {
  //Create a instance of AlarmManager, which is used
  //to make continuous action every REPEAT_TIME or minute
  AlarmManager service = (AlarmManager) context
    .getSystemService(Context.ALARM_SERVICE);
  //The class that will be executed after each interval
  Intent i = new Intent(context, MainReceiver.class);
  //Assigning rights to AlarmManager to run the actions
  PendingIntent pending = PendingIntent.getBroadcast(
    context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

  //Fetch every minute and InexactRepeating allows 
  //Android to optimize the energy consumption
  service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
    0, REPEAT_TIME, pending);
 }
}

StartupReceiver.java
package zcs.utility.receiver;

import java.util.Date;
import java.util.Calendar;

import zcs.simpleServices.broadcaster.MainReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.app.AlarmManager;
import android.app.PendingIntent;

public class StartupReceiver extends BroadcastReceiver {

 private boolean hasRun = false;
 
 @Override
 public void onReceive(Context context, Intent intent) {
  //Validate whether a similar AlarmManager has
  //been created
  boolean alarmUp = (PendingIntent.getBroadcast(context, 0, 
         new Intent(context, MainReceiver.class), 
         PendingIntent.FLAG_NO_CREATE) != null);

  if (alarmUp)
  {
  }
  else
  {
   //If the AlarmManager have not been created,
   //we will need to create it.

   //Create a instance of AlarmManager, which is used
   //to make an action after some time
   AlarmManager Service = (AlarmManager) context.
     getSystemService(Context.ALARM_SERVICE);
   //The class that will be executed after each interval
   Intent i = new Intent(context, FirstRunReceiver.class);
   //Assigning rights to AlarmManager to run the actions
   PendingIntent pending = PendingIntent.getBroadcast(
     context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
   
   //Some crazy calculation to find out how far are
   //we to the next minute.
   Date now = new Date();
   int lapse = 0;
   lapse = 60 - now.getSeconds() + 1;
   //As this BroadcastReceiver will run own its own
   //after the phone boot up successfully, we will want
   //to wait more than 30 sec before we run the 
   //action of the Alarm Manager
   //This is done so that the continuous action of
   //FirstRunReceiver will be executed when we
   //reaches 60 seconds.
   if(lapse < 30)
   {
    lapse += 60;
   }
   
   Calendar cal = Calendar.getInstance(); 
   cal.add(Calendar.SECOND, lapse);
   
   //We will only be executing this action once
   //only.
   Service.set(AlarmManager.RTC_WAKEUP, 
     cal.getTimeInMillis(), pending);
   hasRun = true;
  }
 }
}

AndroidManifest.xml



    
    

    
        
            
                
                
            
        
        
  
        
            
                
            
            
                
            
        
        
        
        
        
    


* Click here for the source files.

Friday, April 20, 2012

Flex 3: Custom List Renderers

Let's just face it. A simple list that shows only plain text isn't sufficient. Therefore today I'm going to show how you can create a list with custom renderers.

Here are the source codes... My Main application 'ListDragAndDrop.mxml'
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute"
     creationComplete="creationCompleteEvent(event)">
 <mx:Script>
  <![CDATA[
   import event.RendererEvent;
   
   import mx.collections.ArrayCollection;
   import mx.collections.XMLListCollection;
   import mx.events.DragEvent;
   import mx.events.FlexEvent;
   
   import renderer.CustomItemRenderer;
   
   private var dataArray:ArrayCollection;
   //Data for the list on the right
   private var tempRStr:String = "<data>" +
    "<item><name>Item r1</name><id>r1</id></item>" +
    "<item><name>Item r2</name><id>r2</id></item>" +
    "<item><name>Item r3</name><id>r3</id></item>" +
    "<item><name>Item r4</name><id>r4</id></item>" +
    "<item><name>Item r5</name><id>r5</id></item>" +
    "</data>";
   private var tempRXML:XML = null;
   
   //Data for the list on the left
   private var tempLStr:String = "<data>" +
    "<item><name>Item l1</name><id>l1</id></item>" +
    "<item><name>Item l2</name><id>l2</id></item>" +
    "<item><name>Item l3</name><id>l3</id></item>" +
    "<item><name>Item l4</name><id>l4</id></item>" +
    "<item><name>Item l5</name><id>l5</id></item>" +
    "</data>";
   private var tempLXML:XML = null;
   
   //Variable to store the selected item
   private var currComponent:* = null;
   
   //Variable to store the selected item's id.
   private var selectedID:String = "";
   
   //Upon creation complete, populate the list on the left and right.
   protected function creationCompleteEvent(event:FlexEvent):void
   {
    dataArray = new ArrayCollection();
    tempLXML = new XML(tempLStr);
    for each(var item:Object in tempLXML.item);
    {
     item.selected = false;
    }
    list1.dataProvider = tempLXML.item;
    tempRXML = new XML(tempRStr);
    for each(item in tempRXML.item);
    {
     item.selected = false;
    }
    list2.dataProvider = tempRXML.item;
    this.addEventListener(RendererEvent.CLICK_ITEM, dataEvent);
   }
   
   /*
    This function will do a few things.
    //1) Remove the selected state of the previous selected item.
    //2) Grab the info of the selected item.
    //3) CHange the label of the button to indicate where you
    //   will be moving the item to.
   */
   private function dataEvent(evt:RendererEvent):void
   {
    if(currComponent)
    {
     (currComponent as CustomItemRenderer).
      isSelected = false;
    }
    currComponent = null;
    selectedID = "";
    btn.label = "-"
    if(evt.component)
    {
     var selectedStr:String = 
      (evt.component as CustomItemRenderer).id;
     currComponent = evt.component;
     selectedID = selectedStr;
     
     var foundObject:Object;
     foundObject = checkList4Data(list1, selectedID);
     if(foundObject.found)
     {
      list2.selectedIndex = -1;
      btn.label = "->"
     }else{
      list1.selectedIndex = -1;
      btn.label = "<-"
     }
    }
   }
   
   //Once the user drag and drop one of the items, reset the
   //state of the selected item and change the label of the
   //button to the original state.
   protected function dragDropHandler(event:DragEvent):void
   {
    if(currComponent)
    {
     (currComponent as CustomItemRenderer).
      isSelected = false;
     currComponent = null;
    }
    btn.label = "-";
   }
   
   //This function will handle all the moving of selected item
   //from left to right and right to left.
   protected function clickHandler(event:MouseEvent):void
   {
    if(currComponent)
    {
     (currComponent as CustomItemRenderer).
      isSelected = false;
     currComponent = null;
    }
    var foundObject:Object;
    var selectedObject:Object;
    if(selectedID != "")
    {
     foundObject = checkList4Data(list1, selectedID);
     if(!foundObject.found)
     {
      foundObject = checkList4Data(list2, selectedID);
      selectedObject = foundObject.tempXML.
       removeItemAt(foundObject.foundNum);
      list2.dataProvider = foundObject.tempXML;
      foundObject.tempXML = 
       XMLListCollection(list1.dataProvider);
      if(!foundObject.tempXML)
      {
       foundObject.tempXML = new XMLListCollection();
      }
      foundObject.tempXML.addItem(selectedObject);
      list1.dataProvider = foundObject.tempXML;
     }else{
      selectedObject = foundObject.tempXML.
       removeItemAt(foundObject.foundNum);
      list1.dataProvider = foundObject.tempXML;
      foundObject.tempXML = 
       XMLListCollection(list2.dataProvider);
      if(!foundObject.tempXML)
      {
       foundObject.tempXML = new XMLListCollection();
      }
      foundObject.tempXML.addItem(selectedObject);
      list2.dataProvider = foundObject.tempXML;
     }
    }
    selectedID = "";
    btn.label = "-";
   }
   
   //Base of the given list, this function will check for the
   //existance of the item that has the same id that was
   //similar to tempStr;
   private function checkList4Data(tempList:List, 
           tempStr:String):Object
   {
    var tempObject:Object = new Object();
    tempObject.found = false;
    tempObject.tempXML = 
     XMLListCollection(tempList.dataProvider);
    if(tempObject.tempXML)
    {
     for(var i:int = 0; i < tempObject.tempXML.length; i ++)
     {
      if(tempObject.tempXML[i].id == selectedID)
      {
       tempObject.found = true;
       tempObject.foundNum = i;
       break;
      }
     }
    }
    return tempObject;
   }
  ]]>
 </mx:Script>
 <mx:VBox width="100%" height="100%"
    verticalGap="0">
  <mx:Spacer height="100%"/>
  <mx:HBox width="100%" height="100%" 
     horizontalGap="0"
     verticalAlign="middle">
   <mx:Spacer width="100%"/>
   <mx:List id="list1"   
      paddingTop="0"
      paddingBottom="0"
      paddingLeft="0"
      paddingRight="0"
      width="100%"
      dragEnabled="true"
      dragMoveEnabled="true"
      dropEnabled="true" 
      dragDrop="dragDropHandler(event)"
      itemRenderer="renderer.CustomItemRenderer"/>
   <mx:Spacer width="20"/>
   <mx:Button click="clickHandler(event)"
        width="50"
        id="btn"
        label="-"/>
   <mx:Spacer width="20"/>
   <mx:List id="list2"    
      paddingTop="0"
      paddingBottom="0"
      paddingLeft="0"
      paddingRight="0"
      width="100%"
      dragEnabled="true" 
      dragDrop="dragDropHandler(event)"
      dragMoveEnabled="true"
      dropEnabled="true"
      itemRenderer="renderer.CustomItemRenderer"/>
   <mx:Spacer width="100%"/>
  </mx:HBox>
  <mx:Spacer height="100%"/>
 </mx:VBox>
</mx:Application>
event/RendererEvent.as
package event
{
 import flash.events.Event;
 
 import mx.core.UIComponent;
 
 /*
  This function handles all the clicking and selection of
  all the items. Although it's pretty heavy for the 
  demo to store the item that is currently selected,
  but to make things easier, this is a fastest way.
 */ 
 public class RendererEvent extends Event
 {
  public static const CLICK_ITEM:String = "CLICK_ITEM";
  private var _component:UIComponent;

  public function get component():UIComponent
  {
   return _component;
  }

  public function set component(value:UIComponent):void
  {
   _component = value;
  }

  public function RendererEvent(type:String, 
           component:UIComponent,
           bubbles:Boolean=false, 
           cancelable:Boolean=false)
  {
   _component = component;
   super(type, bubbles, cancelable);
  }
 }
}
renderer/CustomItemRenderer.mxml
<s;?xml version="1.0" encoding="utf-8"?>
<s;mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
     mouseDown="mouseDownHandler(event)"
     mouseOut="mouseOutHandler(event)"
     mouseOver="mouseOverHandler(event)"
     click="clickHandler(event)"
     mouseChildren="false" backgroundColor="#FF6666"
     creationComplete="creationCompleteEvent(event)">
 <s;mx:Script>
  <s;![CDATA[
   import mx.events.FlexEvent;
   import event.RendererEvent;
   /*
     This is a Component for Custom Renderer that I will
     be using in a list.
   */
   
   //This property will be used to determine whether
   //this item has been selected.
   private var _isSelected:Boolean = false;

   public function get isSelected():Boolean
   {
    return _isSelected;
   }

   //If it is selected give it a light green background
   //else a light red color will do.
   public function set isSelected(value:Boolean):void
   {
    _isSelected = value;
    if(!_isSelected)
    {
     this.setStyle("backgroundColor", 0xFF6666);
    }else{
     this.setStyle("backgroundColor", 0x66FF66); 
    }
   }

   //Mousedown handler
   protected function mouseDownHandler(event:MouseEvent):void
   {
    if(!_isSelected)
    {
     this.setStyle("backgroundColor", 0x66FF66);
    }else{
     this.setStyle("backgroundColor", 0x66FF66); 
    }
   }
   
   //Mouseout handler 
   //When this item is selected, the background should still 
   //remains in light green, else light red will do.
   protected function mouseOutHandler(event:MouseEvent):void
   {
    if(!_isSelected)
    {
     this.setStyle("backgroundColor", 0xFF6666);
    }else{
     this.setStyle("backgroundColor", 0x66FF66); 
    }
   }
   
   //Mouseover handler 
   //When this item is selected, the background should still 
   //remains in light green, else light red will do.
   protected function mouseOverHandler(event:MouseEvent):void
   {
    if(!_isSelected)
    {
     this.setStyle("backgroundColor", 0x6666FF);
    }else{
     this.setStyle("backgroundColor", 0x66FF66); 
    }
   }
   
   //Mouse click handler 
   //Upon clicking, it will dispatch an event indicating 
   //that this item was been selected or unselected.
   protected function clickHandler(event:MouseEvent):void
   {
    _isSelected = !_isSelected;
    if(_isSelected)
    {
     this.dispatchEvent(new RendererEvent(
      RendererEvent.CLICK_ITEM, this, true));
    }else{
     this.dispatchEvent(new RendererEvent(
      RendererEvent.CLICK_ITEM, null, true));
    }
   }
   
   //Upon creation of this item, based on the data that we are
   //getting, change the color of the background.
   protected function creationCompleteEvent(event:FlexEvent):void
   {
    if(data)
    {
     if(data.selected == "true")
     {
      isSelected = true;
     }else{
      isSelected = false;
     }
    }
   }
   
  ]]>
 <s;/mx:Script>
 <s;!-- 
  data is a property that can work within this component
  If you want to point to any of the property in data, you
  need to create a property like the following.
 -->
 <s;mx:String id="id">{data.id}<s;/mx:String>
 <s;mx:HBox width="100%" height="20" horizontalGap="0">
  <s;mx:Label id="lbl" text="{data.name}"/>
  <s;mx:Spacer width="100%"/>
 <s;/mx:HBox>
<s;/mx:Canvas>
* Click here for the demo.
^ Click here for the source files.

Friday, April 13, 2012

AS3: Load a image without uploading it

In the past, if you want to create a flash site that allows user to upload their own image, you probably would need to upload the image to a server and retrieve it back after uploading. This can be quite lame. But in Flash Player 10 onwards, you can throw the step of connecting to a server away and attract the file you have uploaded immediately.

Time to take a look at some codes:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" horizontalAlign="center"
     verticalAlign="middle" width="100%"
     height="100%">
 <mx:Script>
  <![CDATA[
   import flash.net.FileReference;
   
   import mx.events.FlexEvent;
   import mx.utils.Base64Encoder;
   
   private var fileRef:FileReference = new FileReference();
   
   //On Clicking on button 'browse', show dialog box
   //that only allows either jpg or gif or png.
   protected function clickHandler(event:MouseEvent):void
   {
    fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]);
    fileRef.addEventListener(Event.SELECT, onFileSelected);
   }
   
   //After the user has make a selection, 
   protected function onFileSelected(e:Event):void {
    fileRef.addEventListener(Event.COMPLETE, onFileLoaded);
    fileRef.load();
   }
   
   //load the image onto the Image component.
   //And you are done.
   protected function onFileLoaded(e:Event):void {
    imgLoader.load(e.target.data);
   }
  ]]>
 </mx:Script>
 <mx:VBox horizontalAlign="center" verticalAlign="middle"
    paddingBottom="10" paddingLeft="10" 
    paddingRight="10" paddingTop="10"
    width="100%" height="100%">
  <mx:Button id="browse" label="Browse" click="clickHandler(event)"/>
  <mx:Image id="imgLoader"/>
 </mx:VBox>
</mx:Application>

* Click here for the demo.
^ Click here for the source files.

Friday, April 6, 2012

Android: Simple file IO... Back to square 1...

Haven't been touching Android for a very long so I decided to spend a bit of time playing with it. And here's my first tutorial on Android.

Here are my codes for this application.
SimpleFileIOActivity.java
package zcs.simpleFileIO;

import java.util.Date;

import zcs.utility.io.FileIO;
import zcs.utility.io.FileIOResult;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;

public class SimpleFileIOActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        FileIOResult myFile;
        //Create file data.txt
        //or you can try "zcs/tester/wonder/try.txt" 
        //as a file name and it will create the respective
        //folders and files
        myFile = FileIO.createFile("try.txt");
        //Grab the Text View on the layout
     TextView tempTxtView = (TextView)this.findViewById(R.id.txtOutput);
     String strOutput;
     String strToday = "";
     Date tempDate = new Date();
     //Create a string that has today's date
     strToday = tempDate.toString();
     
        if(myFile.get_exist() == 1)
        {
         //If file exist, get contents of file and display it
         strOutput = this.getString(R.string.str_exist);
         strOutput = strOutput.replace("{0}", 
           FileIO.readContentFromFile(myFile.get_file()));
        }else if(myFile.get_exist() == 0){
         //If file doesn't exist, show a different msg
         strOutput = this.getString(R.string.str_create);
        }else{
         //Error occurred
         strOutput = this.getString(R.string.str_error);
        }
        //Show the text base on the condition of the file.
        tempTxtView.setText(Html.fromHtml(strOutput));

        //Update the file with the latest date.
        if(myFile.get_exist() <= 1)
        {
         FileIO.writeContentIntoFile(myFile.get_file(), strToday);
        }
    }
}
FileIO.java <- file that handles all the IO functions
package zcs.utility.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;

public class FileIO {
 
 /**
  * Function that will create the specified file
  * name.
  * @param tempPath - path of the file you are 
  *       trying to access
  * @return FileIOResult Object
  *
  */ 
 public static FileIOResult createFile(String tempPath)
 {
  FileIOResult tempResult = new FileIOResult();
  //Check if the App has access to the External 
  //Storage first.
  boolean mExternalStorageWriteable = false;
  String state = Environment.getExternalStorageState();

  if (Environment.MEDIA_MOUNTED.equals(state)) {
      // We can read and write the media
      mExternalStorageWriteable = true;
  } else {
      // Something else is wrong. 
   // It may be one of many other states, but all we need
      // to know is we can neither read nor write
      mExternalStorageWriteable = false;
  }  
  //If we have access to the storage
  if(mExternalStorageWriteable)
  {
   String tempFilePath = tempPath;
   if(!tempFilePath.startsWith("/"))
   {
    tempFilePath = "/" + tempFilePath;
   }
         File root = Environment.getExternalStorageDirectory();
         File tempFile = new File(root + tempPath);
         //Check if file exist         
         if(!tempFile.exists())
         {
          //split the string and grab all the folders first 
          String[] strPathArray = tempFilePath.split("/");
          //Create all the folders first
          String strFolder = "";
          for(int i = 0; i < (strPathArray.length - 1); i ++)
       {
           strFolder = strFolder + "/" + strPathArray[i];
       }
       File sdDir = new File(root + strFolder);
          if(!sdDir.exists()){
           sdDir.mkdirs();
          }
          //Create File Path
    tempFile = new File(root + strFolder, 
         strPathArray[strPathArray.length - 1]);
         }
         try {
          //Check for file existence.
          if(tempFile.exists())
          {
           tempResult.set_exist(1);
          }else{
           tempResult.set_exist(0);
          }
          //If file doesn't exist, let's make one. 
          if(!tempFile.exists())
          {
           tempFile.createNewFile();
          }
   } catch (IOException e) {
    e.printStackTrace();
   }
         tempResult.set_file(tempFile);
  }else{
      tempResult.set_exist(2);
  }
  return tempResult;
 }

 /**
  *
  * Writing contents to the specified file.
  * Note: Use createFile(String) to gain access to the
  * file first. 
  * @param tempFile - File you are accessing
  * @return contents as a string
  */ 
 public static String readContentFromFile(File tempFile)
 {
  FileInputStream fis = null;    
  int ch;
     StringBuffer strContent = new StringBuffer("");
  try 
  {
   fis = new FileInputStream(tempFile);
      while((ch = fis.read()) != -1)
      {
       strContent.append((char)ch);
      }
  } catch (Exception e) 
  {
   e.printStackTrace();
  } finally
  {
            try
            {
             fis.close();
             fis = null;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
  }
  return strContent.toString();
 }


 /**
  * Writing contents to the specified file.
  * Note: Use createFile(String) to gain access to the
  * file first. 
  * @param tempFile - File you are accessing
  * @param value - value you are going to write
  *       in the file
  */ 
 public static void writeContentIntoFile(File tempFile, String value)
 {
  FileOutputStream fos = null;
  try 
  {
   fos = new FileOutputStream(tempFile);

   fos.write(value.getBytes(),0,value.getBytes().length);
   fos.flush();
  } catch (Exception e) 
  {
   e.printStackTrace();
  } finally
  {
            try
            {
                fos.close();
                fos = null;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
  }
 }
}
FileIOResult.java <- Object that stores the results of the File IO
package zcs.utility.io;

import java.io.File;

public class FileIOResult { 
 private int _exist = 0;
 private File _file = null;

 /**
  * Used to check for the existance of the file.  
  * @return one of the below integer (0-2)
  *  
0 - file does not exist and it will
  *    be created
  *  
1 - file exist
  *  
2 - Error
  */ 
 public int get_exist() {
  return _exist;
 }

 public void set_exist(int _exist) {
  this._exist = _exist;
 }

 public File get_file() {
  return _file;
 }

 public void set_file(File _file) {
  this._file = _file;
 }

 public FileIOResult() {
 }
}

AndroidManifest.xml <- Take note of the permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="zcs.simpleFileIO"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".SimpleFileIOActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

This screen will be shown
if file doesn't exist.
This screen will be shown
if file exist.

* Click here for the source files.