Monthly Archives: February 2012

Custom GridView in android. A simple example.

Hello all………..

Android has been absoultely wonderful for customizing widgets. I have shown a lot of example to customize ListViews, spinners etc.
Today I will show you how to customize gridviews.
Using this method you can actually place anything inside a gridview even a webview also.

So here we start.
We customize a gridview by creating an adapter that extends “BaseAdapter”.
This is the class that extends “BaseAdapter” and create a customAdapter.

 public class MyAdapter extends BaseAdapter {

    	private Context mContext;

		public MyAdapter(Context c) {
			mContext = c;
		}

		@Override
		public int getCount() {
			return mThumbIds.length;
		}

		@Override
		public Object getItem(int arg0) {
			return mThumbIds[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View grid;

			if(convertView==null){
				grid = new View(mContext);
				LayoutInflater inflater=getLayoutInflater();
				grid=inflater.inflate(R.layout.mygrid_layout, parent, false);
			}else{
				grid = (View)convertView;
			}

			ImageView imageView = (ImageView)grid.findViewById(R.id.image);
			imageView.setImageResource(mThumbIds[position]);

			return grid;
		}

	}

Acually we can provide any custom layout for the view inside the gridview that is for each cell.

The xml I am using here is “mygrid_layout.xml” which looks like this.

<?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="wrap_content"
	android:background="@drawable/customshape_header"
	android:orientation="vertical">
	<ImageView
		android:id="@+id/image"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"/>
</LinearLayout>

This is the custom shape header class which is used for styling which is saved in res/drawable folder.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp" />
    <solid android:color="#660033"/>
    <stroke
        android:width="1dip"
        android:color="#C0C0C0" />
</shape>

Now the full source code for implementing this class.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class CustomGridViewExample extends Activity {

	private Integer[] mThumbIds = {
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			R.drawable.android_2,
			};


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

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new MyAdapter(this));
        gridview.setNumColumns(4);
    }

  public class MyAdapter extends BaseAdapter {

    	private Context mContext;

		public MyAdapter(Context c) {
			mContext = c;
		}

		@Override
		public int getCount() {
			return mThumbIds.length;
		}

		@Override
		public Object getItem(int arg0) {
			return mThumbIds[arg0];
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View grid;

			if(convertView==null){
				grid = new View(mContext);
				LayoutInflater inflater=getLayoutInflater();
				grid=inflater.inflate(R.layout.mygrid_layout, parent, false);
			}else{
				grid = (View)convertView;
			}

			ImageView imageView = (ImageView)grid.findViewById(R.id.image);
			imageView.setImageResource(mThumbIds[position]);

			return grid;
		}
	}
}

Here is 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="@string/hello"
    android:padding="10dp"
    android:gravity="center"
    android:textStyle="bold"
    />

<GridView
	android:id="@+id/gridview"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:numColumns="auto_fit"
	android:verticalSpacing="10dp"
	android:horizontalSpacing="10dp"
	android:stretchMode="columnWidth"
	android:gravity="center"
	android:scrollbars="none" />
</LinearLayout>
Custom GridView in Android

Custom GridView in Android

You can download the complete source code from here.

How to Sort a String array in Android.

Hello all….
This is a simple example showing how to sort a string array which is a arraylist in android.

we sort the array using the “Collections” class in android.

Here is a simple example

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import android.app.Activity;
import android.os.Bundle;

public class SortingStringsDemo extends Activity {

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

        ArrayList<String> my_array = new ArrayList<String>();

	      //Add elements to Arraylist
          my_array.add("CoderzHeaven");
          my_array.add("Google");
          my_array.add("Android");
          my_array.add("apple");
          my_array.add("android");
          my_array.add("Microsoft");
          my_array.add("Samsung");

          //sorting function
	      Collections.sort(my_array);

	      //display elements of ArrayList
	      System.out.println("ArrayList elements after sorting in ascending order : ");
	      System.out.println(Arrays.toString(my_array.toArray()));

	      System.out.println("ArrayList elements Comparing - ignorecase");
	      IgnoreCaseComparator icc = new IgnoreCaseComparator();
	      java.util.Collections.sort(my_array,icc);
	      Collections.sort(my_array);
	      System.out.println(Arrays.toString(my_array.toArray()));

	      System.out.println("Reversing the ArrayList");
	      Collections.sort(my_array, Collections.reverseOrder());
	      System.out.println(Arrays.toString(my_array.toArray()));
    }

    class IgnoreCaseComparator implements Comparator<String> {
	  public int compare(String strA, String strB) {
	    return strA.compareToIgnoreCase(strB);
	  }
	}
}

Take a look at the LogCat for the output.

ListView with Sections in android.

Hello all……….

We have seen many posts about ListViews like creating a listview, adding data to it, customizing a listview etc.

Take a look at some of these examples

1. Single Selection ListView in android
2. Flitering a ListView using an input from an EditText in Android.
3. How to create a custom ListView in android?
4. Android dialog with ListView.
5. Expandable ListView in ANDROID using SimpleExpandableListAdapter, a simple example.
6. Android listView with icons.
7. Creating scrolling ListView in android.

ListView with sections in android

ListView with sections in android

