Using Arrays in JavaScript – Basics

Hi…

We all know, Arrays are nothing but variables which can hold all your variable values with a single name.

Let’s see some basic operations of Arrays in JavaScript.

To Create a New Array. Use the following code.

 var myArray = new Array();

This code of line created a new Array object called myArray.

Adding Elements to myArray

myArray[0]= "you";
myArray[1] = "me";
myArray[2] = "we";

or

var myArray=new Array("you","me","we"); 

or

var myArray=["you","me","we"];

Accessing Array Elements

document.write(myArray[0]);

It will print ‘you’!
:)

How to get a selected Item from a spinner in ANDROID?

We have come across this issue many times during programming to get a selected item in your combobox.
ANDROID has built in functions to get the selected item from a spinner.
Take a look at the snippet.
Here my_spinner id the spinner variable and using getSelectedItem() which will return an object and by using toString() I am converting it to human readable string…

my_spinner.getSelectedItem().toString();

Please leave your valuable comments…..

How to add more than One HTML Document in a single Browser ?

Hi…

There may arise certain situations where you need to include more than one HTML document in the same browser.

But how?

It’s simple. It’s by using FRAMES of HTML.
FRAMES can be included inside FRAMESET.

Let’s see an example.

<frameset cols="200,400">
   <frame src="http://www.coderzheaven.com" />
   <frame src="http://www.google.com" />
</frameset>

This will create two column frames in the browser with www.coderzheaven in one frame with 200 pixels, and www.google.com in another frame with 400 pixel.

You can also give cols percentage as well. Like cols=”25%,75%”.
:)

ProgressBar in ANDROID…..

Progress bars are our basic needs when we want to show something for a long time or some progress takes a long time and we want to show it’s progress.
Keeping that in mind ANDROID also has built in progress views.
There are basically two types of progress views in ANDROID.

ProgressDialog.STYLE_SPINNER and ProgressDialog.STYLE_HORIZONTAL

Take a look at this simple example that loads a progressBar on “onCreate”….

public class Example extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main);
    	ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);
    }
}

Toggle between Full Screen and normal Screen in Adobe AIR or FLEX.

Hi all………

We often need to toggle between fullscreen and normal screen in our application.
The following code snippet helps you to toggle between these two screens in Adobe AIR or Flex.
Here I am using StageDisplayState class to do both which has “stage.displayState = StageDisplayState.FULL_SCREEN” and ” stage.displayState = StageDisplayState.NORMAL” constants to do this.

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"  applicationComplete="toggleScreen()">
       <mx:Script>
               <![CDATA[
                       import flash.display.StageDisplayState;
                       private function toggleScreen():void{
                               if(fullScreen.selected == true){
                                       this.goFullScreen();
                               } else {
                                       this.exitFullScreen();
                               }
                       }
                       private function goFullScreen():void {
                               stage.displayState = StageDisplayState.FULL_SCREEN;
                       }
                       private function exitFullScreen():void {
                               stage.displayState = StageDisplayState.NORMAL;
                       }
               ]]>
       </mx:Script>
       <mx:CheckBox label="Full Screen" id="fullScreen" click="this.toggleScreen()"
               	               selected="true"  horizontalCenter="0" verticalCenter="0"/>
</mx:WindowedApplication>
 

How to detect shake Gesture in your iPhone Cocos2D?

For detecting shake in a cocos2D program copy these lines to your layer class

bool shaked_once; //default false

self.isAccelerometerEnabled = YES;
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:1/60];
shaked_once = false;

Then copy this function to the same file…. and you are done……..

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

            float THRESHOLD = 2;

        if (acceleration.x > THRESHOLD || acceleration.x < -THRESHOLD ||
                          acceleration.y > THRESHOLD || acceleration.y < -THRESHOLD ||
                                      acceleration.z > THRESHOLD || acceleration.z < -THRESHOLD) {
                    if (!shaked_once) {
                           shaked_once = true;
                   }
         }
         else {
                          shaked_once = false;
         }
}

Hide and Show a Text Using jQuery – Example

With jQuery manipulation of HTML & CSS can be done very easily.
Here we are going to show how to Hide a line of text using jQuery & Show it back also.
Let’s code speak first….


<html>
<head>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#hideButton").click(function(){
$("p").hide();
});

$("#showButton").click(function(){
$("p").show();
});
});
</script>

