Monthly Archives: April 2011

Customizing your button or TextView or another view in ANDROID.

Beautifying our applications is one of the main features of your application’s success.
In ANDROID there are many possible ways to do this.
For eg. We need to have different colors for our buttons, However we can give backgrounds for buttons and all. But we can do many by using our custom xml files, like changing colors on button press and release, transitions etc. This tutorial explains such an example. Extend this example to create your own custom button.

Create a fresh project and copy this code to your main file.

package pack.coderzheaven;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class SelectorExample extends Activity {
    private Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b = (Button) findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("Button clicked!!");
			}
		});

        ImageButton button = (ImageButton) findViewById(R.id.button);
        TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
        drawable.startTransition(5000);

        Resources res = getResources();
        Drawable shape = res. getDrawable(R.drawable.gradient_box);

        TextView tv = (TextView)findViewById(R.id.textview);
        tv.setBackgroundDrawable(shape);
    }
}

Now the main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">

	<ImageButton android:id="@+id/button"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:src="@drawable/transition">
	</ImageButton>

	<TextView
		android:id="@+id/textview"
		android:text="CoderzHeaven"
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent" />
	<Button android:id="@+id/Button01"
		android:background="@drawable/buttonhighlight"
		android:layout_height="50px"
		android:layout_width="fill_parent"
		android:text="CoderzHeaven"	>
	</Button>
</LinearLayout>

Now create an xml file named “gradient_box.xml” in your drawable folder and copy this code to it.
This xml helps you to define the shape for the view for which you are applying this.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFF0000"
        android:endColor="#80FF00FF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Now create an xml file named “transition.xml” in your drawable folder and copy this code to it.
This xml file is for applying a transition for your view

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/on" />
    <item android:drawable="@drawable/off" />
</transition>

Now the AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.selectors"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SelectorExample"
                  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>

Note: Make sure that you have all the images in your drawable folder as shown in the image below.

See the ImageButton transformation in the consequent pictures.


Please leave your comments if you find this post useful!

How to detect single/double/triple taps in iPhone ?

Hi,
How can you detect single/double/triple taps in iPhone using Objective C?
Use the following code to detect single or multiple taps in iPhone/iPad/iPod.
The code can also be used with Cocos2D & Box2D.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *urtouch = [touches anyObject];

    NSUInteger urtapCount = [urtouch tapCount];

    switch (urtapCount) {

       case 1:
         NSLog(@"Single Tap Detected!");
          break;

       case 2:
          NSLog(@"Double Tap Detected!");
          break;

       case 3:
        NSLog(@"Triple Tap Detected!");
        break;

      default :
       break;

   }
}

Try it out! You can even detect Quadrup!
:)

How to use tableView in Titanium, iPhone or ANDROID?

This tutorial shows how to create a tableview in Titanium and add data to it.
How to handle a click function in the tableView and get the data from the row.


   /* Create a new window */
   var win = Titanium.UI.createWindow({
			backgroundColor:'#336699',
			backgroundImage:'images/bkg.png',
			navBarHidden:true,
			tabBarHidden:true
	});

	/* Datasource for the tableView */
    var my_data = [
		{title:'data1'},
		{title:'data2'},
		{title:'data3'},
		{title:'data4'},
		{title:'data5'}
	];

    var tableview = Titanium.UI.createTableView({
		data:my_data,
		top:0
	});

	/* Alternately you can use this to set the datasource in the tableView.
	tableview.setData(my_data);
	*/

	/* this will handle the click function in the tableView */
	tableview.addEventListener('click', function(e)
	{
		e.rowData.hasCheck = true;		 // add a checkmark to the row.
		var title = e.rowData.title;	       // get the title property of the clicked row.
                var index = e.index;                     // got the clicked index;
                Ti.API.info("Clicked on index : " + index + "with row title : " + title);
	});

	win.add(tableview); 				// add the tableview to the window.

	win.open();							// open the window.

Please leave your valuable comments.

C Sharp/C# – String Uppercase/Lowercase Conversion

Hi,

It will be very useful to know how you can convert a given string into uppercase or lowercase using program.
We are going to show you , how to convert a given string into uppercase or lowercase using C Sharp/C#. See the example given below.

using System;

