How to create a new Virtual SD card in emulator in ANDROID? How to start emulator with the created SDCard?

OK

The first question is
1. How to create a new Virtual SD card in emulator in ANDROID?

Many times we may have not enough memory for our application to run on the emulator.
So what we do?
One method is to create new virtual device with more memory.
Another method is to extend the device’s internal memory.
Third method is to create an SD card for the emulator.

Here is how you create a new SD card for the emulator.
First you have to navigate to you android installation directory and go to tools from there execute this command

C:androidtools>mksdcard -l mySdCard 1024M mySdCardFile.img

A file image named “mySdCardFile” will be created with about 1024 MB memory or you can give it in KB also.

Now SDCard created.Check your C:androidtools directory and confirm that the image has been created.

SDcard

SDcard created

2. How to start emulator with the created SDCard?

Try this in the command prompt
Note: Make sure your emulator(Here VD1.6 created by me) is not running.

C:androidtools>emulator -avd VD1.6 -sdcard mySdCardFile.img

Now go to Eclipse Open DDMS on the right top of the window and open the File-Explorer from the Window-Menu

There you will see the SDcard

No image

SDcard in ANDROID

If you are not starting the emulator with the sdcard you will not see the sdcard here.

You can find more options on emulator here
http://developer.android.com/guide/developing/tools/emulator.html

How to create a scrolling ListView in android?

ListView is like a tableView in iPhone or iOS . In this example i will show you how to add a String Array in to the ListView and also make the listView Scrollable.

First the xml file . Here the line

android:scrollbars=”vertical”

will make the scrolling vertically

<?xml version="1.0" encoding="utf-8"?>
<relativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
	<listView
			android:id="@+id/listview"
			android:scrollbars="vertical"
			android:layout_width="fill_parent"
			android:layout_height="200dip"
			android:layout_gravity="fill_vertical"
			android:layout_alignParentTop="true"
			>
		</listView>

</relativeLayout>

Now the java file

package com.Ch.Example.pack;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Example extends Activity
{
    /** Called when the activity is first created. */
	ListView list;
	private List<string> List_file;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List_file =new ArrayList<string>();
        list = (ListView)findViewById(R.id.listview);

        CreateListView();
    }
	private void CreateListView()
	{
		 List_file.add("Coderzheaven");
		 List_file.add("Google");
		 List_file.add("Android");
		 List_file.add("iPhone");
		 List_file.add("Apple");
		 //Create an adapter for the listView and add the ArrayList to the adapter.
		 list.setAdapter(new ArrayAdapter<string>(Example.this, android.R.layout.simple_list_item_1,List_file));
		 list.setOnItemClickListener(new OnItemClickListener()
		   {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
				{
					//args2 is the listViews Selected index
				}
		   });
	}
}

The screen will be like this

Here is a other useful posts related to listviews.

1. ListView with Sections in android.
2. A Simple Layout with two listViews.

How to read a folder in the assets directory and read files from it in android?

File reading is important in android. For the put the files in the assets folder.

We can able to read

  • foldername
  • filename
  • Contents of the file

First we read the name of the folder.

private String folder_array[];
AssetManager mngr_spinner = getAssets();
try
{
         //"air" is the name of the folder...
	folder_array= mngr_spinner.list("air");
}
catch (IOException e1)
{
	e1.printStackTrace();
}

“folder_array” contains all the names of the folder
Then if the path is set to

folder_array= mngr_spinner.list("air/Buttons Events");

Then the list of file name is got.
If you want to read the file content then do the following..

InputStream is;
try
{
	is = getAssets().open(air/Buttons Events/filename);
	int siz = is.available();
	byte[] buffer = new byte[siz];
	is.read(buffer);
        //This text contains the content of the file..
	String text = new String(buffer);
        is.close();
}
catch (Exception e)
{
	 Toast.makeText(CheatSheet.this,"File Not Found Error.Please ensure that file is not deleted.", Toast.LENGTH_SHORT).show();
}

How to prevent collision between connected bodies in Box2D ?

Hi,

