How to move a body manually in Box2D? or Give a force to a body in Box2D, iPhone.

This is a sample code to move a body in Box2D .
First you have to make a body with variable name “moving_rec” and call the below function in a schedular at regular intervals.

-(void) moveBody{
       b2Vec2 force = b2Vec2(0,0);
       force = b2Vec2(0,3);       //Giving the x an y to negative will move the body in opposite direction.
       moving_rec->SetLinearVelocity(force); //set Linear velocity for moving in a constant speed.
}

Please leave your comments on this post.

Creating a JButton component in swing

Java swing provides a native look and feel that emulates the look and feel of several platforms.
Here i am going to create a Button and adding it to Frame.

For this first create a Jframe object,a JPanel object and a Container object

JFrame f = new JFrame();
JPanel panel1 = new JPanel();
Container con = f.getContentPane();

Then Create a button object and add this ti JPanel object

JButton panel1_but = new JButton();
panel1.add(panel1_but);

and finally add JPanel to JFrame

panel1.add(panel1_but);

This full code is given below

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class mainframe implements WindowListener
{
	JFrame f = new JFrame();
	Container con = f.getContentPane();
	JPanel panel1 = new JPanel();
	mainframe()
	{
		createpanel1();
		f.addWindowListener(this);
		f.setSize(900, 600);
		f.setVisible(true);
		f.setLocationRelativeTo(null);
		f.setResizable(false);    ///cannot maximize
	   	f.setVisible(true);
	}
	public static void main(String args[])
	{
		new mainframe();
	}
	private void createpanel1()
	{
		JButton panel1_but = new JButton();
		panel1_but.setBounds(new Rectangle(450,400,200,40));
		panel1_but.setText("Continue");

		panel1.add(panel1_but);
		panel1_but.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//action to be performed....
			}
			}
		);
		panel1.setLayout(new BorderLayout());
		panel1.setBackground(Color.white);
		panel1.setVisible(true);
		con.add(panel1);
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
}

Pause And Resume iPhone Game Using Cocos2D

More than usually we need to apply the functions of Pause and Resume/Play for our games. In Mac’s cocos2D programming it’s more than simple. Simply use the following code for Pause & Resume where ever you want!

/*For Pausing the game*/

[[CCDirector sharedDirector] pause];
[self pauseSchedulerAndActions]; //Call for pausing all schedulers and actions

/*For Resuming/Playing back the game*/

[[CCDirector sharedDirector] resume];
[self resumeSchedulerAndActions]; // Call for resuming all schedulers and actions

:)

How to Refresh a HTML Page Using JavaScript ?

Hi,

Most probably you may have encountered a situation where you have to refresh the web page in your code.
Here is, how it could be done using JavaScript.











Here on button click it will call the function ‘refresh_yourPage()’, and it will refresh the page!

:)

How to read and write a text file that is stored in your application sandbox in ANDROID?

Hi all…..

In this post I will show you how to read a text file in ANDOID.
Let your file is in the your application sandbox of your ANDOID project, i.e the file’s location is /data/data/your_package_name folder.
To view this folder -> open File Explorer and expand each folder.
For this example to work first push te file into this folder, because I am not creating it now.
The file is named “myfile.txt”

This example reads the file line by line using readLine() function till the end of the file. Here your need two classes named “InputStreamReader” and “BufferedReader”. For writing into the file you need “OutputStreamReader” class. The result is displayed in a Toast. Make sure you notice it.

The following is the code for reading the text file………

String     res  =    null;
try {

	   InputStream       in = openFileInput("myfile.txt");

	   if (in != null) {
	    // prepare the file for reading
	     InputStreamReader input = new InputStreamReader(in);
	     BufferedReader buffreader = new BufferedReader(input);

	      res = "";
	      while (( line = buffreader.readLine()) != null) {
	      	res += line;
	      }
	      in.close();
	      Toast.makeText(getApplicationContext(),"File Contents ==> " + res,Toast.LENGTH_SHORT).show();
          }else{
	    }

} catch(Exception e){
       Toast.makeText(getApplicationContext(),     e.toString() +   e.getMessage(),Toast.LENGTH_SHORT).show();
}

