Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, June 17, 2015

Android: Handling ByteBuffer

In case you are given a structured byteBuffer and you have to cipher the contents of it, here's a quick start up walk through to it.

 //To get relative positioning variables
 short version = byteBufferData.getShort();
 //Besides for getShort(), there's getInt(), getLong(),
 //getDouble(), getChar(). getFloat()
 
 //Or you can use the following to indicate the 
 //position you want to start to read from
 //short shortVar = byteBufferData.getShort(0);
 //but if you use getShort() without any parameters, 
 //it will increase the current position of the 
 //byteBuffer too. Depending on the function used,
 //the position will be increase differently.
 //E.g. getChar(), getShort(), increases by 2
 //getInt(), getFloat(), increases by 4
 //getDouble, getLong(), increases by 8
 
 
 //But what if there's a String of a certain length?
 //For example, you know that the length of the string
 //will be 5. You would need to create the corresponding
 //byte Array first
 final byte[] bytes = new byte[5];
 //then you will get the byte Array that matches the length
 data.get(bytes);
 //then you can pass the byte Array into a String and Voila!!!
 //there you go, a String pulled out from the ByteBuffer
 String filename = new String(bytes);

 //You can use the same steps in the above to control/store
 //binary data for other types of Object too. :)
* Click here to find about the different functions and properties of the 'ByteBuffer' class in
  'Android'.

Friday, January 9, 2015

Android: Taking control of the orientation...

It can be pretty irritating when you have a mixture of screens that should be only be appearing in a Potrait or a Landscape orientation only. Therefore here's a quick demo to show you how you can take control of the orientation of your Android App.