While using Box2D , in many cases you may need to connect two bodies together. But the collision between them during motion is not what you preferred! So how can you prevent those bodies being connected in Box2D from collision?
Use the line of code to prevent the collision.

jointDef.collideConnected = false;

Copying a Sprite Image to another Sprite in Cocos2D

Hi,

Suppose you want to copy a sprite image to another new sprite while using cocos2D. What you do?
See the following code…

Let oldSprite be your first sprite

CCSprite *oldSprite = [CCSprite spriteWithFile:@"ImgOne.png"];

And newSprite be your second sprite

CCSprite *newSprite  = [CCSprite spriteWithTexture:[oldSprite texture]];

That’s it! Done! Now newSprite too contain ImgOne as Sprite.

:)

Playing sound on the Mac Desktop in Objective C.

There are different ways for playing sound on the Mac in Objective C.

Let’s look at some of the methods..
1. Play by filename.

           NSSound *mySound = [NSSound soundNamed:@"sound"];

if you have no file named “sound” in your application’s main bundle, then it will return nil.

2. Play by pathName

           sound = [[NSSound alloc] initWithContentsOfFile:@"/Volumes/Audio/sound.aiff"
           byReference:YES];

3. Play by URL

        NSURL *soundURL = [NSURL
        fileURLWithString:@"file://~/soundfiles/sound.aiff"];
        NSSound *sound = [[NSSound alloc] initWithContentsOfURL:soundURL

byReference:NO];
Then to play the sound add

         if (![sound isPlaying])
                [sound play];

To pause the sound

               [sound pause];

To stop the sound.

              [sound stop];

To resume the sound

             [sound resume];

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

Delete a substring in Objective C, Iphone , Mac………….

This code snippet deletes a substring from a original string..

/** initialize two strings **/
NSString *string = @"This is heaven";
NSString *part = @"heaven";

/** Get the range of the substring in the original string **/
NSRange range = [string rangeOfString:part];

/** Delete the substring from the original string **/
[string deleteCharactersInRange:range];

Please leave your valuable comments………

ToolTip Sound in Adobe AIR/FLEX…

Sometimes we may need to have a sound when we hover over something, i.e when a tooltip appears.
Actually this can be done easily by adding an eventListener to the corresponding control.
Take a look at the example.
This line is the important line.

      myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);

The function myListener gets called when we hover over the label thus producing the sound.
What you have to do is to just copy and paste the following code to your file.

       import mx.events.ToolTipEvent;
     import flash.media.Sound;

     [Embed(source="msgAlert.mp3")]

     private var myToolTipSound:Class;
     private var mySound:Sound;

     private function init():void {
        myLabel.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, myListener);
        mySound = new myToolTipSound();
     }
      public function playSound():void {
        mySound.play();
     }
     private function myListener(event:ToolTipEvent):void {
        playSound();
     }
  ]]>
   

Encapsulation Using Properties in C#.NET / ASP.NET

Hi,

Let’s see how encapsulation can be implemented using properties in C#.NET/ASP.NET.
Let’s see the code first.

using System;

public class Student
{
    private int stud_id = -1;

    public int ID
    {
        get
        {
            return stud_id;
        }
        set
        {
            stud_id = value;
        }
    }

    private string stud_name = string.Empty;

    public string Name
    {
        get
        {
            return stud_name;
        }
        set
        {
            stud_name = value;
        }
    }
}

public class StudentManagerWithProperties
{
    public static void Main()
    {
        Student studObj = new Student();

        studObj.ID = 7;
        studObj.Name = "Aamir Khan";

	Console.WriteLine(
            "ID: {0}, Name: {1}",
            studObj.ID,
            studObj .Name);

        Console.ReadKey();
    }
}

Ok. Here Student class has two properties ID & NAME. Also two private variables or fields stud_name & stud_id, both are encapsulated by our ID & NAME properties. And also two accessors for setting and getting values from fields. Set accessor set the value to the field. Note that the ‘value’ used here is the keyword! This value is assigned by calling function. StudentManagerWithProperties uses the ID & NAME properties as we can see.

:)

AlertView with textbox in iPhone, Objective C.