Today also we will see another customization of listviews.
Today I will show you how to create listviews with sections.

This is the main.xml layout file which contains the ListView.

<?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"
    android:background="@drawable/orange"
    >
    <ListView
		 	android:id="@+id/list1"
			android:cacheColorHint="#00000000"
			android:scrollbars="none"
			android:background="@drawable/bg_transparent"
			android:fadingEdge="vertical"
			android:soundEffectsEnabled="true"
			android:divider="@drawable/green"
			android:dividerHeight="1px"
			android:padding="0dip"
			android:smoothScrollbar="true"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:drawSelectorOnTop="false"
		    android:layout_marginTop="5dip"
		    android:layout_marginLeft="5dip"
		    android:layout_marginRight="5dip"
		    android:layout_marginBottom="5dip"
		    android:layout_weight="1"/>

</LinearLayout>

I am using some resources in this, one of which is the “customshape_header.xml” file which is saved in res/drawable directory.
This will ptovide the background for the section header.
customshape_header.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="3dp" />
    <solid android:color="#FFFFFF"/>
    <stroke
        android:width="1dip"
        android:color="#C0C0FF" />
</shape>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ListView with Sections</string>
    <drawable name="white">#ffffff</drawable>
	<drawable name="black">#000000</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="grey">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
	<drawable name="yellow">#FFFF8C</drawable>
	<drawable name="PowderBlue">#b0e0e6</drawable>
	<drawable name="brown">#2F1700</drawable>
	<drawable name="Hotpink">#7D2252</drawable>
	<drawable name="orange">#FFA500</drawable>
	<drawable name="darkgrey">#606060</drawable>
</resources>

This is the “lv_layout.xml” file which I am using for each row in the listview.

<?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"
    android:id="@+id/l1"
    >
</LinearLayout>

Now the main java file which implements the logic for creating the listview with sections.

package com.coderzheaven.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SectionListViewDemo extends Activity {

	ListView L1;
	myAdapter myadp;
	String last_item = "B";
	static final String[] labels_array = new String[] {
		  "Afghanistan", "Albania",
		  "Bahrain", "Bangladesh",
		  "Cote d'Ivoire", "Cambodia",
		  "Estonia", "Ethiopia", "Faeroe Islands",
		  "Former Yugoslav Republic of Macedonia"
		};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        L1 = (ListView)findViewById(R.id.list1);
        myadp = new myAdapter(this,labels_array);
        L1.setAdapter(myadp);

        L1.setOnItemClickListener(new OnItemClickListener(){
    		@Override
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    				long arg3) {
    		}
    	});
    }

    /* The adapter class.... */
    class myAdapter extends ArrayAdapter<String>
    {
  	   TextView label;
  	   View row;
  	   public myAdapter(Context context,String[] arr)
  	   {
  		    super(context, android.R.layout.simple_list_item_1, arr);
  	   }

  	   public View getView(int position, View convertView, ViewGroup parent)
  		{
  	 		   try{
  	 				LayoutInflater inflater=getLayoutInflater();
  	 				row = inflater.inflate(R.layout.lv_layout, parent, false);

  	 				LinearLayout L1 = (LinearLayout)row.findViewById(R.id.l1);
  	 				TextView header = new TextView(getApplicationContext());
  	 				L1.addView(header);
  	 				TextView label = new TextView(getApplicationContext());
  	 				L1.addView(label);
  					System.out.println("LAST : " + last_item);
  					header.setText(last_item);
  					label.setText(labels_array[position]);
  					label.setPadding(4, 1, 1, 1);
  					L1.setPadding(4, 4, 4, 4);

  					label.setTextColor(Color.BLACK);

  					if(!labels_array[position].substring(0,1).equalsIgnoreCase(last_item)){
  						System.out.println("ADD :  " + last_item);
  						header.setBackgroundResource(R.drawable.customshape_header);
  						header.setPadding(4, 1, 1, 1);
  						row.setEnabled(false);
  						header.setTextColor(Color.BLACK);
  						header.setText(labels_array[position].substring(0,1));
  						//label.setVisibility(View.GONE);
  						//position-=2;
  					}else{
  						System.out.println("REM :  " + last_item);
  						header.setVisibility(View.GONE);
  					}
  					last_item = labels_array[position].substring(0,1);

  	 		   }catch(Exception e){

  			   }
  		    return row;
  		}
    }
}

Now its ready to run the application.

Please leave your valuable comments on this post.

Sony's new HD Android SmartPhone Sony Xperia S – Really Smart.

Features include

GENERAL
2G Network GSM 850 / 900 / 1800 / 1900
3G Network HSDPA 900 / 2100 – LT26i
HSDPA 850 / 1900 / 2100 – LT26a

BODY
Dimensions 128 x 64 x 10.6 mm
Weight 144 g
- Touch-sensitive controls

DISPLAY
Type LED-backlit LCD, capacitive touchscreen, 16M colors
Size 720 x 1280 pixels, 4.3 inches (~342 ppi pixel density)
Multitouch Yes, up to 10 fingers
Protection Scratch-resistant glass
- Sony Mobile BRAVIA Engine
- Timescape UI