class MainClass {
  public static void Main() {

    string sampleString = "CoDeRzHeAvEn";

    string strLwrCase = sampleString .ToLower();
    string strUprCase =  sampleString .ToUpper();

    Console.WriteLine("Lowercase of sampleString :n " +  strLwrCase );
    Console.WriteLine("Uppercase of sampleString :n " +  strUprCase );

  }
}

Output :
Lowercase of sampleString :
coderzheaven
Uppercase of sampleString :
CODERZHEAVEN

:)

jQuery Hide & Show Toggle – An Example

Hi,

Want to try out a simple hide and show toggle using jQuery? The example given below shows how you can simply hide and show a paragraph in html using jQuery. Try it out!

&lt;html&gt;
&lt;head&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;jquery.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

$(document).ready(function(){

  $(&quot;#hideMe&quot;).click(function(){
    $(&quot;p&quot;).hide();
  });

  $(&quot;#showMe&quot;).click(function(){
    $(&quot;p&quot;).show();
  });

});

&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;p&gt;Coderz Heaven! Click 'HideMe' for hiding! Click 'ShowMe' for showing&lt;/p&gt;
&lt;button id=&quot;hideMe&quot;&gt;HideMe&lt;/button&gt;
&lt;button id=&quot;showMe&quot;&gt;ShowMe&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

:)

Cocos2D CCMenu – An Example

Hi,

While using cocos2D you may need to create some scenes with menu items on it. This example given below shows , how to create a cocos2D menu scene with menu items using images. You can have your own custom fancy image text indicating menu items using this.


//Creating the three menu items.
//You can use different images for selected view & normal view.
//On clicking menu will show selectedImage
CCMenuItemImage *Item1 = [CCMenuItemImage
                        itemFromNormalImage:@"Walk.png"
                        selectedImage:@"WalkTwo.png"
                        target:self
                        selector:@selector(walkAction:)];

CCMenuItemImage *Item2 = [CCMenuItemImage
			           itemFromNormalImage:@"Run.png"
				       selectedImage:@"RunTwo.png"
				       target:self
				       selector:@selector(runAction:)];

CCMenuItemImage *Item3 = [CCMenuItemImage
				       itemFromNormalImage:@"Jump.png"
				       selectedImage:@"JumpTwo.png"
				       target:self
				       selector:@selector(jumpAction:)];

//Adding menu items to the CCMenu. Don't forget to include 'nil'
CCMenu *selectMenu= [CCMenu menuWithItems:Item1, Item2, Item3, nil];
//Aligning & Adding CCMenu child to the scene
[selectMenu alignItemsVertically];
[self addChild:selectMenu];


//Different functions on below get called according to the menu item clicked.
- (void)walkAction:(id)sender
{
    [[CCDirector sharedDirector] replaceScene:[WalkingScene node]];
}

- (void)runAction:(id)sender
{
   [[Director sharedDirector] replaceScene:[runningScene node]];
}

- (void)jumpAction:(id)sender
{
    [[Director sharedDirector] replaceScene:[jumpingScene node]];
}

:)

Android: Conversion to Dalvik format failed: Unable to execute dex: null

This error often comes when your android project size is large.

Try the following steps to remove the error

1. Clean the project

Project > Clean

2. Increase the memory allocated in eclipse.ini

Open the eclipse.ini file in the the Eclipse folder. Then edit

-Xms128m to -Xmx512m or something higher

Hope this help you

Compare two strings in C Sharp/C# – Case Insensitive

Hi,

Sometimes you may need to check whether two strings are equal or not equal by checking case insensitive. See the example below to see how to achieve the same using C Sharp /C#.

using System;

class MainClass {
  public static void Main() {

    string strOne = "heaven";

    string strTwo = "HEAVEN";

    if(String.Compare(strOne , strTwo , true) == 0)
      Console.WriteLine(strOne + " and " + strTwo + " are equal - Case Insensitive!");

    else
      Console.WriteLine(strOne + " and " + strTwo + " are not equal - Case Insensitive!");

  }
}

Output : heaven and HEAVEN are equal – Case Insensitive!

:)

Program to generate Fibonacci series in C Sharp/C#

Hi,

Here is a simple program to generate Fibonacci series using C Sharp /C#. It will generate Fibonacci numbers < 100.

class MainClass
{