</head>
<body>

<p>Hey! Click 'Left', I will vanish! Click 'Right', I will be back!</p>

<button id="hideButton">Left</button>
<button id="showButton">Right</button>
</body>
</html>

Note : Download and put ‘jquery.js’ on your working folder before trying out!

What these code did?

Here we have one line text, html paragraph. Two buttons ‘Left’ & ‘RIght’ and whose id’s

are ‘hideButton’ & ‘showButton’ respectively.

jQuery code identifies which button we clicked using the button id’s mentioned above and

apply the hide() or show() function to the html paragraph p.
:) 

Check whether a file exists in Objective C

“fileExistsAtPath” is used to check whether a file exists or not at a specified path.

           if ( [theManager fileExistsAtPath:theFilePath ] ) {
                // File exists......
            }
            else {
                 // No file in this path.....
            }

Preventing Overriding in Java

Methods and variables can be ‘override’ in subclasses. (Yes, it’s a good

feature too!). But what if we don’t want to ‘override’ our Methods and Variables in Java?

It’s simple…

Declare them using the keyword ‘final’ as modifier. That’s it.

eg:

final int myVariable = 79;

So the value of myVariable can never be changed any way.

Also for Classes/Methods.

eg:

final class myClass{ whatever your code;} 

It will prevent our myClass being extended.

Creating Exceptions in JAVA

This is a simple custom exception in java. That is, we can create an exception by extending the exception class.

The “throw new MyExcep” will throw an exception and the error message we specified will be displayed

import java.lang.Exception;
@SuppressWarnings("serial")
class MyExcep extends Exception
{
	MyExcep(String Errormsg)
	{
		super(Errormsg);	// call Exception class error message
	}
}
public class Example
{
	public static void main(String[] args)
	{
		int x = 5 , y = 1000;
		try
		{
			float z = (float) x / (float) y;
			if(z < .01)
			{
				throw new MyExcep("Number is too small");
			}
		}
		catch(MyExcep e)
		{
			System.out.println("Caught My Exception");
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("I am Always Here");
		}
	}
}

The output will be like this

Caught My Exception
Number is too small
I am Always Here

How to use MediaPlayer in ANDROID? A simple example.

MediaPlayer class can be used to play Audio in ANDROID.
See how to do this.

MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(MyClassName.this,songId);
		try {
			mp.prepare();

		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (Exception e) {
			Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();			}
		mp.start();

        //Called when the song completes.....
            mp.setOnCompletionListener(new OnCompletionListener() {
  			public void onCompletion(MediaPlayer mp) {
  			}
  		});

PHP- Warning: session_start(): Cannot sent session cache limiter-headers already sent, ERROR

Most of the beginners in PHP while using sessions at the first time might have encountered a long error, starting with something like,

Warning:session_start(): Cannot sent session cache limiter- headers already sent

Fix : It’s too simple!
Don’t ever leave atleast a single space before the PHP code (starting with That’s it! Don’t try to make the PHP code even a single line or space after! Let PHP begin with < itself. NOT EVEN A SINGLE SPACE before it. Also don’t print (echo) anything before the call using header function.

Difference between & and * operator in C

A beginner to Pointers in C often perplexed by different operators & and *
Let’s see what it really is and how simple it is.

& – This operator gives ‘the address of’ a variable
* – This operator gives ‘the value at address’ of a variable

(Note! Note! Note! Not the other way round! By heart it any way!)

Let’s codes speak…

#include
main()
{

	int myVariable = 25;

	printf("n Address of myVariable = %u", &myVariable);
	printf("n Value of myVariable = %u", myVariable);
	printf("n Value of myVariable = %u", *(&myVariable));
}

 

So… the output…

Guess?

Address of myVariable = 7589
//7589 is the address in memory of the variable myVariable

Value of myVariable = 25
//It simply printed the ‘myVariable’ which contains 25

Value of myVariable = 25
// Please do note that it printed ‘the value at address’ of ‘myVariable’
// Address is passed via &myVariable

:)

How to check whether GPS is available in ANDROID or Not?

This code helps you to check whether the location service is available on your ANDROID Phone or not.
Copy this code and paste to your file.
Happy coding…..

 public boolean GPSAvailable() {
     LocationManager loc_manager = (LocationManager)
     getSystemService(Context.LOCATION_SERVICE);
     List<string> str = loc_manager.getProviders(true);

     if(str.size()>0)
         return true;
     else
         return false;
}

String Functions in C

Let’s now briefly discuss about four essential String function used in C.

We are going to discuss about
a) strlen()
b) strcpy()
c) strcat()
d) strcmp()