SOUND
Alert types Vibration; MP3 ringtones
Loudspeaker Yes
3.5mm jack Yes
MEMORY
Card slot No
Internal 32 GB, 1 GB RAM
DATA GPRS Up to 86 kbps
EDGE Up to 237 kbps
Speed HSDPA, 14.4 Mbps; HSUPA, 5.8 Mbps
WLAN Wi-Fi 802.11 b/g/n, Wi-Fi Direct, DLNA, Wi-Fi hotspot
Bluetooth Yes, v2.1 with A2DP, EDR
NFC Yes
USB Yes, microUSB v2.0, HS
CAMERA
Primary 12 MP, 4000×3000 pixels, autofocus, LED flash


Features
Geo-tagging, touch focus, face and smile detection, 3D sweep panorama, image stabilization
Video
Yes, 1080p@30fps, continuous autofocus, video light, video stabilizer
Secondary Yes, 1.3 MP, 720p@30fps
FEATURES
OS Android OS, v2.3 (Gingerbread), planned upgrade to v4.0
Chipset Qualcomm MSM8260 Snapdragon
CPU Dual-core 1.5 GHz
GPU Adreno 220

Sensors Accelerometer, gyro, proximity, compass
Messaging SMS (threaded view), MMS, Email, IM, Push Email
Browser HTML5, Adobe Flash
Radio Stereo FM radio with RDS
GPS Yes, with A-GPS support and GLONASS
Java Yes, via Java MIDP emulator
Colors White, Black
- MicroSIM card support only
- TV launcher
- SNS integration
- HDMI port
- Active noise cancellation with dedicated mic
- MP4/H.263/H.264/WMV player
- MP3/eAAC+/WMA/WAV player
- TrackID music recognition
- Google Search, Maps, Gmail,
YouTube, Calendar, Google Talk
- Document viewer
- Voice memo/dial/commands
- Predictive text input
BATTERY
Standard battery, Li-Ion 1750 mAh
Stand-by Up to 450 h (2G) / Up to 420 h (3G)
Talk time Up to 7 h 30 min (2G) / Up to 8 h 30 min (3G)
Music play Up to 25 h

How to use global variables in android? -Part 2

Hello all….

In a previous post I showed a method to share global variables across your android application.
Those were done using a static class.
Now today I will show you another way of sharing global variables across the application

Check these posts for sharing data across the application.
1. http://coderzheaven.com/2011/05/global-variables-in-android/
2. http://coderzheaven.com/2011/05/global-variables-in-android%e2%80%a6/
3. http://coderzheaven.com/2011/03/passing-data-between-intents-in-android/

Now in this method. first create a class named “GlobalClass” and extends the “Applictation” class.

This is how it will look like.

package com.coderzheaven.pack;

import android.app.Application;

class GlobalClass extends Application {

	  public static String myVal;

}

Inside which I have a variable named “myVal” which is a string. This is the global string variable that I am using to pass values across the application.

Now the main java class
Here I am using two activities just to demonstrate the sharing of global variables across the application.
Here is the first activity.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

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

        // Assigning some value to the global variable //
        GlobalClass.myVal = "Hello from CoderzHeaven";

        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new  OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(GlobalVariablesDemo.this, SecondClass.class));
			}
		});
    }
}

This line shows how to assign value to a global variable.

GlobalClass.myVal = “Hello from CoderzHeaven”;

Now the second activtiy.

package com.coderzheaven.pack;

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

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

        System.out.println("Accessing the global string : " + GlobalClass.myVal);

        TextView tv = (TextView)findViewById(R.id.tv);
        tv.setText("Global String : " + GlobalClass.myVal);
    }
}

This is how you access the global variable.

GlobalClass.myVal

That’s all done.

Now go on and run the application.

Please leave your comments if you like this post.

Evi more intelligent than Siri and Iris

Ever Since the launch of Siri in iOS smartphones has become more user friendly and funny for people.
After that Iris was launched a rival for Siri, this too was a big hit.

A little bit about Siri
The application uses a natural language user interface to answer questions, make recommendations, and perform actions by delegating requests to a set of web services. Apple claims that the software adapts to the user’s individual preferences over time and personalizes results, and performing tasks such as finding recommendations for nearby restaurants, or getting directions

A little about Iris.

Iris is a personal assistant application for Android. The application uses natural language processing to answer questions based on user voice request. Iris currently supports Call, Text, Contact Lookup, and Web Search actions including playing videos, looking for: lyrics, movies reviews, recipes, news, weather, places and others. It was developed in 8 hours by Narayan Babu and his team at Dexetra Software Solutions Private Limited, a Kochi (India) based firm.

Now about Evi

Evi was launched by True Knowledge Ltd. company in Cambridge, England.
Evi was launched on January 19th 2012
Evi is a cloud based Artificial Intelligence (AI) which builds upon the core semantic search technology first used on www.trueknowledge.com While she has an app for both Android and iPhone, these are merely portals through which users can communicate with her. Users can ask questions by speaking or by using text input.
The app is free for download on Android, but has a nominal charge of $1 (£0.69) on iPhone to cover the cost of the voice recognition service, Nuance, which is not needed on the Android OS.
Evi is able to provide users with information via different means:
A direct answer derived from her database of (at time of writing) nearly a billion facts
Calling a number of APIs for specialist services and dynamic information which include TV listings, train times, restaurant bookings and more
Referring the user to websites which are directly related to the specific question
Checking Q&A sites to see if the question has been asked previously
Performing a web search and presenting the top results within the app.
Evi also includes a built in browser which allows the user to make use of the information presented, booking restaurants and making online purchases within the app itself.