Here's the source code of the Main Activity of the Android Application - MainActivity.java
package com.nekyoutoTech.controloverorientation;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity {
 
 //Dummy Array of Buttons
 private Button[] btns = new Button[5];
 
 //Stores a reference of the Application Context
 private static Context context;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  //Loop through the buttons and assign the Click Listener to them
  for(int i = 0; i < 5; i ++){
   int resID = getResources().getIdentifier("btn" + i, "id", getPackageName());
   btns[i] = (Button) findViewById(resID);
   btns[i].setOnClickListener(btnClickListener);
  }
  
  context = this.getApplicationContext();
 }

 /**
  * Upon clicking on any of the buttons
  */
 OnClickListener btnClickListener = new OnClickListener(){
  @Override
  public void onClick(View v) {
   //Get the String of the button first
   Button btn = (Button) v;
   String text = (String) btn.getText();
   
   //Depending on the button that was click, let's select the orientation
   //that we would want to set for the app.
   int orientation;
   if (context.getResources().getString(R.string.btn0Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
   } else if (context.getResources().getString(R.string.btn1Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
   } else if (context.getResources().getString(R.string.btn2Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
   } else if (context.getResources().getString(R.string.btn3Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
   } else if (context.getResources().getString(R.string.btn4Str).equals(text)) {
    orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
   } else {
    orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
   }
   
   //Let's set the orientation of the app now.
         setRequestedOrientation(orientation);
  }
 };
}
* Click here for the source files of the project.

Sunday, October 26, 2014

Apache Ant: Pushing your Ant script to a whole new level...

If you have been using Apache Ant quite a bit, you will soon realize that it can be pretty annoying at times. You couldn't open up and read a file, you couldn't create Arrays, etc... Therefore there's actually a way to work around it. You can actually use Javascript + Java inside the Ant script environment. And on top of that you can actually manipulate simple basic Ant variables in the Javascript + Java environment.

 <macrodef name="getIndexHtmlContents">
  <sequential>      
   <script language="javascript">
    <![CDATA[
     //Import the necessary Java classes
     importClass(java.io.File);
     importClass(java.io.FileReader);
     importClass(java.io.BufferedReader);

     //We will be reading the value from the Ant Project Property 'filenameProp'
     var filenameProp = GWR.getProperty("filenameProp");

     //Then we will be using BufferedReader and FileReader to read the contents of the file
     var reader = new BufferedReader(new FileReader(new File(filenameProp)));

     //Next we will loop through all the contents of the file and store it in a temporary variable
     var sCurrentLine;
     var strEverything = "";
     while ((sCurrentLine = reader.readLine()) != null) {
      strEverything += sCurrentLine;
     }

     //We will printout the contents of the file/temporary variable on the ant console output
     println(strEverything);

     //Writing the value of the temporary variable and saing it in the Ant Project Property 'fileContents'
     GWR.setProperty("fileContents", strEverything);
    ]]>
   </script>
  </sequential>
 </macrodef>
Though you have specified that you will be writing some script in 'Javascript' syntax, it actually allows Java codes to be written inside that <script> block too.

* Click here to find out more about 'Apache Ant'.

Sunday, July 29, 2012

Android: Playing with System Settings

Probably if you are developing an Android Application, there will be numerous situations which requires you to modify some of the default settings of the Android system. But how to do that? Therefore...

I have created a simple app that will allow you to modify the System settings.
The above are some of the screen captures of the Android Application.

So here comes the source files...
AndroidManifest.xml (Take note of the user permissions.)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zcs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SimpleSystemSettingActivity"
            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>

The main layout file - main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />


    <CheckBox
        android:id="@+id/chkBoxBrightness"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/chkBox" />

    <SeekBar
        android:id="@+id/seekBarBrightness"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:max="255" />

</LinearLayout>

The main application file - SimpleSystemSettingActivity.java
package com.zcs;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;

public class SimpleSystemSettingActivity extends Activity {
 private SeekBar seekBarBrightness;
 private CheckBox chkBoxBrightness;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Grab the components from the main view
        //and assign them to the respective variables
        seekBarBrightness = 
          (SeekBar)findViewById(R.id.seekBarBrightness);
        chkBoxBrightness = 
          (CheckBox)findViewById(R.id.chkBoxBrightness);
        
        //Adding the value change listeners for the
        //components
        seekBarBrightness.setOnSeekBarChangeListener(
          new seekBarChangedListener());
        chkBoxBrightness.setOnCheckedChangeListener(
          new checkBoxChangeListener());
        
        //Call the function updateSettings()
        updateSettings();
    }
    
    //This function will be used to update/retrieve the
    //values of the Screen Brightness and Screen Brightness
    //mode and assign the values to the respective components
    private void updateSettings()
    {
     try {
      //Grabbing the values of the Screen Brightness and 
      //Screen Brightness mode
   int screenBrightnessMode = Settings.System.getInt(
     getContentResolver(), 
     Settings.System.SCREEN_BRIGHTNESS_MODE);
   int screenBrightness = Settings.System.getInt(
     getContentResolver(), 
     Settings.System.SCREEN_BRIGHTNESS);
   
   seekBarBrightness.setProgress(screenBrightness);
   //If the Screen Brightness Mode is Automatic
   if(screenBrightnessMode == 
     Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)
   {
    //we will hide the seek bar and check the 
    //check box
    chkBoxBrightness.setChecked(true);
    seekBarBrightness.setVisibility(View.INVISIBLE);
   }else{
    //else we will show it and uncheck the
    //check box
    chkBoxBrightness.setChecked(false);
    seekBarBrightness.setVisibility(View.VISIBLE);
   }
  } catch (SettingNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
    
    //Change Listener for the seekbar for brightness
    private class seekBarChangedListener implements 
     SeekBar.OnSeekBarChangeListener {
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
         int currentProgress = progress;
         
         //set the screen brightness into the System
         Settings.System.putInt(getContentResolver(), 
           Settings.System.SCREEN_BRIGHTNESS, 
           currentProgress);
         updateSettings();
        }
        public void onStartTrackingTouch(SeekBar seekBar) {}
        public void onStopTrackingTouch(SeekBar seekBar) {}
    }

    //Change Listener for the check bos for brightness mode
    private class checkBoxChangeListener implements 
     CheckBox.OnCheckedChangeListener
    {
  @Override
  public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
   boolean checkValue = isChecked;
   int intCheckValue = (checkValue)?1:0;
         //set the screen brightness mode into the System
   if(intCheckValue == 
     Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)
   {
          Settings.System.putInt(getContentResolver(), 
            Settings.System.SCREEN_BRIGHTNESS_MODE, 
            Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
   }else{
          Settings.System.putInt(getContentResolver(), 
            Settings.System.SCREEN_BRIGHTNESS_MODE, 
            Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);    
   }
         updateSettings();
  }
    }
}

* Click here for the source files of this demo Android Application.
^ Click here for the complete list of System Settings that you can play around.

Saturday, June 23, 2012

Android: Playing with a Singleton

A few weeks ago, I have shown you the steps of creating a Singleton object for Flex applications. As for this week, I am going to show you how to create a Singleton for a Android Application.


Image of Demo Android App.
The App that I am showing in this post will be using the Singleton
object to store the number of clicks.

Main application file - zcs/simpleSingleton/SimpleSingletonActivity.java
package zcs.simpleSingleton;

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

public class SimpleSingletonActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

A reusable Custom Component File - zcs/simpleSingleton/CustomComponent.java
package zcs.simpleSingleton;

import zcs.singleton.MainSingleton;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomComponent extends LinearLayout 
{
 private TextView txt = null;
 
 public CustomComponent(Context context, AttributeSet attrs) {
  super(context, attrs);
  // TODO Auto-generated constructor stub      
  LayoutInflater.from(context).
   inflate(R.layout.layout_custom_component, this, true);
  
  Button btn = (Button) this.findViewById(R.id.btn);
  btn.setOnClickListener(clickListener);
  
  txt = (TextView) this.findViewById(R.id.txt);
 }
 
 // Create a clickListener of type OnClickListener
 // Which will be added to the Button
 private OnClickListener clickListener = new OnClickListener() 
 {
  @Override
  public void onClick(View arg0) {
   //Create an instance of MainSingleton
   MainSingleton tempObj;
   tempObj = MainSingleton.getInstance();
   //Get the current value for Counter and
   //increase it by 1
   int tempCount = tempObj.getCounter() + 1;
   //Set it back to the MainSingleton
   tempObj.setCounter(tempCount);
   
   //Update the text of the label
   txt.setText("Number of Counts:" + tempCount);
  }
 };

}

Main Singleton File - zcs/singleton/MainSingleton.java
package zcs.singleton;

public class MainSingleton 
{
 private static MainSingleton instance;
 
 public static MainSingleton getInstance()
 {
  //If the Singleton is not found, create
  //an instance of it and init / reset the
  //values.
  if(instance == null)
  {
   instance = new MainSingleton();
   instance.reset();
  }
  return instance;
 }
 
 //function to reset data
 public void reset()
 {
  _counter = 0;
 }
 
 //Variable storing the number of counter
 private int _counter = 0;

 public int getCounter() {
  return _counter;
 }

 public void setCounter(int _counter) {
  this._counter = _counter;
 }
 
}
Main Application XML Layout file - layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <zcs.simpleSingleton.CustomComponent
        android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
    <TableLayout 
        android:layout_width="fill_parent"
     android:layout_height="fill_parent">
        <LinearLayout 
            android:layout_width="fill_parent"
      android:layout_height="wrap_content">
         <zcs.simpleSingleton.CustomComponent
          android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
     </LinearLayout>
        <LinearLayout 
            android:layout_width="fill_parent"
      android:layout_height="wrap_content">
         <zcs.simpleSingleton.CustomComponent
          android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>
     </LinearLayout>
     <TableLayout 
         android:layout_width="fill_parent"
      android:layout_height="fill_parent">
         <LinearLayout 
             android:layout_width="fill_parent"
       android:layout_height="wrap_content">
          <zcs.simpleSingleton.CustomComponent
           android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
      </LinearLayout>
         <LinearLayout 
             android:layout_width="fill_parent"
       android:layout_height="wrap_content">
          <zcs.simpleSingleton.CustomComponent
           android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
      </LinearLayout>
     </TableLayout>
    </TableLayout>
</LinearLayout>
Custom Component Layout File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button android:id="@+id/btn"         
         android:text="@string/btn_name"
         android:layout_width="wrap_content"
          android:layout_height="wrap_content"/>
    <TextView android:id="@+id/txt"    
         android:text="@string/txt_name"     
         android:layout_width="wrap_content"
          android:layout_height="wrap_content"/>
</LinearLayout>
* Click here to download the source files of this Android Demo.

Sunday, June 3, 2012

Android: Copying an asset from your App into your Phone.

I was playing some Android Mobile Game the other day and I was wondering how do I create a file from my Android App into the phone itself. If I'm not wrong, I think I have done it before... Hence the journey of code searching starts again.


My Main Android Application file - CopyAssetToPhoneActivity.java
package zcs.copyAsset;

import java.io.IOException;
import java.io.InputStream;

import zcs.utility.io.FileIO;
import zcs.utility.io.FileIOResult;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.widget.TextView;

public class CopyAssetToPhoneActivity 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 food.jpg
        myFile = FileIO.createFile("zcs/copy from assets/food.jpg");
        //Grab the Text View on the layout
     TextView tempTxtView = (TextView)this.findViewById(R.id.txtOutput);
     String strOutput;
     
        if(myFile.get_exist() == 1)
        {
         //If file exist, get contents of file and display it
         strOutput = this.getString(R.string.str_exist);
        }else if(myFile.get_exist() == 0){
         //If file doesn't exist, show a different msg
         strOutput = this.getString(R.string.str_create);
   try {
    //Create a InputStream Instance
          InputStream is;
          //Open the file that is located in the assets
          //folder of your Application as a InputStream
    is = getAssets().open("food.jpg");
    //Write the data into myFile 
    FileIO.writeStreamIntoFile(myFile.get_file(), is);
    //Closes the InputStream
    is.close();
    //Broadcast a Command telling your phone that
    //the sdcard has been mounted again so that it will
    //scan the sdcard for images
    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
      Uri.parse("file://"+ 
      Environment.getExternalStorageDirectory())));
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
        }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));
    }
}

