"Conversion to Dalvik format failed with error 1" Error in ANDROID / Eclipse.

This is a normal error when you import some project into eclipse.
I will show you how to solve this

First try cleaning the project from project->Clean.
If this didn’t work, then try these

Follow these steps
1. Go to Project » Properties » Java Build Path » Libraries and remove all except the “Android X.Y” (eg: Android 1.5). click OK.
2. Go to Project » Clean » Clean projects selected below » select your project and click OK.

Now your error may be gone.
Happy coding…

Cocos2D Sprite Sheet Animation

Hi,

Suppose you have a sprite sheet of the desired animation you want. But how will you use that sprite sheet animation in your program using cocos2D? That’s simple. See the following code first.

Note : But how to make a sprite sheet? That topic can be found here. Making of sprite sheets from individual images are well discussed in that post.


//Initializing a CCSpriteBatchNode with our sprite sheet image
CCSpriteBatchNode *newSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"jumpingOver.png"];

//Adding the spriteSheet to the layer & setting the z orientations
[self addChild:spriteSheet z:14];

//Creating Frames from the frames file jumpingOver.plist
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"jumpingOver.plist"];

//Initializing a sprite with the first frame from plist
CCSprite *jumper = [CCSprite spriteWithSpriteFrameName:@"jump1.png"];

//Creating an NSMutableArray for adding the frames from plist
NSMutableArray *framesArray = [[NSMutableArray array] retain];

//Iterating for the total number of frames from plist
//Here supposing our jumpingOver plist have 15 images
for(int i=0; i<15; i++){
//Adding frames to our framesArray from the frames
[framesArray addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"jump%d.png",i]]];
}

//Creating an animation using the frames in framesArray
CCAnimation *jumping = [CCAnimation animationWithFrames:framesArray delay:0.25f];

//Setting our jumper sprite sprite sheet animation to the position of one another sprite
//oldSprite is our previous sprite on that position we are adding the animation
jumper.position=oldSprite.position;

//Creating action from the animation jumping
CCAction *jumpAction= [CCAnimate actionWithAnimation:jumping];

//running the action on jumper sprite with the sprite sheet animation action on jumpAction
[jumper runAction:jumpAction];

//Adding the jumper sprite to the layer with z orientation
[self addChild:jumper z:15];

If you have any doubt in animating your sprite sheets or about creating a sprite sheet , please feel free to comment us!

Email id verification using Objective C

Hi,

In order to verify an email address you have entered is valid or not using Objective C, use the following code.

- (BOOL) checkYourMail: (NSString *) myEmail{
      NSString *checkMail= @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}";
      NSPredicate *matchMail = [NSPredicate predicateWithFormat:@"Matching %@", checkMail];
      return [matchMail evaluateWithObject:myEmail];
}

:)

Pausing & Resuming Sound in Cocoa Mac

Hi,

If you want to Pause an instance of NSSound which is being played in Cocoa Mac, use the following line of code.

[yourSound pause];

‘yourSound’ is the NSSound Object.

Similarlyl for resuming NSSound in cocoa Mac

[yourSound resume];

Using Gestures in ANDROID,A Simple example.

This is a really simple example illustrating gestures in ANDROID.
You Know that everything you do with your hand inside the phone is a gesture like SingleTap, doubleTap etc.
Here is a quick illustration of this.
For this the activity must implement OnGestureListener. The GestureDetector detects the gestures.
Let’s look at the example.

package pack.GestureSampleThree;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class GestureSampleThreeExample extends Activity implements OnGestureListener {
	 private LinearLayout main;
	    private TextView viewA;

	    private GestureDetector gestureScanner;

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

	        gestureScanner = new GestureDetector(this);

	        main = new LinearLayout(this);
	        main.setBackgroundColor(Color.GRAY);
	        main.setLayoutParams(new LinearLayout.LayoutParams(320,480));

	        viewA = new TextView(this);
	        viewA.setBackgroundColor(Color.YELLOW);
	        viewA.setTextColor(Color.BLACK);
	        viewA.setTextSize(16);
	        viewA.setLayoutParams(new LinearLayout.LayoutParams(320,80));
	        main.addView(viewA);

	        setContentView(main);
	    }

	    @Override
	    public boolean onTouchEvent(MotionEvent me) {
	        return gestureScanner.onTouchEvent(me);
	    }


	    public boolean onDown(MotionEvent e) {
	        viewA.setText("-" + "DOWN" + "-");
	        return true;
	    }

	    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	        viewA.setText("-" + "FLING" + "-");
	        return true;
	    }


	    public void onLongPress(MotionEvent e) {
	        viewA.setText("-" + "LONG PRESS" + "-");
	    }


	    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
	        viewA.setText("-" + "SCROLL" + "-");
	        return true;
	    }


	    public void onShowPress(MotionEvent e) {
	        viewA.setText("-" + "SHOW PRESS" + "-");
	    }


	    public boolean onSingleTapUp(MotionEvent e) {
	        viewA.setText("-" + "SINGLE TAP UP" + "-");
	        return true;
	    }
	}