Angry Birds Again, Angry Birds Space, the new Angry Birds coming.

We know Angry Birds have conquered almost all tablets and now the completely new edition is launching this March.
Acoording to the reports the new game will be launched on March.

Angry Birds Space already has an official website with an image of a slingshot on the Moon overlooking Earth.


The official blog spot says that

Angry Birds Space is a “completely new game with innovative new gameplay, but with some of the familiar Angry Birds elements that fans already know and love.”

Check out the official Blog site here.

How to get the elapsed time after app launch in Corona ?

In order to get the elapsed time after the application launch in Corona, use the following lines of code,

function elapsedTimeCalc( event )
  print ("Time elapsed since app launch---"..event.time/1000 )
end

Runtime:addEventListener("enterFrame", elapsedTimeCalc)

Thus we will get the elapsed time after the app launch in milliseconds.
:)

Listening to EditText input in Android using TextWatcher.

Hello all…….

In todays post I will show you how to listen to an EditText input in Android.
Often we need this in our applications.
We implement this with the help of TextWatcher class.

Here is the java code for this.

package com.coderzheaven.test;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

public class Test extends Activity{
	private EditText ed_txt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ed_txt=(EditText)findViewById(R.id.EditText01);

        ed_txt.addTextChangedListener(new TextWatcher() {
        	public void afterTextChanged(Editable s) {
        		if(ed_txt.getText().toString().trim().length() > 0){
	        		if(Integer.parseInt(ed_txt.getText().toString().trim()) < 20 || Integer.parseInt(ed_txt.getText().toString().trim()) > 120){
	        			ed_txt.setTextColor(Color.GREEN);
					}else{
						Toast.makeText(getApplicationContext(), "High", Toast.LENGTH_SHORT).show();
						ed_txt.setTextColor(Color.RED);
					}
        		}
        	}

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    	    public void onTextChanged(CharSequence s, int start, int before, int count) {
    	    }
        });
    }
}

Here I am checking whether the input value in the edittext is between 20 and 120 if yes then change the text color to Green otherwise to Red.

Please leave your valuable comments on this post

How to create a scrollable TextView in android?

The simplest way to create a Scrolling TextView in android is to place it inside a ScrollView.
Here is a sample xml file with a scrollable TextView.

<?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"
    >
<ScrollView
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:fillViewport="true">
	<LinearLayout
		android:layout_width="fill_parent"
		android:layout_height="fill_parent">
	<TextView android:text="sample text "
		android:id="@+id/tv"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent">
	</TextView>
	</LinearLayout>
</ScrollView>
</LinearLayout>

Listening to checkBox stateChange in Android

This is a simple example showing how to listen to checkbox in android. To check whether the checkbox is in on state or in off state just add a listener to the checkbox you want to listen.

This is how we do this.

ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
});

This is the layout contaning a checkbox.

<?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="Coderzheaven CheckBox Demo"
	    />
	<CheckBox
		android:text="Check Me"
		android:id="@+id/CheckBox01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
	</CheckBox>
</LinearLayout>

This is the java code for listening to the state change

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

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

        ch = (CheckBox)findViewById(R.id.CheckBox01);
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(getApplicationContext(), "Not Checked", Toast.LENGTH_SHORT).show();
				}
			}
		});
    }
}

Download the sample code here

Please leave in your valuable comments on this post.

Digital Clock Widget in Android.

Digital Clock is a very useful widget in android to show time in your application.
Here is a simple demo on using digital Clock widget.

First In the layout file copy this 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"
    android:gravity="center|center_vertical"
    android:background="@drawable/android_3"
    >

<DigitalClock
	android:text="Digital Clock"
	android:id="@+id/DigitalClock01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:background="@drawable/header_bg"
	android:gravity="center|center_vertical"
	android:layout_gravity="center|center_vertical"

	android:layout_margin="10dp">
</DigitalClock>
</LinearLayout>

This creates a digital clock widget in the UI which will automatically update the time from the device.

Now in the java file you can reference it like this.
Since Digital Clock extends TextView you can apply every methods that you apply on a TextView.

        DigitalClock dg;
        dg = (DigitalClock)findViewById(R.id.DigitalClock01);
        dg.setTextColor(Color.RED);
        dg.setTextSize(25f);

Digital Clock Demo in Android

Please leave your comments on this post.

How to change the activity orientation through java code in android?

Here is a simple way to change the orientation of the activity in android
Through java code we do this….

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

Through xml we do this

<activity android:name=”.MainActivity”
           android:label=”@string/app_name”
           android:screenOrientation=”landscape” >
       <intent-filter>
          <action android:name=”android.intent.action.MAIN” />
          <category android:name=”android.intent.category.LAUNCHER” />
       </intent-filter>
</activity>

Following are two other values that you can specify in the android:screenOrientation attribute:

➤➤ portrait — Portrait mode
➤➤ sensor — Based on the accelerometer

Please leave your valuable comments.

How to place layouts one over another in android using addContentView()?

Hello all…

In today’s tutorial I will show you how to add different layouts one over another in android through java code.
For this we use the function addContentView() which is a variation on setContentView(View, android.view.ViewGroup.LayoutParams) to add an additional content view to the screen.

Here I will create an xml with a textView and a Edittext and on another layout i Will have edittext, imageView etc.
I am going to place these two layouts one over the other.

First layout is named “main.xml” which will look like this.

<?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="CoderzHeaven"
	    />
	<EditText
		android:text="CoderzHeaven"
		android:id="@+id/EditText01"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
	</EditText>
</LinearLayout>

And the second xml named “second.xml”

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center_horizontal" >

<ScrollView
	android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:fadeScrollbars="true">

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center_horizontal" >

		<TextView
			android:text="TextView"
			android:id="@+id/TextView01"
			android:layout_width="fill_parent"
			android:gravity="center"
			android:layout_gravity="center|center_horizontal"
			android:layout_height="wrap_content">
		</TextView>

		<ImageView
			android:id="@+id/ImageView01"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:src="@drawable/android_3"
			android:layout_gravity="center|center_horizontal">
		</ImageView>

		<EditText
			android:text="CoderzHeaven"
			android:id="@+id/EditText01"
			android:layout_margin="5dp"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content">
		</EditText>

		<EditText
			android:text=""
			android:id="@+id/EditText02"
			android:layout_margin="5dp"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content">
		</EditText>

		<RatingBar
			android:id="@+id/RatingBar01"
			android:layout_width="wrap_content"
			android:layout_margin="5dp"
			android:layout_height="wrap_content">
		</RatingBar>

		<Button
			android:text="Button"
			android:id="@+id/Button01"
			android:layout_gravity="center|center_horizontal"
			android:layout_width="fill_parent"
			android:layout_margin="5dp"
			android:layout_height="wrap_content">
		</Button>
	</LinearLayout>
</ScrollView>
</LinearLayout>

Now I am going to add these two xml in a single activity. The xml which you add first will have lower z-order.

This is the activity java file.

package com.coderzheaven.pack;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

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

        LayoutInflater inflater = getLayoutInflater();
        getWindow().addContentView(inflater.inflate(R.layout.second, null),
        						   new ViewGroup.LayoutParams(
        						   ViewGroup.LayoutParams.FILL_PARENT,
        						   ViewGroup.LayoutParams.FILL_PARENT));
    }
}

Here I am adding the main.xml before second.xml that is why main.xml is below second.xml.
After running this application you will see this window.

You can download the sample code from here.
Please leave your valuable comments if you find this post useful.

Find me on facebook, twitter and G+ for more updates.

How to use Preferences in android?

Hello all…

Today I will show you how to use preferences in android?

First we will create preferences using

EditTextPreference

Create a folder named “xml” inside the “res” folder and inside that create an xml named “preferences.xml”.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
	<EditTextPreference android:title="User Name"
		android:key="username"
		android:summary="Please enter username">
	</EditTextPreference>
	<EditTextPreference android:title="Password"
		android:password="true"
		android:key="password"
		android:summary="Please enter password">
	</EditTextPreference>
</PreferenceScreen>

Now create a java file named “PreferenceDemo.java” in your src folder and copy this code into it.

package com.coderzheaven.pack;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class PreferencesDemo extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences);
    }
}

Now in your main java file copy this code..

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

		SharedPreferences myprefs;
        EditText user = null;
		EditText password = null;
        Button login_but;

        @Override
        public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	        Intent i = new Intent(MainActivity.this,PreferencesDemo.class);
	        startActivity(i);
       }
}

Run it now. Your screen will appear like this

Now we will make some changes in the main java code, so that if the user has set preferences then we will navigate to another xml which will allow user to enter the values stored in the preferences and check it..

Copy this code to your main java file.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

		SharedPreferences myprefs;
        EditText user = null;
		EditText password = null;
        Button login_but;

        @Override
        public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	        myprefs = PreferenceManager.getDefaultSharedPreferences(this);

	        // get the preference values //
	        final String username_ = myprefs.getString("username", null);
	        final String password_ = myprefs.getString("password", null);

	        // check whether those are null or not //
		    if (username_ != null && password_ != null){

		        setContentView(R.layout.main);

		        user = (EditText)findViewById(R.id.userText);
		        password = (EditText)findViewById(R.id.passwordText);
		        login_but = (Button)findViewById(R.id.loginButton);
		        login_but.setOnClickListener(new OnClickListener() {

		        public void onClick(View v) {
			        try {
				        if(username_.equalsIgnoreCase(user.getText().toString())
					        && password_.equals(password.getText().toString())) {
					        Toast.makeText(MainActivity.this, "Preferences value matching!!", Toast.LENGTH_SHORT).show();
					        Intent i = new Intent(MainActivity.this,PreferencesDemo.class);
					        startActivity(i);
				        } else {
				        	Toast.makeText(MainActivity.this,"Preferences value not matching!!", Toast.LENGTH_SHORT).show();
				        }
			        } catch (Exception e) {
			        	e.printStackTrace();
			        }
		        }
		        });
		    } else {
		    	Intent i = new Intent(this, PreferencesDemo.class);
		    	startActivity(i);
	        }
        }
}

