Show Alert in cocos2D Android.

By | February 4, 2012

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

One thought on “Show Alert in cocos2D Android.

  1. sandeep

    Thanks for your tutorial, It works great.
    But i need to go to another scene when i click on No option on the alert, How can i achieve that. Please Guide me.

    Thanks in Advance

    Reply

Leave a Reply to sandeep Cancel reply

Your email address will not be published. Required fields are marked *