Want More then

Follow this link

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Please leave your comments on this post.

Java Applet MouseEvents

A simple event based applet applications is described below
First importing the necessary header files
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=”MouseEvents” width=300 height=100>
</applet>
*/
Next step is to create a class which implements the “MouseListener” and “MouseMotionListener ”
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener {
String msg = “”;
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse clicked.”;
repaint();
}
Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse entered.”;
repaint();
}
Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse exited.”;
repaint();
}
Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Down”;
repaint();
}
Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Up”;
repaint();
}
Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “*”;
showStatus(“Dragging mouse at ” + mouseX + “, ” + mouseY);
repaint();
}
Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus(“Moving mouse at ” + me.getX() + “, ” + me.getY());
}
Display msg in applet window at current X,Y location. This “paint” method is called when JVM execute “repaint()” function . The “paint” method will refresh the screen
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

How to show preview of older posts at random in Blogger ?

Hi,
If you want to show the preview of your older posts at random in blogger page then use the following steps
1. Go to your blogger ‘Design’
2. Click ‘Add A Gadget’
3. Add ‘HTML/JavaScript’
4. Paste the following JavaScript code into it and save

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<style media="screen" type="text/css">
<!--

#spylist {
overflow:hidden;
margin-top:5px;
padding:0px 0px;
height:350px;
}
#spylist ul{
width:218px;
overflow:hidden;
list-style-type: none;
padding: 0px 0px;
margin:0px 0px;
}
#spylist li {
width:204px;
padding: 5px 5px;
margin:0px 0px 5px 0px;
list-style-type:none;
float:none;
height:70px;
overflow: hidden;
background:#fff url(http://i879.photobucket.com/albums/ab351/bloggerblogimage/blogger/post.jpg) repeat-x;
border:1px solid #ddd;
}

#spylist li a {
text-decoration:none;
color:#4B545B;
font-size:11px;
height:18px;
overflow:hidden;
margin:0px 0px;
padding:0px 0px 2px 0px;
}
#spylist li img {
float:left;
margin-right:5px;
background:#EFEFEF;
border:0;
}
.spydate{
overflow:hidden;
font-size:10px;
color:#0284C2;
padding:2px 0px;
margin:1px 0px 0px 0px;
height:15px;
font-family:Tahoma,Arial,verdana, sans-serif;
}

.spycomment{
overflow:hidden;
font-family:Tahoma,Arial,verdana, sans-serif;
font-size:10px;
color:#262B2F;
padding:0px 0px;
margin:0px 0px;
}

-->
</style>

    <script language="JavaScript">

imgr = new Array();

imgr[0] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[1] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[2] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[3] = "http://i43.tinypic.com/orpg0m.jpg";

imgr[4] = "http://i43.tinypic.com/orpg0m.jpg";
showRandomImg = true;

boxwidth = 555;

cellspacing = 6;

borderColor = "#232c35";

bgTD = "#000000";

thumbwidth = 70;

thumbheight = 70;

fntsize = 12;

acolor = "#666";

aBold = true;

icon = " ";

text = "Your Opinions ?";

showPostDate = true;

summaryPost = 400;

summaryFontsize = 10;

summaryColor = "#666";

icon2 = " ";

numposts = 45;

home_page = "http://coderzheaven.com/";

limitspy=4
intervalspy=4000

</script>

<div id="spylist">
    <script src="http://infution.byethost22.com/recentpostthumb.js" type="text/javascript"></script>
</div>

5. Done!

Note : Replace your blogger url in the “http://coderzheaven.com/” part! You can also change different parameters like number of random posts, font size, color etc.

Select an Image from gallery in ANDROID and show it in an ImageView.