  public static void Main()
  {
    int oldNum = 1;

    int presentNum = 1;

    int nextNum;

    System.Console.Write(presentNum + ",");

    while (presentNum < 100)
    {
      System.Console.Write(presentNum + ",");

      nextNum = presentNum + oldNum;

      oldNum = presentNum;

      presentNum = nextNum;
    }
  }
}

:)

How to create and delete a directory in SdCard in ANDROID?

Hi all……

This is a simple example to create and delete a directory in ANDROID.
Here the directly is created in the SDCARD. So first create an SDCARD and start the emulator with the SDCARD.

Let’s look at the program.
Use can use this program to create or delete a file in ANDROID also.

package pack.coderzheaven;

import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CreateDeleteDIR_Example extends Activity {

    Button b;
    TextView t;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        t = (TextView)findViewById(R.id.tv);
        b= (Button) findViewById(R.id.Button01);
        File dir = new File("/sdcard/new_dir");
        try{
          if(dir.mkdir()) {
             System.out.println("Directory created");
             t.setText("Directory created");
          } else {
             System.out.println("Directory is not created");
             t.setText("Directory is not created");
          }
        }catch(Exception e){
          e.printStackTrace();
        }

        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File del = new File("/sdcard/new_dir");
				 boolean success = del.delete();
			        if (!success) {
			           System.out.println("Deletion of directory failed!");
			        }
			}
        });

    	/* IF THE DIRECTORY IS NOT EMPTY . USE THIS FUNCTION */
	public static boolean deleteNon_EmptyDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteNon_EmptyDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	    return dir.delete();
	}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tv"
    />
<Button
	android:text="Delete Directory"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Now go to File-explorer in the window menu->show View and see the result.

After directory creation.

After directory deletion.

How to place a label or textBox or anyother control inside a tableView in Titanium, ANDROID or iPhone ?

Hi all……..
This tutorial is for Titanium users. This tutorial explains how to place a textBox or anyother control inside a tableView.
A tableview requires data in the form of a array, so we create an array (here array is named “data_array“) by adding the controls like textboxes and labels inside it. You can give a large number of properties to customize the controls. i have given some of them.

                var data_array= [];  // This is the array that we are going to give to the tableView.

                /* creating a textField to place in the tableView */
                var name_tf = Titanium.UI.createTextField({
			color:'#336699',
			hintText: 'Enter Name',
			height:45,
			value: "",
			left:100,right:10,
			textAlign:'right',
			autocorrect:false,
			scrollable:false,
			clearButtonMode:Titanium.UI.INPUT_BUTTONMODE_ONFOCUS,
			borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE
		});

               var place_tf = Titanium.UI.createTextField({
			color:'#336699',
			hintText: 'Enter place',
			height:45,
			value: "",
			left:100,right:10,
			textAlign:'right',
			autocorrect:false,
			scrollable:false,
			clearButtonMode:Titanium.UI.INPUT_BUTTONMODE_ONFOCUS,
			borderStyle:Titanium.UI.INPUT_BORDERSTYLE_NONE
		});

              function addFirstRow()
		{
			var row = Ti.UI.createTableViewRow({height:45});
			row.backgroundColor = '#ffffff';
			row.selectedBackgroundColor = '#ffffff';

                        /* creating a label to place in the tableView */
			var label = Titanium.UI.createLabel({
					color:'#000', height:45,left:10,text:'App Name', width:280,
					font:{fontSize:18,fontFamily:'Arial', fontWeight:'bold'}
			});

			row.add(label);
			row.add(name_tf );
			row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
			row.className = 'control';
			data_array[0] = row;
		}

               function addSecondRow()
		{
			var row = Ti.UI.createTableViewRow({height:45});
			row.backgroundColor = '#ffffff';
			row.selectedBackgroundColor = '#ffffff';

			var label = Titanium.UI.createLabel({
					color:'#000', height:45,left:10,text:'App Name', width:280,
					font:{fontSize:18,fontFamily:'Arial', fontWeight:'bold'}
			});

			row.add(label);
			row.add(place_tf );
			row.selectionStyle = Ti.UI.iPhone.TableViewCellSelectionStyle.NONE;
			row.className = 'control';
			data_array[1] = row;
		}

                addFirstRow();    /* calling the above functions */
                addSecondRow();

              /* Creating a tableView and placing the TextBox and Label inside it
                  here data is the property for which we have to provide the data-source */

               var tableview = Titanium.UI.createTableView({
			data:data_array,
			height:260,
			width:320,
			backgroundColor:'transparent',
			scrollable:'false',
			style:Titanium.UI.iPhone.TableViewStyle.GROUPED,
			top:25
		});