One of my class file used for file I/O - FileIO.java
package zcs.utility.io;

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

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

 /**
  * Writing data to the specified file.
  * Note: Use createFile(String) to gain access to the
  * file first. 
  * @param tempFile - File you are accessing
  * @param in - data you are going to write
  *       in the file
  */ 
 public static void writeStreamIntoFile(File tempFile, InputStream in) throws IOException { 
  OutputStream out = new FileOutputStream(tempFile); 
  // Transfer bytes from in to out 
        int size = in.available();
        
  byte[] buf = new byte[size]; 
  int len; 
  while ((len = in.read(buf)) > 0) { 
   out.write(buf, 0, len); 
  } 
  out.close(); 
 } 
}

One of my class file used for file I/O - FileIOResult.java
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() { } }

My App Manifest file - AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="zcs.copyAsset"
    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=".CopyAssetToPhoneActivity"
            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>

Once you have run the application once, go to gallery and it
will be showing you a new folder that contains a new image.

* Click here to download the source file of the App that I have shown here.

Saturday, May 19, 2012

Android: Queue and Stack

When we talk about Data Structure, the most common terms would most probably be Queue and Stack. A Queue is pretty much the same as a real world Queue (first come first serve theory) and a Stack would be pretty much similar as a Stack of books (first item will be the last to be taken out).