Your main.xml will look like this.

<?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="username"
		/>
		<EditText
			android:id="@+id/userText"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
		/>
		<TextView
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:text="password"
		/>
		<EditText
			android:id="@+id/passwordText"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content"
			android:password="true"
		/>
		<Button
			android:id="@+id/loginButton"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="login"
			android:textSize="20dp"
		/>
</LinearLayout>

Please leave your valuable comments on this post.

Custom Alert in android.

We can create any type of alert in android.
Today I will show a simple example showing how to create a custom alert in android.

i.e you can provide any layout to your alert dialog.

Now we will start.

First create an xml for your alert dialog.
Here I am creating an xml that contains a textView, an imageView, two editText, a ratingbar and a button.
All these are placed inside a scrollview.
create a new xml file named “custom_alert.xml” in the res/layout folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center_horizontal" >

<ScrollView
	android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:fadeScrollbars="true">

    <LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center|center_horizontal" >

		<TextView
			android:text="Custom Alert"
			android:id="@+id/TextView01"
			android:layout_width="fill_parent"
			android:gravity="center"
			android:layout_gravity="center|center_horizontal"
			android:layout_height="wrap_content">
		</TextView>

		<ImageView
			android:id="@+id/ImageView01"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_gravity="center|center_horizontal">
		</ImageView>

		<EditText
			android:text="CoderzHeaven"
			android:id="@+id/EditText01"
			android:layout_margin="5dp"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content">
		</EditText>

		<EditText
			android:text=""
			android:id="@+id/EditText02"
			android:layout_margin="5dp"
			android:layout_width="fill_parent"
			android:layout_height="wrap_content">
		</EditText>

		<RatingBar
			android:id="@+id/RatingBar01"
			android:layout_width="wrap_content"
			android:layout_margin="5dp"
			android:layout_height="wrap_content">
		</RatingBar>

		<Button
			android:text="Close App"
			android:id="@+id/Button01"
			android:layout_gravity="center|center_horizontal"
			android:layout_width="fill_parent"
			android:layout_margin="5dp"
			android:layout_height="wrap_content">
		</Button>

	</LinearLayout>
</ScrollView>
</LinearLayout>

Now in your main java file copy this code.

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

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

        showAlert();
    }

    public void showAlert(){
    	 Dialog dialog = new Dialog(this);
         dialog.setContentView(R.layout.custom_alert);
         dialog.setTitle("This is a custom dialog box");
         dialog.setCancelable(true);

         TextView text = (TextView) dialog.findViewById(R.id.TextView01);
         text.setText("Custom alert demo");

         ImageView img = (ImageView) dialog.findViewById(R.id.ImageView01);
         img.setImageResource(R.drawable.android_3);

         Button button = (Button) dialog.findViewById(R.id.Button01);
         button.setOnClickListener(new OnClickListener() {
         @Override
             public void onClick(View v) {
                 finish();
             }
         });
         dialog.show();
    }
}

The showAlert function will create the Dialog with the custom layout and show it.

This is the main.xml. Actually we dont need this .

<?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="@string/hello"
    />
</LinearLayout>

Here is the AndroidManifest.xml

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

Custom Alert in Android

Please leave your valuable comments on this post

Using Android Built in drawables.

This is a simple example showing how to use android built in drawables.

Here I am showing only the 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"
    >
<EditText
	android:text=""
	android:hint="Search here"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_menu_search">
</EditText>
<EditText
	android:text=""
	android:hint="Email"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_dialog_email">
</EditText>
<EditText
	android:text=""
	android:hint="Information"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_dialog_info">
</EditText>
<EditText
	android:text=""
	android:hint="Send"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_menu_send">
</EditText>
<EditText
	android:text=""
	android:hint="Media play"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_media_play">
</EditText>
<EditText
	android:text=""
	android:hint="Add"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_input_add">
</EditText>
<EditText
	android:text=""
	android:hint="Delete"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_delete">
</EditText>
<EditText
	android:text=""
	android:hint="Details"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:drawableLeft="@android:drawable/ic_menu_info_details">
</EditText>
</LinearLayout>

Please leave your valuable comments on this post.

How to open browser from android cocos2D Application?

This code snippet helps you to open browser in android cocos2D application

public void openBrowser(){
		CCDirector.sharedDirector().getActivity().runOnUiThread(new Runnable() {
		    public void run() {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
				CCDirector.sharedDirector().getActivity().startActivity(browserIntent);
		}});
	}

Call this function anywhere inside your cocos2D project to open the browser with the corresponding URL.

CustomAlert without any custom Layout in android.

We can create a dialog with custom alert dialog with our xml in android.
But for making simple alerts we can make custom alerts through code itself.