Now you have created a tableView with 2 controls in each row.
Make sure to add this to your window to view it.
Please leave your comments if this post was useful.

Get files from a directory – C#/C Sharp

Hi,

Sometimes you may need to get the files from a specified directory using C# / C Sharp. See the sample code on how it works.

using System;
using System.IO;

class MainClass
{
  public static void Main()
  {
    string[] yourFiles = Directory.GetFiles("c:");

    foreach (string fNames in yourFiles)

      Console.WriteLine(fNames);
  }

}

This code will get you files from the root directory.

:)

C#/C Sharp – Delete file in a folder

Hi,

Let’s see a simple example of deleting a file in a folder using c#.

using System;
using System.IO;

public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo sampleFile= new FileInfo(@"c:SamplestestFile.txt");

    sampleFile.Create();

    sampleFile.Delete();

  }
}

sampleFile.Create() will create the file in the specified folder.
sampleFile.Delete() will delete the file in the specified folder.

:)

ANDROID – Upload an image to a server

Hi ANDROIDians in today’s tutorial I will show you how to send an image to server using POST method in ANDROID.
Uploading an image to server is a basic requirement in many of our application.
Sending data to server which is using a PHP Script is already explained in this example .
Now in this example I will show you how to send an image file.
For that first we have to read the file, put it in nameValuePairs and then send using HttpPost.

I have already shown you three other methods on uploading a file to server. If you want you can check these posts.
1. How to Upload Multiple files in one request along with other string parameters in android?
2. Uploading audio, video or image files from Android to server.
3. How to upload an image from Android device to server? – Method 4

These are for downloading files from the server.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

Now can we quickly go to the code.

This is the main java file source code UploadImage.java

package pack.coderzheaven;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;

public class UploadImage extends Activity {
	InputStream inputStream;
	    @Override
	public void onCreate(Bundle icicle) {
	        super.onCreate(icicle);
	        setContentView(R.layout.main);

	        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);	        ByteArrayOutputStream stream = new ByteArrayOutputStream();
	        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
	        byte [] byte_arr = stream.toByteArray();
	        String image_str = Base64.encodeBytes(byte_arr);
	        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

	        nameValuePairs.add(new BasicNameValuePair("image",image_str));

	         Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				  try{
			             HttpClient httpclient = new DefaultHttpClient();
			             HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
			             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			             HttpResponse response = httpclient.execute(httppost);
			             String the_string_response = convertResponseToString(response);
			             runOnUiThread(new Runnable() {
				      			
				      			@Override
				      			public void run() {
				      				Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();		      				
				      			}
				      		});
			             
			         }catch(Exception e){
			        	  runOnUiThread(new Runnable() {
			      			
			      			@Override
			      			public void run() {
			      				Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();			      				
			      			}
			      		});
			               System.out.println("Error in http connection "+e.toString());
			         }	
			}
		});
         t.start();
	    }

	    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

	    	 String res = "";
	    	 StringBuffer buffer = new StringBuffer();
	    	 inputStream = response.getEntity().getContent();
             int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
              runOnUiThread(new Runnable() {
   			
   			@Override
   			public void run() {
   				Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();	      				
   			}
   		});
         
             if (contentLength < 0){
             }
             else{
	                byte[] data = new byte[512];
	                int len = 0;
	                try
	                {
		                while (-1 != (len = inputStream.read(data)) )
		                {
		                	buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
		                }
	                }
	                catch (IOException e)
	                {
	                	e.printStackTrace();
	                }
	                try
	                {
	                	inputStream.close(); // closing the stream…..
	                }
	                catch (IOException e)
	                {
	                	e.printStackTrace();
	                }
	                res = buffer.toString();	 // converting stringbuffer to string…..

	                runOnUiThread(new Runnable() {
           			
           			@Override
           			public void run() {
           			   Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
           			}
           		});
	                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
             }
	         return res;
	    }
}

Note : You should do networks operations inside a thread only.
AND you cannot modify UI elements inside a thread, but you have to do inside a UIThread only.