The layout file main.xml for the above code is

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

The manifest file.

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

A complete example for making your own gesture application in ANDROID is explained in this tutorial

How to open browser in an ANDROID application? How to open a URL from an ANDROID application?

Hi all,In this tutorial I will show you how to open browser from an ANDROID application.
This is done through intents. You know that intents are used to invoke other activities.
So we here invoke the browser activity.
The following code will open the default browser in your ANDROID phone.

package com.myPackage;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class OpenURL extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = "http://www.google.com/";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }
}

This is the manifest file for the above code.

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

How to make a sprite visible and invisible in Cocos2D ?

Hi,
In certain situations you may need to make visible or invisible certain sprites. But how to set a sprite visible and invisible in Cocos2D? See the following Cocos2D code.

//Set the sprite's visible value to 1 to make it visible
yourSprite.visible = 1;
//Set the sprite's visible value to 0 to make it invisible
yourSprite.visible = 0;

:)

How to change the Z value of a Sprite during an action in Cocos2D ?

Hi,
There may arise some situations where you need to change the z value of a particular sprite during an action in Cocos2D. So how can you do that? See the following lines of code.

CCSprite *sample= [CCSprite spriteWithFile:@"trialImage.png"];
sample.position = ccp(160,240);
[self addChild:sample z:1];
/* Some of your actions goes here! */
[self reorderChild:sample z:9];

This will re order the sprite’s tag to 9 from 1 after ‘your actions’. :)

How to show hyper link in Alert in Adobe AIR/ FLEX?




	coderzheaven.com";
             var alert:Alert = Alert.show(txt, "Alert with htmltext");
             alert.mx_internal::alertForm.mx_internal::textField.htmlText =txt;
        }
	]]>
        



Show Hyperlink in Alert

Show Hyperlink in Alert

How to create an action when a UITextField is clicked ?

Hi,
Want to invoke an action when a text field (UITextField) is clicked using Objective C? Use the following.

[myTextField addTarget:self action:@selector(textFieldTouched:) forControlEvents:UIControlEventTouchDown];
- (void) textFieldTouched:(id)sender {
        //Here goes your actions on TextField Clicked
}

:)

Creating a Button using Objective C

Hi,

Sometimes you may need to create some buttons to the View using Objective C code rather than using Interface Builder. Here is how you can do that easily and efficiently.
//You can create button with type. Here I am creating a Custom Button

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

//Then what? Give action to be performed on it!

[myButton addTarget:self action:@selector(newAction:)
forControlEvents:UIControlEventTouchUpInside];

//Giving Background, Frame & Title to the button

myButton.frame = CGRectMake(0, 0, 80, 40);
[myButton setBackgroundImage:[UIImage imageNamed:@"buttonImage.png"] forState:UIControlStateNormal];
[myButton setTitle:@"Go Next!" forState:UIControlStateNormal];

//Finally what?? Add it to the View

[self.view addSubview:myButton];

You can create any number of UIButtons like this! :)

How to show more than one animation in sequence in Cocos2D?

For showing a number of animations sequentially in Cocos2D we use the CCSequence.
CCSequence can accept a number of actions as parameters which will be executed in sequence , ie one after another.
Here is a sample code to so this.


        /*  This action will scale my_sprite */
        id scaleTo = [CCScaleTo actionWithDuration:4 scale:1.5];
        /*This action will move the sprite from current position to this point*/
        id moveTo = [CCMoveTo actionWithDuration:1.0f
                         position:ccp(size.width/3,size.height/3)];
        /* This will execute all the above actions in sequence. */
	id sequence=[CCSequence actions:scaleTo,moveTo,nil];
	/* Run the above actions for your sprite */
        [my_sprite runAction:sequence];

Android listView with icons

In this post, we will have a list whose rows are made up of image, Here we just supply data to the adapter and helping the adapter to create a View objects for each row

The output will be

For this first create a xml file to hold 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"
    >
		<TextView
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:text="@string/hello"
	    />
	    <ListView
			android:id="@android:id/list"
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"/>

</LinearLayout>

The next objective is to create the xml for listview row. Here i create 2 components a imageview and a a textview for displaying the selected row. Also the image for the imageView is put in the drawable folder and is referred in this xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ImageView
		android:id="@+id/icon"
		android:layout_width="wrap_content"
		android:paddingLeft="4dip"
		android:paddingRight="4dip"
		android:layout_height="wrap_content"
		android:src="@drawable/icon"/>
	<TextView
		android:id="@+id/label"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textSize="24sp"/>