Here is a simple function for this. Here I am having a Listview and an edittext with two buttons in the alertBox.

  public void addDialog(){

          String test[] = {"hello1","hello2"};

    	  AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(true);
          builder.setTitle("My Title");
          builder.setInverseBackgroundForced(true);
          builder.setIcon(R.drawable.android_2);
          builder.setItems(test, new OnClickListener() {
  			@Override
  			public void onClick(DialogInterface dialog, int which) {
  				System.out.println("onClick " + which);
  			}
  		  });
          builder.setAdapter(myadp, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				System.out.println("DialogInterface : " + which);
			}
		  });

          EditText ed = new EditText(this);
          builder.setView(ed);
          builder.setPositiveButton("Yes",
                  new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog,
                              int which) {
                          dialog.dismiss();
                      }
                  });
          builder.setNegativeButton("No",
                  new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog,
                              int which) {
                          dialog.dismiss();
                      }
                  });
          AlertDialog alert = builder.create();
          alert.show();
    }

Please leave your valuable comments on this post.

Custom Alert

How to make your activity appear like a dialog box in android?

Hello all..

Today I will talk about how to theme your activities the way you want.
Besides that android provides many built in themes that you can use instead of all writing it yourselves.
One of those kind is making the activity appear like a dialog box.

Here is how you do it.
After creating your activity -> go to AndroidManifest.xml. then add this inside the activity tag.

android:theme=”@android:style/Theme.Dialog”

After that the manifest will look something like this.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.Dialog">
        <activity android:name=".ThemeActivityDemo"
                  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 activity for which you have added this theme will appear as a dialog as shown in the figure.

Theme Android activity

Theme Android activity

iOS apps crash more than Android Apps

Hello all…

Recent studies has shown that apps that run on Apple’s iOS crashes more than Google’s Android apps.

This is something that people who are involved in computer repair training
should be aware of.
According to the studies iOS apps crashes more than 3 times as compared to Android apps.

These are some of the results.

Source from this link.
http://www.forbes.com/sites/tomiogeron/2012/02/02/does-ios-crash-more-than-android-a-data-dive/

For people thinking iOS is the best smartphone OS, this is an answer to them.

Apply Custom Theme for your activity in android.

In today’s tutorial I will show how to apply custom theme for your activity in android.
Android has several built in themes for applying to your activity but you can also provide your own custom themes for your activity.

Now we will start creating an activity with a custom theme applied.
Create a fresh project and name it ThemeActivity.

Now create a file named “styles.xml” in the res/values folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="android:Theme.Light">
    <item name="android:windowBackground">@color/custom_theme_color</item>
    <item name="android:colorBackground">#ff00ff</item>
</style>
</resources>

Now in the AndroidManifest.xml make changes in the activity tag for the activity you want to apply this theme.

Here I have only one activity which is the main activity for which I am applying the theme.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/CustomTheme">
        <activity android:name=".ThemeActivityDemo"
                  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 is the main java file.

package com.coderzheaven.pack;

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

public class ThemeActivityDemo extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

I am not making any changes in the main.xml.
Now applying theme to this activity is complete and you can now run the project.

Apply theme to your activity

Apply theme to your activity

Show Alert in cocos2D Android.

Here is a simple example showing alert in android cocos2D.
For this I am using an example from my previous android cocos2D tutorial..
So please read that tutorial before reading this because the I am using the classes and files from it.

I am only changing the Gamelayer.java file to show an Alert Dialog when the sprite move is finished.
Check the showAlert() function which will show the Alert.

Here is the modified GameLayer.java

package com.coderzheaven.pack;

import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.view.MotionEvent;

public class GameLayer extends CCColorLayer
{
	protected CCLabel _label = null;
	CGSize winSize = CCDirector.sharedDirector().displaySize();
	int myscore = 0;

	public static CCScene scene()
	{
		CCScene scene = CCScene.node();
		CCColorLayer layer = new GameLayer(ccColor4B.ccc4(255, 255, 255, 255));
		scene.addChild(layer);
		return scene;
	}

	protected GameLayer(ccColor4B color)
	{
		super(color);
		this.setIsTouchEnabled(true);

		DBOperations();
	}