Codes speak louder than words! Let’s see what these functions do in a simple C Program.


#include
main()
{

	char stringOne[15] = "CoderzHeaven";
	char stringTwo[] ="Codes";
	char stringThree[15];

	int varOne, varTwo;

	//Counting the string length
	varOne = strlen(stringOne);
	printf("n Length of stringOne = %d", varOne);

	//Copying stringOne to stringThree
	strcpy(stringThree, stringOne);
	printf("n After Copying process, stringThree=%s", stringThree);

	//Comparing two strings
	varTwo=strcmp(stringThree, stringOne);
	printf("n On Comparing stringThree & stringOne, varTwo=%d", varTwo);

	//Comparing two strings
	varTwo = strcmp (stringOne, stringTwo);
	printf("n On Comparing stringOne & stringTwo, varTwo=%d", varTwo);

	//Concatenating two strings
	strcat(stringOne, stringTwo);
	printf("n After Concatenation, stringOne = %s", stringOne);

}

Output???
Here y
Length of stringOne = 12
After Copying process, stringThree = CoderzHeaven;
On Comparing stringThree & stringOne, varTwo = 0
On Comparing stringOne & stringTwo, varTwo= -1
After Concatenation, stringOne = CoderzHeavenCodes

Programmatically change background in Adobe AIR/FLEX.

  private function change():void
   {
	this.setStyle("backgroundColor","#00FF00");
	this.setStyle("color","green");
   }
 

Create PopUp Window in Adobe AIR / FLEX, A simple Example.

Below code shows how to create a new popUp window in Adobe AIR or FLEX.
To create a new window “right click on the src folder and create a new MXML Component named Here “MyLoginForm” It should be aTitleWindow for the example below.
How ever You can create other components, but the code accordingly must change.

          import mx.managers.PopUpManager;
          import mx.core.IFlexDisplayObject;
          import myComponents.MyLoginForm;


          // Additional import statement to use the TitleWindow container.
          import mx.containers.TitleWindow;


          private function showLogin():void {
            // Create the TitleWindow container.
            var helpWindow:TitleWindow =
          TitleWindow(PopUpManager.createPopUp(this, MyLoginForm, false));


            // Add title to the title bar.
            helpWindow.title="Enter Login Information";


            // Make title bar slightly transparent.
            helpWindow.setStyle("borderAlpha", 0.9);


            // Add a close button.
            // To close the container, your must also handle the close event.
            helpWindow.showCloseButton=true;
          }
        ]]>
    

FullScreen Event in Adobe AIR or FLEX

 

The following simple code snippet explains how to get an eventListener for FullScreen Event in Adobe AIR or FLEX. The function “onScreenModeChange ” gets called when you maximizes your window.
private function init():void {
stage.addEventListener( FullScreenEvent.FULL_SCREEN, onEnteringFullScreenMode);
}
private function onEnteringFullScreenMode( e:FullScreenEvent ):void {
if( e.fullScreen ) {
// Do something on fullscreen……………
} else {
// Do something else………..
}
}

Please leave your valuable comments if this post was useful…..

Abstract Class in java

This example shows how a simple java abstract class works
Here “Shape” is the abstract class
abstract class Shape
{
abstract void initial(); // methods only defined…..
abstract void display();
}
class cube extends Shape
{
void initial() // Abstract Methods defined….
{
System.out.println(“Hello !! “);
}
void display()
{
System.out.println(“How are you?”);
}
}
public class Abstract
{
public static void main(String[] args)
{
// Shape S = new Shape(); // error cannot create objects for abstrac classes…..
cube C = new cube();
C.initial();
C.display();
}
}
Here we cannot create “Shape” class object because it is abstract
The output is
Hello !!
How are you?

How to create custom layout for your spinner in ANDROID? or Customizable spinner

This code helps you to customize the spinner in ANDROID.

For that you have to create an XML file inside your layout folder as shown below and name it spinner.xml.
You can give all properties that are available for TextView inside this which is going to be then applied for your spinner.

<xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="14sp"
android:typeface="serif"
android:textStyle="bold|italic"
android:textColor="@drawable/yellow"
>
TextView>