Hi all
In this tutorial I will show you how to get an image from your phone gallery and show it in an imageview.
Here we use intents to open up the image gallery and get the image URI.
Here I am setting the image type as “image” to get only the images.
And on onActivityResult if the result is OK, then get the data using getData() function and converting the imageURI to the stringPath.
Then show the image in the imageview using setImageURI.

package pack.GetImage;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class GetImageActivity extends Activity {

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;

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

	    img = (ImageView)findViewById(R.id.ImageView01);

	    ((Button) findViewById(R.id.Button01))
	            .setOnClickListener(new OnClickListener() {
	                public void onClick(View arg0) {
	                    Intent intent = new Intent();
	                    intent.setType("image/*");
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	                }
	            });
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            System.out.println("Image Path : " + selectedImagePath);
	            img.setImageURI(selectedImageUri);
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
}

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"
    />
<Button android:text="Browse gallery"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/ImageView01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</ImageView>
</LinearLayout>

Please leave your valuable comments if you found this post useful.

Using of CCWaves in iPhone

CCWaves is one of the interesting functionalities in Cocos2D iphone.
Check out this following snippet to see how it works.

id my_wavesAction = [CCWaves actionWithWaves:7 amplitude:25 horizontal:NO
                                                               vertical:YES grid:ccg(15,10) duration:10];
[my_sprite runAction: [CCRepeatForever actionWithAction:my_wavesAction n]];

Please leave your valuable comments on this post………………….

JComboBox in Java swing