Now download a file from here which encodeBytes in Base64 Format. Put this file in the same package of UploadImage.java. See the screenshot.

Upload Image

Upload Image

However you can put in your own package but don’t forget to change the package name otherwise you will get error.

Now the server part.

Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.

I am saying the htdocs folder because I am using XAMPP. You change this according to your use.

<?php
	$base=$_REQUEST['image'];
	 $binary=base64_decode($base);
	header('Content-Type: bitmap; charset=utf-8');
	$file = fopen('uploaded_image.jpg', 'wb');
	fwrite($file, $binary);
	fclose($file);
	echo 'Image upload complete!!, Please check your php file directory……';
?>

Now run your program and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.

If you want to upload another file in your SDCARD you have to change this line to give the exact path

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);

For example if I have to upload a file residing in my SDCARD I would change the path like this.

Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/android.jpg”);

This tutorial explains how to create an SDCARD and start the emulator with the SDCARD
and this tutorial explains how to put file inside your emulator SDCARD

if you want to use the android using php and mysql
please check these posts.

1. Android phpMysql connection
2. Android phpmySQL connection redone.

Please comment if you didn’t get it right or you like this post.

Showing Twitter updates on Blogger/Blogspot

Hi,

If you want to show the latest twitter update of yours in your blogger/blogspot, then use the following steps.
1. Go to your blogger ‘Design’
2. Click ‘Add A Gadget’
3. Add ‘HTML/JavaScript’
4. Paste the following JavaScript code into it and save

<div class="twitter-desc">
<ul id="twitter_update_list"><li></li></ul>
<script src="http://twitter.com/javascripts/blogger.js" type="text/javascript"></script>
<script src="http://twitter.com/statuses/user_timeline/SampleURL.json?callback=twitterCallback2&amp;count=1" type="text/javascript"></script>
</div>

5. Done!

Note : Replace ‘SampleURL’ with your twitter id & you can set the number of twitter updates to be shown using the ‘count’, here count is set to 1.

:)

How to get notified during an incoming call and get that number inside your program in ANDROID?

Hi all…….

In today’s tutorial I will show you how to get the incoming phone number inside your application. In many situation we may need this.
For this we need to have BoradCastReceivers. Inside this class we create an object of the TelephonyManager class ang register with the sytem service.Now we have to make another class which extends PhoneStateListener class which implements the onCallStateChange class which listens to incoming calls.The onReceive method inside the BroadcastReceiver class gets the incoming number from the intent using this line

Bundle bundle = intent.getExtras();
String phone_number = bundle.getString(“incoming_number”);

Note that this program doesnot have an UI ,since it is a service.

Now we go to the code part.
Create a new project and copy this code to it.

package pack.coderzheaven;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class MyBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

	    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
	    MyPhoneStateListener customPhoneListener = new MyPhoneStateListener();

	    telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

	    Bundle bundle = intent.getExtras();
	    String phone_number = bundle.getString("incoming_number");
	    System.out.println("Phone Number : " + phone_number);
	}

}

Now create another class and name it MyPhoneStateListener.java and copy following code to it.

package pack.coderzheaven;

import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class MyPhoneStateListener extends PhoneStateListener {

	public void onCallStateChange(int state, String incomingNumber){

	       System.out.println("Icoming Number inside onCallStateChange : "  + incomingNumber);
	        switch(state){
	                case TelephonyManager.CALL_STATE_RINGING:
	                		System.out.println("PHONE RINGING.........TAKE IT.........");
	                        break;
	                case TelephonyManager.CALL_STATE_OFFHOOK:
		                	System.out.println("CALL_STATE_OFFHOOK...........");
		                    break;
	        }
	}
}

Done.
Note that all receivers have to be declared in the androidmanifest file inorder to get events.
So the androidmanifest.xml is given below.

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

      <uses-permission android:name="android.permission.RECEIVE_SMS" />
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.WRITE_CONTACTS" />
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />

      <application android:icon="@drawable/icon" android:label="@string/app_name">
    	        <receiver android:name=".MyBroadcastReceiver">
		        <intent-filter>
		                <action android:name="android.intent.action.PHONE_STATE" />
		        </intent-filter>
		</receiver>
      </application>

</manifest>

Now what you have to do is to simulate a call to your emulator. Check these links for this