Often we see alerts with text message or title in it.
But actually we can customize alerts. We can place any views inside it.
We can place a textView(TextField) , imageView etc in it.
Take a look at this simple example that places a textbox inside an alertView.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title goes here!!"
                            message:@"My Message"
                            delegate:self cancelButtonTitle:
                            @"Cancel" otherButtonTitles:@"OK", nil];
UITextField *TF = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[TF setBackgroundColor:[UIColor ClearColor]];
[alert addSubview:TF];        /** adding the textfield to the alertView **/
[alert show];
[alert  release];

Please leave your valuable comments…..

Using GridView in ANDROID….

GridViews are those in which you can arrange elements in a two dimensional grid.
It is what you see in the gallery where images are arranged. Here images are arranged in a two dimensional grid.
Copy the below code and save it as “MyGridView.java”

package com.pack;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MyGridView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this));
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(MyGridView.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}

/********************************* End of MyGridView.java ****************************** **/

Now create another file named “Images.java” and copy the below code to it.

package com.pack;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
lass="Apple-style-span" style="font-family: Times, 'Times New Roman', serif;">import android.widget.ImageView;
public class Images extends BaseAdapter {
private Context ctxt;
public Images (Context c) {
ctxt = c;
}
public int getCount() {
return Ids.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int pos) {
return 0;
}
public View getView(int pos, View convertView, ViewGroup parent) {
ImageView imgView;
if (convertView == null) {
imgView = new ImageView(mContext);
imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
} else {
imgView = (ImageView) convertView;
}
imgView.setImageResource(Ids[pos]);
return imgView;
}
private Integer[] Ids = {
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7
};
}
/*********************************** End of Images.java**************************** **/

Note: Please make sure that you have images named img_0 to img_7 in your res/drawable folder.
Please leave your valuable comments if this post was useful…..

Android TableLayout

In android there are different layouts and we often confuse about which one to use. Even if we select one, it is little complicated.

So this tutorials is to show you about the TableLayout

Here i first created linear Layout in which a Table Layout is added

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TableLayout
		android:layout_width="wrap_content"
		android:id="@+id/table"
		android:layout_height="wrap_content">
	<TableRow>
		<EditText
			 android:text=""
			 android:id="@+id/name"
			 android:layout_column="0"
			 android:hint="name"
			 android:layout_width="wrap_content"
			 android:layout_height="wrap_content"
			 android:fadingEdge="vertical|horizontal"/>
	</TableRow>
	<TableRow>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Save"
			android:layout_column="0"
			android:id="@+id/OkButton"
			android:fadingEdge="horizontal">
		</Button>
		<Button android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="Cancel"
			android:layout_column="1"
			android:id="@+id/cancelButton"
			android:fadingEdge="horizontal">
		</Button>
	</TableRow>

	</TableLayout>
</LinearLayout>

Here you can see that the first row ie, the EditText length is limited to 1 column and so it is not looking good. So we can make the EditText span across two column by adding this line to EditText

android:layout_span="2"

Now we can position the TableLayout in the center of the screen by adding this to TableLayout

android:layout_gravity = "center_vertical"

Now we think of aligning this to center horizontal as

android:layout_gravity = "center_horizontal"

But this wont work. This is because of LinearLayout and here the positioning is restricted.
But their is solution “Relative Layout” and positioning is easy by using this layout.

I will cover this in my next Post

Alert Button with Image in Adobe AIR/FLEX…

We usually see only alerts with text only, but in Adobe AIR and FLEX we can have alerts with our images in it. That’s really cool right.
Take a look at this simple example. It places an image in the alert.
Make sure that you have the image named “alert_image.png” in your “src” folder or otherwise give the specific path.



 
        
        


No Image

How to Disable Right Click on HTML page using jQuery ?

Hi,

In some special cases you may need to disable the Right Click option on HTML page you are using.
An easy way to do it using jQuery is follows. Use the following code in the HTML page where you want to disable Right Click.

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

:)

Sorting ArrayList Elements Alphabetically in ASP.NET – Sort()

Hi,
In order to sort elements in ArrayList using ASP.NET we can use the Sort() method.
It will sort ArrayList Elements alphabetically.