This shows you how to add JcomboBox to JPanel

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Example implements WindowListener
{
  JFrame content_frame = new JFrame();
  JPanel panel = new JPanel();
  JComboBox Combonote;
  public Example()
  {
  	    content_frame.setTitle("Contents");
		content_frame.addWindowListener(this);
		content_frame.setSize(300, 300);
		content_frame.setVisible(true);
		content_frame.setLocationRelativeTo(null);
		content_frame.setResizable(false);    ///cannot maximize
		content_frame.setVisible(true);

		showComboBox();
  }
  private void showComboBox()
  {
	  String test[]= {"[select Exercise...]","Exercise1","Exercise2","Exercise3","Exercise4","Exercise5"};
	  panel.setBackground(Color.lightGray);
	  panel.setVisible(true);
	  Combonote = new JComboBox(test);
	  Combonote.setBounds(250, 240, 250, 30);
	  panel.add(Combonote);

	  panel.setBounds(250, 240, 250, 30);
	  content_frame.getContentPane().add(panel);
	  Combonote .addItemListener(new ItemListener()
	  {
	  	  public void itemStateChanged(ItemEvent ie)
	      {
	      	  if(ie.getStateChange() == ie.SELECTED)
	      	  {
	      		    if(Combonote.getSelectedItem().equals("Exercise1"))
	  		  		{
	                                          //code...
	                }
	          }
	      }
	  });
  }

  public static void main(String[] args)
  {
    new Example();
  }

@Override
public void windowActivated(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowClosed(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowOpened(WindowEvent arg0) {
	// TODO Auto-generated method stub

}
}


How to scroll a UIScrollView programatically ?

Hi,

If you want to scroll a UIScrollView programatically as the result of any IBOutlet actions, use the following code in that particular action.

[yourScroller setContentOffset:CGPointMake(0,250) animated:YES];

This will scroll your scroller named ‘yourScroller’ automatically to the point specified! :)

How to change the background color of a Layer in Cocos2D using CCColorLayer?

Set background color to magenta.

CCColorLayer* colorLayer = [CCColorLayer layerWithColor:ccc4(255, 0, 255, 255)];
[self addChild:colorLayer z:0];

//Changing the color of a sprite....

((CCSprite*)node).color = ccRED; // This will change the sprite color to RED.

How to get Device Orientation in Cocos2D, iPhone in Objective C?

Hello all……
We may need to know that what is your current device orientation.
Using the below code you can do this.

if([[UIDevice currentDevice] orientation] == kCCDeviceOrientationPortrait) {
            NSLog(@"Device is now in Portrait Mode");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeLeft) {
            NSLog(@"Device is now in LandscapeLeft Mode ");
}
else if ([[UIDevice currentDevice] orientation] == kCCDeviceOrientationLandscapeRight) {
            NSLog(@"Device is now in LandscapeRight Mode");
}
else if([[UIDevice currentDevice]orientation] ==
  kCCDeviceOrientationPortraitUpsideDown) {
            NSLog(@"Device is now in PortraitUpsideDown Mode");
ss="Apple-style-span" style="font-weight: normal;">
}

Note: If you have to explicitly set the orientation of your phone to any of the above you can set this in the appDelegate.m file. You can put an “||” (OR) symbol in between to set more than one.

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

How to inherit from other styles or how to extend your own styles in android?

Hello all….
I have covered many tutorials on styles on how to implement and use them.
Today I will show you how to inherit from other styles or how to extend a style already created by you and use it for applying to other views.

Here is one of my previous posts.
http://www.coderzheaven.com/2012/02/03/changing-the-style-or-theme-of-default-alertdialog-in-android/
Another one is here..
http://www.coderzheaven.com/2011/06/19/styling-text-in-android-through-xml/

OK We will start now.

First I will show you my main.xml
It contains only one simple 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"
    >

<TextView    
	 android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Hello World, Coderzheaven"
 />
   
</LinearLayout>

OK now we are going to apply a style to the textview, for that I am creating a file named “styles.xml” inside the values folder.
And inside the styles.xml copy this code.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="RedLabel">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:typeface">monospace</item>
		<item name="android:background">#F00</item>
		<item name="android:textColor">#FFF</item>
	</style>
</resources>
1


Now we will apply this style to the textview like this -> by providing it as style to the textview in the xml.
1
<TextView    
	 android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Hello World, Coderzheaven"
     style="@style/RedLabel"
     />

Now we will create another style and name it ButtonStyle aand apply it to a button. But the main thing is that this new style is inherited from the style we previously created. i.e the first style will be the parent of the second thus extending the first one. Our styles.xml will look like this now.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="RedLabel">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:typeface">monospace</item>
		<item name="android:background">#F00</item>
		<item name="android:textColor">#FFF</item>
	</style>
	
 	<style name="ButtonStyle" parent="RedLabel">
		<item name="android:layout_width">wrap_content</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:textSize">15px</item>
		<item name="android:typeface">serif</item>
	</style>

</resources>

Now we will apply this style to a button inside the main.xml(Do this after placing a button control inside main.xml)

Our new main.xml will now 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="Hello World, Coderzheaven"
     style="@style/RedLabel"
     />
 
 <Button    
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="This is a button"
     style="@style/ButtonStyle"
 />   
</LinearLayout>

i.e. We can extend this second style and soon. That’s the power of styles in xml.

This the main java file. Actually we don’t need this .

package com.coderzheaven.pack;

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

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

Please leave your valuable comments on this post so that I can improve it.

How to animate a series of images in iphone? A simple Example.

The following code shows animation of 5 images.

-(void)viewDidLoad
{
	NSArray *images = [NSArray arrayWithObjects:
	[UIImage imageNamed:@”pic1.jpeg”],
	[UIImage imageNamed:@”pic2.jpeg”],
	[UIImage imageNamed:@”pic3.jpg”],
	[UIImage imageNamed:@”pic4.jpeg”],
	[UIImage imageNamed:@”pic5.jpeg”],
	nil];
	CGRect frame = CGRectMake(0,0,320,460);
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
	imageView.animationImages = images;
	imageView.contentMode = UIViewContentModeScaleAspectFit;
	imageView.animationDuration = 3;
	imageView.animationRepeatCount = 0;
	[imageView startAnimating];
	[self.view addSubview:imageView];
	[imageView release];
	[super viewDidLoad];
}

How to add sprite to a body in Box2D in Adobe AIR, FLEX and FLASH? Or Add image/Sprite to a body in ActionScript.

The below code is for FlashBuilder 4, If you are using FlexBuilder3 use addChild()
instead of the commented block in the following code.

public function addCircle(){x:Number, y: Number, radius:Number, ballcip:Ball):void{

bd:b2BodyDef = new b2BodyDef();

      var loader:Loader = new Loader();

      loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
                                                           imageFailed);
      var request:URLRequest = new URLRequest("ball.png");
      loader.load(request);

      /*optionally change the position of the image if not fitting in the body */
      /* You can also rotate the image.*/
      loader.x = -50;
      loader.y = -50;

      /***************************************/
      var ui:UIComponent = new UIComponent();
      ui.addChild(loader);
      this.addElement(ui);
      /**************************************/

      bd.userData = ui;
      bd.position.Set(_x/m_phys_scale, _y/ m_phys_scale);
      bd.type=b2Body.b2_dynamicBody;
      var ball_shape:b2CircleShape=new b2CircleShape(50/world_scale);
      var ball_fixture:b2FixtureDef = new b2FixtureDef();
      ball_fixture.shape=ball_shape;
      ball_fixture.friction=0.9;
      ball_fixture.density=30;
      ball_fixture.restitution=0.3;
      ball_body=world.CreateBody(bd);
      ball_body.CreateFixture(ball_fixture);
}