1. Simulating a call or SMS in your ANDROID Emulator

2. How to simulate an incoming call to an emulator OR Send an SMS to an emulator in ANDROID ?

Check your console for the output.

Please leave your comments if this post was useful.

How to create a text file in C# ?

Hi,

How can you create a text file in C# and write to it? Sometimes you may need to create a text file using C sharp program. Here is how you can do that.

using System;
using System.IO;

class MainClass
{
  static void Main(string[] args)
  {
    StreamWriter yourStream= null;
    string yourString= "I Love Coderz Heaven!";

    try
    {
      yourStream = File.CreateText("testFile.txt");
      yourStream.Write(yourString);
    }
    catch (IOException e)
    {
      Console.WriteLine(e);
    }
    catch (Exception e)
    {
      Console.WriteLine(e);
    }
    finally
    {
      if (yourStream!= null)
      {
          yourStream.Close();
      }
    }
  }
}

:)

Identifying sprite associated with a particular body in Box2D

Hi,

How can you identify the sprite associated with a particular body while using box2D ? Sometimes you may need to identify the sprite associated with the body you are using. For that use the following line of code.

CCSprite *yourSprite= (CCSprite*)yourBody->GetUserData();

Now you got the corresponding sprite in your ‘yourSprite’

:)

Android frame Animation

A series of frames is drawn one after the other at regular intervals.
For this create a xml which contains ImageView for showing the animation

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
	"http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:background="#FFFFFF"
   android:gravity="center_vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">


   <ImageView
      android:id="@+id/Image"
       android:layout_gravity="center_horizontal"
      android:layout_width="wrap_content"
      android:background="@drawable/d1"
      android:layout_height="wrap_content"/>

      <Button
      android:id="@+id/startFAButtonId"
      android:layout_width="wrap_content"
      android:layout_gravity="center_horizontal"
      android:layout_height="wrap_content"
      android:text="Start Animation"
      />
</LinearLayout>

The main java file is

package com.coderzheaven.animation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

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

        Button b = (Button)this.findViewById(R.id.startFAButtonId);
        b.setOnClickListener(new View.OnClickListener()
        {
			public void onClick(View v)
			{
				animate();
			}
		});

    }
 	   private void animate() {
 	      ImageView imgView = (ImageView)findViewById(R.id.Image);
 	      imgView.setVisibility(ImageView.VISIBLE);
 	      imgView.setBackgroundResource(R.drawable.animation_frame);

 	      AnimationDrawable frameAnimation =  (AnimationDrawable) imgView.getBackground();

 	      if (frameAnimation.isRunning()) {
 	         frameAnimation.stop();
 	      }
 	      else {
 	         frameAnimation.stop();
 	         frameAnimation.start();
 	      }
 	   }
 }

Next the main part, an xml which holds each image and duration in which each image shows.
The xml should be placed inside drawable folder

<?xml version="1.0" encoding="utf-8"?>
<animation-list
	 xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
   <item android:drawable="@drawable/d1" android:duration="50" />
   <item android:drawable="@drawable/d2" android:duration="50" />
   <item android:drawable="@drawable/d3" android:duration="50" />
   <item android:drawable="@drawable/d4" android:duration="50" />
   <item android:drawable="@drawable/d5" android:duration="50" />
</animation-list>

When i click the button the animation will start

A simple exception handling using C#

Hi,

See how a very simple exception handling works with try-catch methods using C#.

using System;

class MainClass{

    public static void Main(){

        int divOne = 0;

        try {
            int ans = 79 / divOne ;
        }

        catch (Exception e) {
            Console.WriteLine("You got the exception-> " + e.Message);
        }

    }
}

Output- “You got the exception-> Attempted to divide by zero.”

:)

Android dialog with ListView

For implementing a ListView, we first create a xml which contains a ListView named list.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">

  <ListView
    android:id="@+id/listview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>