</LinearLayout>

ok. Next create one main java file. Here instead of activity we extend the class ListActivity.That is shown below

package com.ImageListView.pack;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ImageListView extends ListActivity
{
    /** Called when the activity is first created. */
	TextView selection;
	String[] names;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       names = new String[] { "sunday", "monday", "tuesday", "wednesday",
					"thrusday", "friday", "saturday",};

       this.setListAdapter(new ArrayAdapter<String>(this, R.layout.custom, R.id.label,names));
		selection=(TextView)findViewById(R.id.label);

	}

	public void onListItemClick(ListView parent, View v,int position,long id)
	{
	 	selection.setText(names[position]);
	}

}

The names array contains the elements that is to be displayed. The second parameter in the setlistAdapter is the name of the xml file we create for the row, the third is the imageView in the custom xml file and the last is the name of the array

Important
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen.

However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id “@android:id/list”

How to install a new skin for your ANDROID Emulator?

Hi all..
In this tutorial I will lead you to show how to install a new skin for your ANDROID Emulator.
The steps are really easy
1. Download the skin from here( http://www.android.encke.net/)
2.Extract it and copy to android/platforms/the_version_of_emulator_you_want_to_skin/skins
3. Now from here you have two options for starting the emulator with the new skin
a. From the command-line.
b. From inside Eclipse.
a. To start from the command Line
Go to path android/tools/ and type
emulator -avd virtual_device_name -skin the_extracted_folder_name
and press enter.
b. To install the skin from inside eclipse
Go to Run->Run Configurations->Target and in the text below from additional command line options type this
-avd VD1.6 -skin HVGA-P

Here my extracted folder name is HVGA-P.

How to add files like images inside your emulator in ANDROID?

In many of our android applications we need images and other files to be inside your emulator, such as images in the gallery. But unlike iPhone we cannot simply drag and drop files inside the emulator., because iPhone’s is simply a simulator. It justs creates an envoronment for testing. But ANDROID mimics the real phone. So we need to put files into the memory space inside the phone.
In this tutorial I will show you how to add files to the gallery of ANDROID emulator.
First you need to create an SD card for the emulator.
Second start the emulator with the created SD Card.

These two things are covered in this tutorial.
Third Open File Explorer from Window-> showViews and search for File-explorer.
You can see the File-explorer in the screnshot below.

See the Market portion on the right side of the window.
There are two buttons for pulling data out of the emulator and other for putting data into the emulator. Click on the “push a file on to the device”

Then you will be prompted with a dialogue(see above screenshot). choose the file from your computer and click Open. The selected file will be in your Emulator SD Card.

Now to see the file inside your emulator.
Either restart your phone or restart the emulator. If you put an image file then go to “Gallery” and you will see the pulled in file.

Splitting a string using symbols in Objective C

Hi,
If you want to split a string between a symbol like, ‘.’ or ‘-’ or ‘,’ in Objective C, what to do?
See the code for how to split string in Objective C.

NSString *myString = @”song.mp3”;
NSArray *splitArray = [myString componentsSeparatedByString:@”.”];

This code will split the string ‘myString’ into ‘song’ & ‘mp3′ (separated by ‘.’) and stores in the splitArray indices 0 & 1 respectively. :)

How to empty an NSMutableArray ?

Hi,
Sometimes you may need to empty an array completely. How to do it? Use the following lines of code for it.

[yourArray removeAllObjects];

here yourArray is the name of your array! :)

How to make tableView transparent in iPhone ?

Hi,

If you want to make tableView transparent with only texts visible, use the following code

tableView.backgroundColor = [UIColor clearColor];

Retrieving Data from NSTextField in Cocoa Mac

Hi,

If you want to retrieve the data a user typed in on a Cocoa Mac application, follow the following steps.
1. You first need to declare a NSTextField variable in .h file

@interface SampleAppDelegate : NSObject {
NSTextField *myText;
}
@property (retain) IBOutlet NSTextField *myText;

2. Then you need to synthesize it for properties in .m file

@synthesize myText;

3. Connect myText with the interface
4. For getting data from this ‘myText’ use the following code

myText.stringValue

Using NotificationManager in ANDROID for showing notification, sample code.

Multiple Notifications are a unique feature in ANDROID phones. This tutorial will show you how to create notification from your application.
ANDROID uses the NotificationManager class to create the notification.
Let’s look at the code.