private function imageFailed(event:IOErrorEvent):void
{
      Alert.show("Image loading failed"); //make sure you have the image.
}

Simulate a Balloon in Box2D, iPhone or ANDROID

Hello………
Sometimes you may want your body to act against the gravity of the world.
One method to do this is described below.
First what you have to do is to make a body in the shape of a circle and give it the image of a balloon as the userdata.

Then in the tick function write this code.
This method of applying the force is called “The antagonist forces method”
By this method we are giving an upward force to only our balloon body irrespective of the gravitational force.
After running the code you will see your body floating in air like a balloon.

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
   {
        if (b->GetUserData() != NULL) {
               if (b==baloonBody) {
                         b->ApplyForce( b2Vec2(0.0,9.8*b->GetMass()),b->GetWorldCenter()); // here 0.0 is x, 9.8 is y (the gravity)
               }
         }
   }

Note: Try to change the value 9.8 to higher if you have given your world’s gravity as 9.8. It will produce a balloon effect.
Please leave your comments if this post was useful……….

Date and TimePicker in ANDROID.

The following code simply allows you to select a date and time using the datepicker and timepicker in ANDROID.

package AndroidDatePicker.pack;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class AndroidDatePicker extends Activity {

 private int myYear, myMonth, myDay, myHour, myMinute;
 static final int ID_DATEPICKER = 0;
 static final int ID_TIMEPICKER = 1;

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

        Button datePickerButton = (Button)findViewById(R.id.datepickerbutton);
        Button timePickerButton = (Button)findViewById(R.id.timepickerbutton);
        datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
        timePickerButton.setOnClickListener(timePickerButtonOnClickListener);
    }

    private Button.OnClickListener datePickerButtonOnClickListener
     = new Button.OnClickListener(){

   @Override
   public void onClick(View v) {

          final Calendar c = Calendar.getInstance();
          myYear = c.get(Calendar.YEAR);
          myMonth = c.get(Calendar.MONTH);
          myDay = c.get(Calendar.DAY_OF_MONTH);
          showDialog(ID_DATEPICKER);
   }
    };

    private Button.OnClickListener timePickerButtonOnClickListener
  = new Button.OnClickListener(){

   @Override
   public void onClick(View v) {

          final Calendar c = Calendar.getInstance();
          myHour = c.get(Calendar.HOUR_OF_DAY);
          myMinute = c.get(Calendar.MINUTE);
          showDialog(ID_TIMEPICKER);
   }
    };

	 @Override
	 protected Dialog onCreateDialog(int id) {

	        switch(id){
	         case ID_DATEPICKER:
	          Toast.makeText(AndroidDatePicker.this,
	            "- onCreateDialog(ID_DATEPICKER) -",
	            Toast.LENGTH_LONG).show();
	          return new DatePickerDialog(this,
	            myDateSetListener,
	            myYear, myMonth, myDay);
	         case ID_TIMEPICKER:
	          Toast.makeText(AndroidDatePicker.this,
	            "- onCreateDialog(ID_TIMEPICKER) -",
	            Toast.LENGTH_LONG).show();
	          return new TimePickerDialog(this,
	            myTimeSetListener,
	            myHour, myMinute, false);
	         default:
	          return null;

	  }
	 }

	 private DatePickerDialog.OnDateSetListener myDateSetListener
	        = new DatePickerDialog.OnDateSetListener(){

	         @Override
	         public void onDateSet(DatePicker view, int year,
	           int monthOfYear, int dayOfMonth) {
	          String date = "Year: " + String.valueOf(year) + "n"
	           + "Month: " + String.valueOf(monthOfYear+1) + "n"
	           + "Day: " + String.valueOf(dayOfMonth);
	          Toast.makeText(AndroidDatePicker.this, date,
	            Toast.LENGTH_LONG).show();
	         }
	 };

	 private TimePickerDialog.OnTimeSetListener myTimeSetListener
	        = new TimePickerDialog.OnTimeSetListener(){
	         @Override
	         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

	          String time = "Hour: " + String.valueOf(hourOfDay) + "n"
	           + "Minute: " + String.valueOf(minute);
	          Toast.makeText(AndroidDatePicker.this, time,
	            Toast.LENGTH_LONG).show();
	         }
	 };
}