Time to look at my codes. :D
SimpleDataStructureActivity.java
package zcs.dataStructure;

import zcs.utility.dataStructure.Queue;
import zcs.utility.dataStructure.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SimpleDataStructureActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Grab the TextView first
        TextView txtView;
        txtView = ((TextView)findViewById(R.id.lblView));
        txtView.setText("");
        
        //Following codes shows how to use a Queue
        Queue tmpQueue = new Queue();
        txtView.append("====Queue====\n");
        int tempNum;
        for(int i = 0; i < 5; i ++)
        {
         tempNum = (int) Math.floor(Math.random() * 1000);
            txtView.append("Insert " +
              "" + tempNum + " into Queue\n");
            tmpQueue.push(tempNum);
            txtView.append("Queue has " +
              "" + tmpQueue.length() + " items.\n");
        }
        for(int i = 0; i < tmpQueue.length(); i ++)
        {
         tempNum = ((Integer)tmpQueue.getValue(i));
         txtView.append("Item " + i + "" +
          " has a value of " + tempNum +".\n");
        }
        for(int i = 0; i < 5; i ++)
        {
         tmpQueue.pop();
            txtView.append("Queue has " +
              "" + tmpQueue.length() + " items.\n");
            if(!tmpQueue.isEmpty())
            {
             for(int j = 0; j < tmpQueue.length(); j ++)
             {
              tempNum = ((Integer)tmpQueue.getValue(j));
              txtView.append("Item " + j + "" +
               " has a value of " + tempNum +".\n");
             }
            }
        }
        txtView.append("\n\n");
        
        //Following codes shows how to use a Stack
        Stack tmpStack = new Stack();
        txtView.append("====Stack====\n");
        for(int i = 0; i < 5; i ++)
        {
         tempNum = (int) Math.floor(Math.random() * 1000);
            txtView.append("Insert " +
              "" + tempNum + " into Stack\n");
            tmpStack.push(tempNum);
            txtView.append("Stack has " +
              "" + tmpStack.length() + " items.\n");
        }
        for(int i = 0; i < tmpStack.length(); i ++)
        {
         tempNum = ((Integer)tmpStack.getValue(i));
         txtView.append("Item " + i + "" +
          " has a value of " + tempNum +".\n");
        }
        for(int i = 0; i < 5; i ++)
        {
         tmpStack.pop();
            txtView.append("Stack has " +
              "" + tmpStack.length() + " items.\n");
            if(!tmpStack.isEmpty())
            {
             for(int j = 0; j < tmpStack.length(); j ++)
             {
              tempNum = ((Integer)tmpStack.getValue(j));
              txtView.append("Item " + j + "" +
               " has a value of " + tempNum +".\n");
             }
            }
        }
    }
}