This will sort the ArrayList elements alphabetically.

:)

How to play music in cocos2D or Box2D, iPhone?

This simple code plays a music……..


[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@”my_music.mp3″];

For stopping the music use this…….


[[SimpleAudioEngine sharedEngine]stopBackgroundMusic];

To pause the music use this line of code…..


[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];

How to make gear joint in Box2D, iPhone?

Gear joints are one of the real specialities of Box2D.

By creating gear joints between two bodies you can actually simulate a real world gear. For creating a gear joint you need two bodies connected by a revolute or prismatic joint.

The below code creates two bodies in the shape of a circle which is actually attached to the ground. however you can also create joints without joining it with the ground. Here you have to make a ground with possible four fixtures or no fixtures simply creating a body.


        b2Body* body1 = circle1;
        b2Vec2 pos1 = circle1 -> GetPosition();//get position of first body.....
        b2Body* body2 = circle2;
        b2Vec2 pos2 = circle2 -> GetPosition(); // get position of second body....
        revJointDef.Initialize(ground, circle1, pos1);
        b2RevoluteJointDef revJointDef2;
        revJointDef2.Initialize(ground, body2, pos2)//revolute joint is initialized
        joint1 = world->CreateJoint(&revJointDef;); //First joint.....
        revJointDef2.maxMotorTorque = 20000.000000f; //connect a motor to the joint2
        revJointDef2.motorSpeed = 120.000000f / 60; //set the rotation speed.....
        revJointDef2.enableMotor = true;            // enable the motor.....
        joint2 = world->CreateJoint(&revJointDef2;);  //Second joint.....

        gearJointDef.bodyA = body1;
        gearJointDef.bodyA = body2;
        gearJointDef.joint1 = joint1;
        gearJointDef.joint2 = joint2;
        gearJointDef.collideConnected = true;
        gearJointDef.ratio = circleShape2.m_radius/circleShape1.m_radius;
        world->CreateJoint(&gearJointDef;); // this line creates the joint.

Please leave your valuable comments……………………..

Swing JPanel with background image

This code add an image to Jpanel.

JPanel panel1 = new JPanel();
JFrame recursion_frame = new JFrame();

BackgroundPanel stack_image1 = new BackgroundPanel("Recursion.jpg");

panel1.setLayout(null);
panel1.setLayout(new BorderLayout());
panel1.setBackground(Color.lightGray);
panel1.setVisible(true);
recursion_frame.setContentPane(panel1);  ///adding to panel...
recursion_frame.getContentPane().add(stack_image1);  //adding image to panel...

Position swing window in center of the screen

In some case we need to position the window in the center of the screen . The same effect can be achieved by hard coding the center points .But in that case the window position change when the screen resolution changes

This code will position the window in center irrespective of different screen resolutions

public JFrame stack_frame = new JFrame();
stack_frame.setLocationRelativeTo(null);

What is Objective C Keyword id ?

Hi,

Objective C uses a special keyword ‘id’.
Let’s see what it is.
Objective C -id- is actually a ‘pointer to an object’. That is ‘id’ can hold a pointer to any objective c object. It doesn’t matter the object’s class.
eg:

NSString *myString = @"Coderz Heaven!";
id newString;
NSString *tempString;
newString=myString;
tempString=newString;

That’s it! It will work out with using ‘id’ keyword. Compiler simply thinks ‘you know what you are doing!’

A word of caution : Remember not to use * while creating id objects! Because that type already know it’s a pointer!

Read a plist from your resources folder in Iphone Objective C

Plist or property list are usually used for storing data in iPhone.
They are normal XML files, you can open it in a texteditor to view it’s data.
This sample code shows how to read data from the plist.
Reading a plist will return an array.You can print out the array to view the results.


     NSString *path= [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"];
     BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
     if(fileExists){
         NSMutableArray *arr = [[NSArray alloc]  initWithContentsOfFile: path];
         NSLog(@"Data from plist %@",arr);
     }else {
        NSLog(@"File Not Found");
        exit(1);  // if file not found exit the application.
    }

Please leave your valuable comments………