Saving Key-Value pair in Windows Phone using IsolatedStorageSettings

This sample code helps you to save a key and a corresponding value in windows Phone inside your application sandbox with the help of isolatedStorageSettings.

PLease check this post before working around this post.

How to save a text file in Windows Phone 7 or How to use isolated storage settings in Windows Phone 7?

Here is the C# code for this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;

namespace IsolatedStorageSettingsDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
            iss.Add("site", "coderzheaven.com");
            iss.Save();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;
            string data = "";

            try
            {
                iss.TryGetValue("site", out data);
                MessageBox.Show(data);
            }
            catch (Exception e1)
            {

            }
        }


    }
}

The stored value will be stored in a MessageBox.
Please leave your valuable comments on this post.

Sprite Animations Without Sprite Sheets

You can simulate any animations if you have a sequence of images which makes the illusion of that
animations and rendering those images to the screen. In cocos2D it can be done in two ways, with sprite sheet
animation and without sprite sheets. Here we are going to see how it can be done with out sprite sheet.


CCAnimation *sitDown = [CCAnimation animationWithName:@"sitDown" delay:0.1f];

[sitDown addFrameWithFilename:@"sit1.png"];
[sitDown addFrameWithFilename:@"sit2.png"];

[mySprite addAnimation:sitDown];

id sitAction = [CCAnimate actionWithAnimation:sitDown restoreOriginalFrame:YES];

[yourSprite runAction:sitAction];

Here CCAnimation holds a series of images known as Frames and CCAnimate is simply the action which will run the
CCAnimation. Simple.

Suppose that we have two images named, sit1.png and sit2.png which simulates a sitting animation of our sprite. First
we have added that images/frames to our CCAnimation object sitDown. Then we CCAnimate our CCAnimation frames and
deploy those actions to our sprite. We can set the delay time between the individual frames in CCAnimation. Also we can restore the original image before sprite animation after animatin completes or not!That’s it.

We will later see in here how Sprite Animations can be done by using Sprite Sheets. Keep in touch.

:)

How to use CCProgressTimer in Cocos2D to show progress?

The progress timer takes a
sprite and, based on a percentage, displays only a part of it to visualize some kind of
progress in your game.