Node.java
package zcs.utility.dataStructure;

public class Node {
 
 //The Next Node
 private Node _nextNode = null;

 public Node nextNode() {
  return _nextNode;
 }

 public void nextNode(Node _tempNode) {
  this._nextNode = _tempNode;
 }
 
 //The Prev Node
 private Node _prevNode = null;

 public Node prevNode() {
  return _prevNode;
 }

 public void prevNode(Node _tempNode) {
  this._prevNode = _tempNode;
 }

 //THe Node data
 private Object _data = null;
 
 public Object data() {
  return _data;
 }

 public void data(Object _data) {
  this._data = _data;
 }
}

List.java
package zcs.utility.dataStructure;

public class List {
 protected Node head = null;

 /**
  * Number of items in the list
  * @return int
  */
 public final int length()
 {
  int count = 0;
  Node tempNode = null;
  tempNode = head;
  if(!isEmpty())
  {
   count = 1;
   while(tempNode.nextNode() != null)
   {
    count ++;
    tempNode = tempNode.nextNode();
   }
  }
  return count;
 }
 
 /**
  * Is the list empty
  * 
* -> true when empty *
* -> false when not empty * @return true or false */ public final boolean isEmpty() { return (head == null); } /** * Get the data of the selected Item in the list * based on count * @return Object */ public Object getValue(int count) { Node tempNode = null; int tempCount = 0; if(isEmpty()) { return null; }else{ if(this.length() < count) { return null; }else{ tempNode = head; while(tempCount != count) { tempCount ++; tempNode = tempNode.nextNode(); } return tempNode.data(); } } } /** * Push a Object into the List */ public void push(Object tempObj) { Node newNode = new Node(); newNode.data(tempObj); Node tempNode; if(!isEmpty()) { tempNode = head; while(tempNode.nextNode() != null) { tempNode = tempNode.nextNode(); } tempNode.nextNode(newNode); newNode.prevNode(tempNode); }else{ head = newNode; } } /** * Pop item from the List * @return Object */ public Object pop() { return null; } }

Queue.java
package zcs.utility.dataStructure;

public class Queue extends List {
 /**
  * Pop first item from the List
  * @return Object
  */
 public Object pop()
 {
  Node tempNode = null;
  Node nextNode = null;
  if(!isEmpty())
  {
   tempNode = head;
   if(tempNode.nextNode() != null)
   {
    nextNode = tempNode.nextNode();
    nextNode.prevNode(null);
   }
   head = nextNode;
   tempNode.nextNode(null);
   return tempNode.data();
  }else{
   return null;
  }
 }
}

Stack.java
package zcs.utility.dataStructure;

public class Stack extends List {
 /**
  * Pop last item from the List
  * @return Object
  */
 public Object pop()
 {
  Node tempNode = null;
  Node prevNode = null;
  if(!isEmpty())
  {
   tempNode = head;
   while(tempNode.nextNode() != null)
   {
    tempNode = tempNode.nextNode();
   }
   prevNode = tempNode.prevNode();
   if(prevNode != null)
   {
    prevNode.nextNode(null);
   }else{
    head = null;
   }
   tempNode.prevNode(null);
   return tempNode.data();
  }else{
   return null;
  }
 }
}

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

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SimpleDataStructureActivity"
            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>

* Click here for the source files.

Friday, May 11, 2012

Android: Drag And Drop List

I was thinking since Flex has a Drag and Drop List, Android should have 1 too. Hence, my long search for a Drag and Drop List begins... I managed to find one on the blogspot 'TICE' and I decided to enhance it a bit.

Added features:
  • Besides dragging, upon on the other hotspot of the list, a Toast Message Box will be shown indicating the id of the item
  • Upon dropping an item, display a simple Error Log with the new sequence of items
  • Some visual change

* Click here for the blogspot 'TICE'.
^ Click here for the post on drag and drop list on 'TICE'.
~ Click here for the Drag and Drop List that I had enhanced.

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 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.