	public void DBOperations(){
		addAndroid();
		createAndInitializeTables();
		insertData(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		updateTable(myscore);
		myscore = getDataFromTable();
		System.out.println("SCORE : " + myscore);
		showLabel(myscore);
	}

	public void createAndInitializeTables(){
        try{
        	MyTable mytable = new MyTable();
        	String[] tableCreateArray = {mytable.getDatabaseCreateQuery()};
    		dbOperation operation = new dbOperation(CCDirector.sharedDirector().getActivity(),tableCreateArray);
			operation.open();
			operation.close();
        }catch(Exception e){
           System.out.println("Error creating table " + e.getMessage());
        }
        System.out.println("Table successfully created!!");
	}
	public int getDataFromTable(){
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		MyTable mytable = new MyTable();
		int score = 0;
		String  condition2 = mytable.getID() +" = 1 ";
        String[] dbFields4 = {mytable.getScore()};
        Cursor cursor =  operationObj.getTableRow(mytable.getTableName(),dbFields4,condition2,mytable.getID() + " ASC ",1 +"");
        if(cursor.getCount()>0)
        {
        	 cursor.moveToFirst();
        	 do{
        		 score = cursor.getInt(0);
        	 }while(cursor.moveToNext());
        }
        cursor.close();
		cursor.deactivate();
		operationObj.close();

		return score;
	}
	public void insertData(int score){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),score+"");
        operationObj.insertTableData(mytable.getTableName(),initialValues);
        int maxID = operationObj.lastInsertedID(mytable.getTableName());
        System.out.println("LAST INSERTED ID : " + maxID);
        operationObj.close();
	}
	public void updateTable(int scr){
		MyTable mytable = new MyTable();
		dbOperation operationObj = new dbOperation(CCDirector.sharedDirector().getActivity());
        operationObj.open();
        String condition = mytable.getID() + " = 1";
		ContentValues initialValues = new ContentValues();
    	initialValues.put(mytable.getScore(),scr+"");
        operationObj.updateTable(mytable.getTableName(),initialValues,condition);
        operationObj.close();
	}
	public void showLabel(int scr){

		if(_label != null){
			this.removeChild(_label,true);
		}
		_label = CCLabel.makeLabel("Score : " + scr, "Verdana", 20);
		_label.setColor(ccColor3B.ccBLACK);
		_label.setPosition(55f, winSize.height - 15);
		addChild(_label);
	}
	public void addAndroid(){
		CGSize winSize = CCDirector.sharedDirector().displaySize();
		CCSprite player = CCSprite.sprite("android.png");
		player.setPosition(CGPoint.ccp(player.getContentSize().width / 2.0f, winSize.height / 2.0f));
		addChild(player);

		CCMoveTo actionMove = CCMoveTo.action(3, CGPoint.ccp(winSize.getWidth(), winSize.getHeight()/2.0f));
		CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
		CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);

		player.runAction(actions);
	}

	public void spriteMoveFinished(Object sender)
	{
		CCSprite sprite = (CCSprite)sender;
		this.removeChild(sprite, true);
		myscore++;
		updateTable(myscore);
		showLabel(myscore);
		showAlert();
		//addAndroid();
	}
	public void showAlert(){
		CCDirector.sharedDirector().getActivity().runOnUiThread(new Runnable() {
		    public void run() {
		    	AlertDialog.Builder builder = new AlertDialog.Builder(CCDirector.sharedDirector().getActivity());
		    	builder.setMessage("Are you sure you want to exit?")
		    	       .setCancelable(false)
		    	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	        	   CCDirector.sharedDirector().getActivity().finish();
		    	           }
		    	       })
		    	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		    	           public void onClick(DialogInterface dialog, int id) {
		    	                dialog.cancel();
		    	           }
		    	       });
		    	AlertDialog alert = builder.create();
		    	alert.show();
		    }
		});
	}

	@Override
	public boolean ccTouchesBegan(MotionEvent event)
	{
		return true;
	}
}

Please copy all other files from this project before proceeding.
A sample project is available for download for this tutorial.

Alert in android cocos2D

Changing the style or theme of default alertDialog in Android.

Hello everyone,
Here is a simple example showing how to change the theme of default AlertDialog in android.

Check this post before for understanding how to use styles.
http://www.coderzheaven.com/2012/04/17/inherit-styles-extend-styles-android/

To start first create a fresh project named AlertTest.
In the AlertTestDemo.java file copy this code

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

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

        AlertDialog dialog = new CustomDialog(this);
        dialog.setButton("OK", new OnClickListener()
        {
            public void onClick(DialogInterface arg0, int arg1)
            {
            }
        });
        dialog.setTitle("Coderzheaven");
        dialog.setMessage("Heaven of all working codes!! n Keep Visiting..n" +
        		"Thankyou.");
        dialog.show();
    }
}


Now create a file named “styles.xml” inside the res/values folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="CenterTextView" parent="@android:style/Widget.TextView">
        <item name="android:gravity">center|center_vertical</item>
    </style>

    <style name="CenterJustifyDialogTitle" parent="@android:style/DialogWindowTitle" >
         <item name="android:gravity">center|center_vertical</item>
         <item name="android:textColor">#000000</item>
    </style>

	<style name="CenterJustifyTheme1" parent="@android:style/Theme.Translucent">
        <item name="android:textViewStyle">@style/CenterTextView</item>
        <item name="android:windowTitleStyle">@style/CenterJustifyDialogTitle</item>
    </style>

    <style name="CenterJustifyTheme2" parent="@android:style/Theme.Black">
        <item name="android:textViewStyle">@style/CenterTextView</item>
        <item name="android:windowTitleStyle">@style/CenterJustifyDialogTitle</item>
    </style>

    <style name="CenterJustifyTheme3" parent="@android:style/Theme.Light">
        <item name="android:textViewStyle">@style/CenterTextView</item>
        <item name="android:windowTitleStyle">@style/CenterJustifyDialogTitle</item>
    </style>

</resources>

Now create another java file named “CustomDialog.java” and copy this code into it.
We will apply the theme through this java file.
The theme is located and named in the above xml file.


package com.coderzheaven.pack;
import android.app.AlertDialog;
import android.content.Context;
import com.coderzheaven.pack.R;


public class CustomDialog extends AlertDialog {
		public CustomDialog(Context ctx)
		{
			super(ctx, R.style.CenterJustifyTheme1);
		}
}