CCProgressTimer* timer = [CCProgressTimer progressWithFile:@"progress.png"];
timer.type = kCCProgressTimerTypeRadialCCW;
timer.percentage = 0;
[self addChild:timer z:1 tag: my_tag];
// The update is needed for the progress timer.
[self scheduleUpdate];

You can choose between radial, vertical, and horizontal progress timers. But the timer doesn’t update itself. You have to change the timer’s percentage value frequently to update the progress.

Switch Images in ANDROID.

Hi all ……..

Ofter we have trouble with loading continous images in ANDROID from our application directory.
The reason is that all resources have a unique resource ID which we need to get to load these resources.
The following example shows how to get these unique identifier from the “path” of the resource.
For example Here I have seven images with names sample_0.png, sample_1.png to sample_7.png.
By using
imgID = getResources().getIdentifier(“sample_”+num, “drawable”, “com.switchImages”);
I convert the path to it’s identifier.
Note that all these images need to be in “drawable” folder.
Even if your folder name is “drawable-hdpi” also then give only “drawable” and third parameter the package name.Just copy and paste the following code to your java file.
Make sure that you have all the images in the resource.

package com.switchImages;

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

public class Switch extends Activity {
    ImageView img;
    Button preview;
    int num = 0;
    public int imgID = 0;

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

        img = (ImageView)findViewById(R.id.imageView);
        preview = (Button)findViewById(R.id.Prev);

        try
             {
                 imgID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
                         img.setImageResource(imgID);
             }catch(Exception e){
                        Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();
             }

             preview.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                                 imgID = getID();
                                                switchImage(imgID);
                                    }
                        });
    }

    public void switchImage(int ID){
             try
                         {
                                     ID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
                                     img.setImageResource(ID);
                         }catch(Exception e){
                                    Toast.makeText(Switch.this,e.getMessage() , Toast.LENGTH_SHORT).show();
                         }
    }

    public int getID(){
             int imgID = 0;
             num++;
             if(num > 7) num = 0;
             try
             {
                        imgID = getResources().getIdentifier("sample_"+num, "drawable", "com.switchImages");
             }catch(Exception e){
                        Toast.makeText(Switch.this,e.getMessage(), Toast.LENGTH_SHORT).show();
             }
             return imgID;
    }
}

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

How to scale a Flex window to any size?

This simple code scale your current window to max size of your screen.
Call this code where ever you want.

    stage.scaleMode= StageScaleMode.SHOW_ALL;

How to drag and drop a file from outside to your flex or AIR application and render it correctly?

Actually we have to do this by registering your application with the eventlisteners for NATIVE_DRAG_ENTER and NATIVE_DRAG_DROP.
The following code shows how to do this.
Just copy and paste the code to your MXML file and see the result.
Drag and drop an image file from outside to your AIR application.


        import mx.controls.Alert;
        import mx.controls.Image;
        import flash.filesystem.File;

        private function init():void{
               this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,onDragIn);
               this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,onDrop);
        }

        private function onDragIn(event:NativeDragEvent):void{
          NativeDragManager.acceptDragDrop(this);
        }

        private function onDrop(event:NativeDragEvent):void{
          var dropfiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
          for each (var file:File in dropfiles){
            switch (file.extension.toLowerCase()){
              case "png" :
                addImage(file.nativePath);
                    break;
              case "jpg" :
                addImage(file.nativePath);
                break;
              case "jpeg" :
                addImage(file.nativePath);
                break;
              case "gif" :
                addImage(file.nativePath);
                break;
              default:
                Alert.show("Unmapped Extension");
              }
            }
          }

          private function addImage(nativePath:String):void{
            var i:Image = new Image();
            if(Capabilities.os.search("Mac") >= 0){
              i.source = "file://" + nativePath;
            } else {
              i.source = nativePath;
            }
            this.addChild(i);
          }
        ]]>

How to lock the screen in an Android ?

 KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
 KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
 lock.disableKeyguard();

Note:you need to give permissions for it.