Next we create a Dialog Object and inflate the above xml and when the listItem is clicked then a Alert Dialog windows comes
The java file is listed below


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class DialoglistView extends Activity implements OnItemClickListener{
    /** Called when the activity is first created. */
	String[] val = {"sunday","monday","tuesday","thrusday","friday","wednesday","march"};
	ListView list;
	Dialog listDialog;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         showdialog();
    }

    private void showdialog()
    {
    	listDialog = new Dialog(this);
    	listDialog.setTitle("Select Item");
    	 LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	 View v = li.inflate(R.layout.list, null, false);
    	 listDialog.setContentView(v);
    	 listDialog.setCancelable(true);
         //there are a lot of settings, for dialog, check them all out!

         ListView list1 = (ListView) listDialog.findViewById(R.id.listview);
         list1.setOnItemClickListener(this);
         list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, val));
         //now that the dialog is set up, it's time to show it
         listDialog.show();
    }

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Delete item "+arg2)
		           .setPositiveButton("OK ", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   System.out.println("OK CLICKED");

		           }
		       });
		builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	        	 dialog.dismiss();
	        	 listDialog.cancel();

	           }
	       });

		AlertDialog alert = builder.create();
		alert.setTitle("Information");
		alert.show();
	}
}

The alert window look like this

When the Item is selected then

How to get the SMS sent to your emulator within your application? OR Get notified when an SMS arrives to your phone.

Actually these are done using services in ANDROID. These are called BroadcastReceivers.Your class has to extend the BroadcastReceiver class to get these broadcast events. But note that these services need to have an interface. So you will not see any UI on the device. But don’t think your application is not running or not installed. Look at the console for results. You will probably see this type of console on running this application.

SMS receiver in android

SMS Receiver in android

This means that your service has been installed in the emulator. Check the apps installed. You will probably see your application.

Now we are going to create this SMS receiver application.
Create a new project and copy this code to the java file created.

package pack.coderzheaven;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class SMS_Receiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();

		Object messages[] = (Object[]) bundle.get("pdus");
		SmsMessage SMS[] = new SmsMessage[messages.length];
		for (int n = 0; n < messages.length; n++) {
			SMS[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
		}
		/* GETTING THE LAST JUST ARRIVED MESSAGE FROM INBOX */
		Toast toast = Toast.makeText(context,"Received SMS inside SMS_Receiver : " + SMS[0].getMessageBody(), Toast.LENGTH_LONG);
		toast.show();
	}
}

In the above class you can see that “SMS_Receiver” extends the BroadcastReceiver class.So this class has to implement the onReceive method inorder to receive broadcast events. The intent is get using

Bundle bundle = intent.getExtras();

After that an array is created for all the SMS and here I am showing only the last SMS received by the intent using a toast. How to simulate an SMS to your emulator is explained in here and another method here
No XML file for layout is used here.

AndroidManifest.xml file.

Note that every receiver should be registered in the manifest file in order to receive intents using the receiver tag. Take a look at this code.

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

      <uses-permission android:name="android.permission.RECEIVE_SMS" />
      <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
	<uses-permission android:name="android.permission.READ_PHONE_STATE" />

 <application android:icon="@drawable/icon" android:label="@string/app_name">
       <receiver android:name=".SMS_Receiver" android:enabled="true">
<intent-filter>
	<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
	</receiver>
</application>
</manifest>

After sending the SMS mentioned in one of the methods after running this application, quickly switch to the emulator to see the output, because I am using a toast to display the message, So it will come and go and you may not see.
Sending SMS using emulator control.

SMS receiver example

SMS Receiver example

SMS Receiver service example

SMS Receiver service example

Please leave your comments if you found this post useful.

How to check SDCard free space in ANDROID?

This is a simple example that shows how many bytes are free in your SDCard.
Inorder to run this example, you have to create an SDCard and start the emulator with the SDCard.

Now create a fresh project and name it “FreeSpaceActivity.java” and copy the following code to it.

package pack.coderzheaven.check_space;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.widget.TextView;

public class FreeSpaceActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        double avail_sd_space = (double)stat_fs.getAvailableBlocks() *(double)stat_fs.getBlockSize();
        double GB_Available = (avail_sd_space / 1073741824);
        System.out.println("Available GB : " + GB_Available);

        TextView tv = (TextView)findViewById(R.id.tv);
        tv.setText("Your SD Card is " + GB_Available + " bytes free." );
        tv.setTextColor(Color.GREEN);
        tv.setTextSize(20);
    }
}

The main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/tv"
    />
</LinearLayout>

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven.check_space"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FreeSpaceActivity"
                  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>

Please leave your comments if the post was useful.

Free space in SD Card

Free Space in SD Card