Now I will show you how to add it to a spinner.

ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner,my_array);
My_spinner.setAdapter(my_Adapter);

“my_array” is an array that populates the spinner and “My_spinner” is the spinner.

Please leave your valuable comments if this post was useful…..

How to set an item selected in Spinner in ANDROID?

This code helps yoy to set an item in your combobox(spinner) in ANDROID.
Here my_spinner is the combobox which we call as spinner in ANDROID.
Declare it in your XML file and link to it by using the following code….
my_spinner= (Spinner)findViewById(R.id.my_spinner);
After that in your code set an item Listener for the spinner using the code below.

my_spinner.setOnItemSelectedListener(spinnerListener);

Now you have registered the listener with the selection event.

Next are the functions that is actually triggered when we select an item in the spinner
“onNothingSelected” function is triggered when nothing is selected.

private Spinner.OnItemSelectedListener spinnerListener
= new Spinner.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
/* This function is called when you select something from the spinner */
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
/**This line sets the index of the spinner.
Here I have given it as position which
can be  any number with in the index range  ***/
my_spinner.setSelection(position);
}};

Please leave your valuable comments.

How to add categories / labels in your blogger?

Unlike wordpress blogger, blogspot don’t have direct method (I said direct not ‘NO’!) to add categories to your posts.

Just adding ‘Labels’ while you post your posts won’t work always.

But it’s simple to categorize posts in your blogspot.

Follow the simple steps below. (Google is always simple & will be!)

1. From your ‘Dashboard’ , Go to ‘Design’

2. Click ‘Add a Gadget’

3. Add ‘Labels’ from ‘Basics’ gadgets by clicking ‘+’ sign.

(Just scroll down to 17th or 18th item, you won’t find it by search sometime!)

4. Now you can add any number of Labels with commas while you post in Label Box

5. Done! Now Labels or Categories of your posts will be in your blog.

Very simple, right?
:)

Why don't my player showing subtitles?

You may be perplexed at a common situation where your movie player don’t showing up the subtitles even after you have the subtitle file!

But the fix to this problem is too simple.

How to fix subtitles not showing up problem?

Ans : Just Rename the subtitle file with the same name as that of the movie file. DONE! (Or both files need to be in the same name!)

Eg : If your movie file name is ‘myMovie.avi’ , your subtitle file should be like ‘myMovie.srt’ (srt or anyother subtitle format)
:)

Java Exception

Simple java program to show how exception works

public class exception
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 10/0;
}
catch(ArithmeticException e)
{
System.out.println(“Exception Caught ” + e);
}
}
}
The output will be like you expect
Exception Caught java.lang.ArithmeticException: / by zero

How to remove an item in a row in Datagrid in Adobe AIR or FLEX?

Most often you may need to delete data from a datagrid in your application.
The code below shows one of the ways in which you can delete the corresponding row in your application.
Here I am placing a button in the datagrid for deleting and on its click I am getting the index of the datagrid, thus identifying the row.
Then by using

DataProvider.removeItemAt(DataGrid.selectedIndex);

I removed the row from it.
After that I am just refreshing the data in the Datagrid.
See the example below.

<?xml version=”1.0″ ?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Script>
<![CDATA[
import mx.controls.DataGrid;
import mx.collections.XMLListCollection;
private var my_xml:XML =   <data>
<item1>data1</item1>
<item2>data2</item2>
<item3>data3</item3>
</data>;
[Bindable] private var DataProvider:XMLListCollection = new XMLListCollection(my_xm..item1);
public function deleteItem(event:MouseEvent):void{
DataProvider.removeItemAt(DataGrid.selectedIndex);
DataProvider.refresh();
}
]]>
</mx:Script>
<mx:DataGrid id=”DataGrid” dataProvider=”{DataProvider}”>
<mx:columns>
<mx:DataGridColumn headerText=”  Text “
dataField=”item”>
<mx:itemRenderer>
<mx:Component>
<mx:Text text=”{data}”/>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
<mx:DataGridColumn headerText=”Delete this Row”>
<mx:itemRenderer>
<mx:Component>
<mx:LinkButton label=”Delete”
click=”outerDocument.deleteItem(event)”/>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>
</mx:columns>
</mx:DataGrid>
</mx:Application>

Please post your comments on this post.