package com.Webviews;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NotificationActivity  extends Activity implements View.OnClickListener {

private Button button, clear;
private NotificationManager mManager;
private static final int APP_ID = 0;

@Override

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  button = (Button) this.findViewById( R.id.my_button);
  clear = (Button) this.findViewById( R.id.cancel);
  clear.setOnClickListener(new OnClickListener() {

	@Override
	public void onClick(View arg0) {

		mManager.cancel(APP_ID);
	}
  });
  button.setOnClickListener(this);
  mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onClick(View v) {

  Intent intent = new Intent(this,NotificationActivity.class);
  Notification notification = new Notification(R.drawable.icon,"Notification!!", System.currentTimeMillis());
  notification.setLatestEventInfo(NotificationActivity.this,"Send by which application","Description of the notification",
		  					      PendingIntent.getActivity(this.getBaseContext(), 0, intent,
		  					      PendingIntent.FLAG_NO_CREATE));
  mManager.notify(APP_ID, notification);
}
}

Explanation.

mManager.notify(APP_ID, notification);

This line in the code sends the notification where notification is the object of the Notification class where you can set the data and title for the notification.

This line will cancel the notification created by this application.

mManager.cancel(APP_ID);

The layout file for the above code “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:text="@string/hello"
    />

<Button
	android:text="Send Notification"
	android:id="@+id/my_button"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>

<Button
	android:text="Cancel Notification"
	android:id="@+id/cancel"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>

</LinearLayout>

Please leave your valuable comments on this post.

Changing the image of the sprite in cocos2D ?

Hi,

You all know how to add an Image to a sprite. But what if we need to change the image of the same sprite? How to do that?
Use the following line of code to change the image of a sprite which already initialized with a sprite.

[sampleSprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"newImage.png"]];

where sampleSprite is the name of your sprite and newImage is the new image you want to replace with!
:)

How to Flip Sprite in Cocos2D ?

Hi,

On certain occasions you may need to flip the sprite you are using in your application.
There are two ways to flip a sprite. Let’s see how this can be done along X-direction
Method:1

mySprite.flipX = 180;

where mySprite is the name of your sprite you want to flip.

Method:2

CCFlipX *flipOnX = [CCFlipX actionWithFlipX:YES];
[mySprite runAction:flipOnX ];

where mySprite is the name of your sprite & flipOnX is the name of the CCFlipX action.
:) . You can try the Y-direction your own!

How to stop the sprite sheet animation in cocos2D ?

Hi,

In one of our previous post we have discussed how to animate sprite sheet in cocos2D.
In some cases you may need to stop the sprite sheet animation abruptly. How to do that?
Here the way to do that. Use the following.

[spriteName stopAction:spriteNameAction];

where spriteName is the name of your sprite & spriteNameAction is the name of your sprite sheet animation action. :)

Getting name of selected item from NSPopUpButton in Cocoa Mac

Hi,

On many occasions you may need to use a popup button & in cocoa mac you can use NSPopUpButton objects for the same.
While using a pop up button we need to identify the name of the item selected from the pop up list. But how is that done?
You can use the following code for do the same.

NSPopUpButtonCell *nameHere = [sender selectedCell];

nameHere contains the name of your selected item from the NSPopUpButton. :)

How to create OptionsMenu in ANDROID?, a simple example……

This is a simple example of creating options Menu in ANDROID.
This menu can be seen by clicking on the “Menu Button” in ANDROID.
Check out this example.

	package com.options;

	import android.app.Activity;
	import android.os.Bundle;
	import android.view.Menu;
	import android.view.MenuItem;
	import android.widget.TextView;

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

	public boolean onCreateOptionsMenu(Menu menu) {
	  super.onCreateOptionsMenu(menu);
	  menu.add(0,0,0,"My Menu One");
	  menu.add(0,1,0,"My Menu two");
	  menu.add(0,2,0,"My Menu three");
	  menu.add(0,3,0,"My Menu Four");
	  menu.add(0,4,0,"My Menu Five");
	  return true;
	 }

	 public boolean onOptionsItemSelected(MenuItem item) {
	  super.onOptionsItemSelected(item);
	  TextView view = (TextView) findViewById(R.id.tv);
	  switch (item.getItemId()) {
	  case 0:
	      view.setText("Menu selected =>  "+item.getTitle());
	      break;
	  case 1:
		  view.setText("Menu selected => "+item.getTitle());
		  break;
	  case 2:
		  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 3:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 4:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 5:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 6:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  default:
	          view.setText("Nothing found.");
	  break;
	  }
	  return false;
	 }

	 public boolean onPrepareOptionsMenu(Menu menu) {
	  return super.onPrepareOptionsMenu(menu);
	 }
	}

The main.xml for the above code is

<?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:id="@+id/tv"
    />
</LinearLayout>
Options Menu in ANDROID

Options Menu in ANDROID