Tag Archives: java

java

How to draw Arcs in Android using canvas?

This is a simple example showing how to draw Arcs in android, You can use this to create piecharts or someother similar thing you want.

Arc Drawing

Arc Drawing

Arc Drawing

Arc Drawing

Here we have 3 classes.
1. GraphicsActivity.java
2. MainActivity.java
3. PictureLayout.java

GraphicsActivity.java

package com.coderzheaven.arcdrawing;

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

class GraphicsActivity extends Activity {
    // set to true to test Picture
    private static final boolean TEST_PICTURE = false;

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

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}

PictureLayout.java

package com.coderzheaven.arcdrawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

    public PictureLayout(Context context) {
        super(context);
    }

    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() > 1) {
            throw new IllegalStateException("PictureLayout can host only one direct child");
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth()/2;
        int y = getHeight()/2;

        if (false) {
            canvas.drawPicture(mPicture);
        } else {
            drawPict(canvas, 0, 0, x, y,  1,  1);
            drawPict(canvas, x, 0, x, y, -1,  1);
            drawPict(canvas, 0, y, x, y,  1, -1);
            drawPict(canvas, x, y, x, y, -1, -1);
        }
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

MainActivity.java

package com.coderzheaven.arcdrawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends GraphicsActivity implements OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button b1 = (Button) findViewById(R.id.button1);
		Button b2 = (Button) findViewById(R.id.button2);
		Button b3 = (Button) findViewById(R.id.button3);
		b1.setOnClickListener(this);
		b2.setOnClickListener(this);
		b3.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		Style sytle = null;
		boolean use_centre = false;
		final LinearLayout r1 = (LinearLayout) findViewById(R.id.l1);
		if (MainActivity.this.findViewById(1) != null)
			r1.removeView(MainActivity.this.findViewById(1));
		switch (id) {
		case R.id.button1:
			use_centre = true;
			sytle = Paint.Style.FILL;
			break;
		case R.id.button2:
			use_centre = false;
			sytle = Paint.Style.STROKE;
			break;
		case R.id.button3:
			use_centre = true;
			sytle = Paint.Style.STROKE;
			break;
		default:
			break;

		}
		SampleView s = new SampleView(MainActivity.this);
		s.setId(1);
		s.startDraw(sytle, use_centre);
		r1.addView(s);
	}

	private static class SampleView extends View {
		private Paint mPaint;
		private Paint mFramePaint;
		private RectF mBigOval;
		private float mStart;
		private float mSweep;
		private boolean use_centre = false;
		private static final float SWEEP_INC = 0.5f;
		private static final float START_INC = 15;

		public SampleView(Context context) {
			super(context);
			mPaint = new Paint();
			mPaint.setAntiAlias(true);
			mPaint.setColor(0x880000FF);
			mPaint.setStrokeWidth(4);

			mBigOval = new RectF(40, 10, 280, 250);

			mFramePaint = new Paint();
			mFramePaint.setAntiAlias(true);
			mFramePaint.setStrokeWidth(4);
		}

		public void startDraw(Style style, boolean use_centre) {
			this.use_centre = use_centre;
			mPaint.setStyle(style);
			mFramePaint.setStyle(style);
		}

		private void drawArcs(Canvas canvas, RectF oval, boolean useCenter,
				Paint paint) {
			// canvas.drawRect(oval, mFramePaint);
			canvas.drawArc(oval, mStart, mSweep, useCenter, paint);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			canvas.drawColor(Color.WHITE);

			drawArcs(canvas, mBigOval, use_centre, mPaint);

			mSweep += SWEEP_INC;
			if (mSweep > 360) {
				mSweep -= 360;
				mStart += START_INC;
				if (mStart >= 360) {
					mStart -= 360;
				}
			}
			invalidate();
		}
	}
}

Download the complete source code from here.

How to crop an Image in Android?

This is a sample program that launches the camera and crop the captured image.

Check this link to another crop image example.

http://www.coderzheaven.com/2011/03/15/crop-an-image-in-android/

Crop an Image in Android

Crop an Image in Android

Crop an Image in Android

This is the layout xml.
activity_main.xml

<?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"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:text="@string/intro"
        android:textStyle="bold" />

    <Button
        android:id="@+id/capture_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/capture" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:contentDescription="@string/picture" />

</LinearLayout>

Now this is the Main Java File that implements the crop functionality.

Here we are using the “com.android.camera.action.CROP” Intent to crop the Image passing the captured Image URI to it.

package com.coderzheaven.cropimage;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
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;
import android.widget.Toast;

public class ShootAndCropActivity extends Activity implements OnClickListener {

	final int CAMERA_CAPTURE = 1;
	final int CROP_PIC = 2;
	private Uri picUri;

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

		Button captureBtn = (Button) findViewById(R.id.capture_btn);
		captureBtn.setOnClickListener(this);
	}

	public void onClick(View v) {
		if (v.getId() == R.id.capture_btn) {
			try {
				// use standard intent to capture an image
				Intent captureIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				// we will handle the returned data in onActivityResult
				startActivityForResult(captureIntent, CAMERA_CAPTURE);
			} catch (ActivityNotFoundException anfe) {
				Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == CAMERA_CAPTURE) {
				// get the Uri for the captured image
				picUri = data.getData();
				performCrop();
			}
			// user is returning from cropping the image
			else if (requestCode == CROP_PIC) {
				// get the returned data
				Bundle extras = data.getExtras();
				// get the cropped bitmap
				Bitmap thePic = extras.getParcelable("data");
				ImageView picView = (ImageView) findViewById(R.id.picture);
				picView.setImageBitmap(thePic);
			}
		}
	}

	/**
	 * this function does the crop operation.
	 */
	private void performCrop() {
		// take care of exceptions
		try {
			// call the standard crop action intent (the user device may not
			// support it)
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			// indicate image type and Uri
			cropIntent.setDataAndType(picUri, "image/*");
			// set crop properties
			cropIntent.putExtra("crop", "true");
			// indicate aspect of desired crop
			cropIntent.putExtra("aspectX", 2);
			cropIntent.putExtra("aspectY", 1);
			// indicate output X and Y
			cropIntent.putExtra("outputX", 256);
			cropIntent.putExtra("outputY", 256);
			// retrieve data on return
			cropIntent.putExtra("return-data", true);
			// start the activity - we handle returning in onActivityResult
			startActivityForResult(cropIntent, CROP_PIC);
		}
		// respond to users whose devices do not support the crop action
		catch (ActivityNotFoundException anfe) {
			Toast toast = Toast
					.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
			toast.show();
		}
	}
}

Download the complete source code for the above example from here.

How to load a spinner with values from SQlite Database in android?

Here is a simple example showing how to load a database values in a spinner in android.

Spinner from SQLite

OK we will start.

This is the layout for the spinner row.
spinner_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation     =      "vertical"
    android:id="@+id/tv"
    android:layout_margin="10dp">   
</TextView>

This is the layout for the interface.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:text="Load DB values into Spinner"
         >
    </TextView>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_below="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

</LinearLayout>

Now this is the MainActivity.java file that uses the spinner and the database.

package com.coderzheaven.loadspinnerfromdb;

import   java  .util  .ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {

	SQLiteDatabase mydb;
	private   static String DBNAME = "PERSONS.db";
	private static String TABLE = "MY_TABLE";

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

		createTable();
		insertIntoTable();

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

		Spinner My_spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner_row,
				my_array);
		My_spinner.setAdapter(my_Adapter);
	}

	// CREATE TABLE IF NOT EXISTS
	public void createTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("CREATE TABLE IF  NOT EXISTS " + TABLE
					+ " (ID INTEGER PRIMARY KEY, NAME TEXT, PLACE TEXT);");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error in creating table",
					Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION INSERTS DATA TO THE DATABASE
	public void insertIntoTable() {
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('CODERZHEAVEN','GREAT INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('ANTHONY','USA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SHUING','JAPAN')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('JAMES','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('SOORYA','INDIA')");
			mydb.execSQL("INSERT INTO " + TABLE
					+ "(NAME, PLACE) VALUES('MALIK','INDIA')");
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	// THIS FUNCTION SHOWS DATA FROM THE DATABASE
	public ArrayList<String> getTableValues() {

		ArrayList<String> my_array = new ArrayList<String>();
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
			System.out.println("COUNT : " + allrows.getCount());

			if (allrows.moveToFirst()) {
				do {

					String ID = allrows.getString(0);
					String NAME = allrows.getString(1);
					String PLACE = allrows.getString(2);
					my_array.add(NAME);

				} while (allrows.moveToNext());
			}
			allrows.close();
			mydb.close();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error encountered.",
					Toast.LENGTH_LONG);
		}
		return my_array;
	}

}

Join the Forum discussion on this post

Note : Please remove the “span” tags from the post when you copy it.

Download the complete source code for this example from here.

How to Get Contact Image in Android.

This simple example gets the image from contacts in android.

private void getContactsDetails() {

		Cursor phones = getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		while (phones.moveToNext()) {
			String Name = phones
					.getString(phones
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			String Number = phones
					.getString(phones
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			String image_uri = phones
					.getString(phones
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

			System.out.println("Contact1 : " + Name + ", Number " + Number
					+ ", image_uri " + image_uri);
 
			
			if (image_uri != null) {
			     image.setImageURI(Uri.parse(image_uri));
		        }
			

		}

Please leave your valuable comments.

How to create a Slide from Left animation while deleting a row from a ListView in Android?

Hello all……

I have written a lost of posts on Listviews. You can see that by just searching Listviews in my site. Today I will show you how to create a slide out animation while we delete a row from a ListView.

So this is the xml that contains the ListView. Let it be in the main.xml

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">
  
	<ListView android:layout_width="fill_parent" 
	  android:layout_height="fill_parent" 
	  android:id="@+id/mainListView">
	</ListView>
	
</LinearLayout>

Create another file inside the layout folder named “simplerow.xml”.

simplerow.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/rowTextView" 
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content"
 android:padding="10dp"
 android:textSize="16sp" >
</TextView>

OK our xml part is over. Now the java part.

This is the main java file that implements this xml.

“SimpleListViewActivity.java”

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListViewActivity extends Activity {
  
  private ListView mainListView ;
  private ArrayAdapter<String> listAdapter ;
   ArrayList<String> all_planets = 
       new ArrayList<String>(){      
           private static final long serialVersionUID = -1773393753338094625L;
           {
               add("Mercury ");
               add("Venus "); 
               add("Earth"); 
               add("Mars"); 
               add("Jupiter"); 
               add("Saturn"); 
               add("Uranus"); 
               add("Neptune"); 
               add("Pluto"); 
           }
   };
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    
  
    mainListView = (ListView) findViewById( R.id.mainListView );

    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, all_planets);

    mainListView.setAdapter( listAdapter );  
    
    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View rowView, int positon,long id) {
            Toast.makeText(rowView.getContext(), ""+positon, Toast.LENGTH_LONG).show();
            removeListItem(rowView,positon);
        }
    });
    
  }
  
  protected void removeListItem(View rowView, final int positon) {

      final Animation animation = AnimationUtils.loadAnimation(SimpleListViewActivity.this,android.R.anim.slide_out_right); 
      rowView.startAnimation(animation);
      Handler handle = new Handler();
      handle.postDelayed(new Runnable() {

		@Override
          public void run() {
        	  all_planets.remove(positon);
              listAdapter.notifyDataSetChanged();
              animation.cancel();
          }
      },1000);

  }

}

OK Done. Now run it and see the result.

Slide delete

Slide delete

Slide delete

Join the Forum discussion on this post

Download.

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

Using Tabbars in ANDROID, A Simple Example……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

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

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

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

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

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

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}
 

Now ThirdTab.java.

package com.coderzheaven;

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

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}
 

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tabbar.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
TabBar in ANDROID

TabBar in ANDROID Demo

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

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);
}
}

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.

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…..

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 check whether your service is running in android?

This example will test whether a service is running in android if you know it’s package name.
Run this sample of code to check this.

private boolean checkMyServiceRunningOrNot() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.your_Service".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

How to Upload Multiple files in one request along with other string parameters in android?

Hello everyone,

I have shown two methods to upload files in android.
In today’s tutorial I will show another simple method to upload files. With this method you can upload multiple files in one request + you can send your own string parameters with them.

Here is another method on working with uploading of images.
How to upload an image from Android device to server? – Method 4

These are the things to do after creating the project.
1. You have to include two libraries in the your project build path(Download these libraries from here apache-mime4j-0.6.jar and httpmime-4.0.1.jar).
2. Add these libraries to the project build path.
3. Here you can see the the other things you need to remember while connecting to a server.

Refer the image

Note : I am working here on the local system as server. So I have used the server domain name as 10.0.2.2. Please change this according to your need.

OK Now open your main java file and copy this code into it.

package pack.coderzheaven;

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadTest extends Activity {

	private static final int SELECT_FILE1 = 1;
	private static final int SELECT_FILE2 = 2;
	String selectedPath1 = "NONE";
	String selectedPath2 = "NONE";
	TextView tv, res;
	ProgressDialog progressDialog;
	Button b1,b2,b3;
	HttpEntity resEntity;

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

        tv = (TextView)findViewById(R.id.tv);
        res = (TextView)findViewById(R.id.res);
        tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
        b1 = (Button)findViewById(R.id.Button01);
        b2 = (Button)findViewById(R.id.Button02);
        b3 = (Button)findViewById(R.id.upload);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openGallery(SELECT_FILE1);
			}
		});
        b2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openGallery(SELECT_FILE2);
			}
		});
        b3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
					progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
		       		 Thread thread=new Thread(new Runnable(){
		           	        public void run(){
		           	       		doFileUpload();
		           	            runOnUiThread(new Runnable(){
		           	                public void run() {
		           	                    if(progressDialog.isShowing())
		           	                    	progressDialog.dismiss();
		           	                }
		           	            });
		           	        }
		   	        });
		   	        thread.start();
				}else{
	  	                	Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
				}
	        }
		});

    }

    public void openGallery(int req_code){

   	 	Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
   }

   public void onActivityResult(int requestCode, int resultCode, Intent data) {

	    if (resultCode == RESULT_OK) {
	    	Uri selectedImageUri = data.getData();
	        if (requestCode == SELECT_FILE1)
	        {
	            selectedPath1 = getPath(selectedImageUri);
	         	System.out.println("selectedPath1 : " + selectedPath1);
	        }
	        if (requestCode == SELECT_FILE2)
	        {
	            selectedPath2 = getPath(selectedImageUri);
	         	System.out.println("selectedPath2 : " + selectedPath2);
	        }
	        tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
	    }
	}

    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);
	}

    private void doFileUpload(){

    	File file1 = new File(selectedPath1);
    	File file2 = new File(selectedPath2);
        String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
        try
        {
        	 HttpClient client = new DefaultHttpClient();
             HttpPost post = new HttpPost(urlString);
	         FileBody bin1 = new FileBody(file1);
	         FileBody bin2 = new FileBody(file2);
	         MultipartEntity reqEntity = new MultipartEntity();
	         reqEntity.addPart("uploadedfile1", bin1);
	         reqEntity.addPart("uploadedfile2", bin2);
	         reqEntity.addPart("user", new StringBody("User"));
	         post.setEntity(reqEntity);
	         HttpResponse response = client.execute(post);
	         resEntity = response.getEntity();
	         final String response_str = EntityUtils.toString(resEntity);
	         if (resEntity != null) {
	             Log.i("RESPONSE",response_str);
	        	 runOnUiThread(new Runnable(){
	 	                public void run() {
	 	                	 try {
	 	                		res.setTextColor(Color.GREEN);
	 							res.setText("n Response from server : n " + response_str);
	 							Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
	 						} catch (Exception e) {
	 							e.printStackTrace();
	 						}
	 	                   }
	 	            });
	         }
        }
        catch (Exception ex){
             Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
      }
}

Now the layout for this file 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="Multiple File Upload from CoderzHeaven"
    />
<Button
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get First File">
</Button>
<Button
    android:id="@+id/Button02"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Second File">
</Button>
<Button
    android:id="@+id/upload"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Start Upload">
</Button>
<TextView
	android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Selected File path : "
    />

<TextView
	android:id="@+id/res"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text=""
   />
</LinearLayout>

Now the AndroidManifest file(Remember to add the permission for accessing internet)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">

      <uses-permission android:name="android.permission.INTERNET" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FileUploadTest"
                  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>

Now the server side(Here it is written in PHP)
upload_media_test.php file contents

<?php
$target_path1 = "uploads/";
$target_path2 = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploadedfile1']['name']);
if(move_uploaded_file($_FILES['uploadedfile1']['tmp_name'], $target_path1)) {
    echo "The first file ".  basename( $_FILES['uploadedfile1']['name']).
    " has been uploaded.";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile1']['name']);
    echo "target_path: " .$target_path1;
}

$target_path2 = $target_path2 . basename( $_FILES['uploadedfile2']['name']);
if(move_uploaded_file($_FILES['uploadedfile2']['tmp_name'], $target_path2)) {
    echo "n The second file ".  basename( $_FILES['uploadedfile2']['name']).
    " has been uploaded.";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile2']['name']);
    echo "target_path2: " .$target_path2;
}

$user = $_REQUEST['user'];
echo "n String Parameter send from client side : " . $user;
?>


Please leave your comments. If you like this post, please hit a “+1″ for this post and share it across your networks.

How to find if a string starts with a particular word – JAVA ?

Hi,

In order to find whether a given string starts with a particular string or not in JAVA, use the following code.


public class Main {

  public static void main(String[] args) {

    String urStr = "Coderz Heaven";

    if (urStr.startsWith("Coderz")) {

      System.out.println("Yes! Your string starts with Coderz");

    }

    else {

      System.out.println("No!");

    }

  }

}

Simple View Animation in ANDROID?

Hi all…..
In this post I will show you a simple animation using a textView.
It’s really simple.

Steps.

1. Create a fresh project and copy this java code into it.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.widget.Toast;

public class AnimationDemo extends Activity implements AnimationListener {

	View v;
	Boolean STOP = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void startAnimation(View view) {
		Animation animation = AnimationUtils.loadAnimation(this,R.anim.animation);
		animation.setAnimationListener(this);
		View animatedView = findViewById(R.id.textview);
		animatedView.startAnimation(animation);
	}

    public void stopAnimation(View view){
    	Toast.makeText(this, "Animation will stop after this loop.", Toast.LENGTH_SHORT).show();
    	STOP = true;
    }
	@Override
	public void onAnimationStart(Animation animation) {
		Toast.makeText(this, "Animation started", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		Toast.makeText(this, "Animation ended", Toast.LENGTH_SHORT).show();
		if(STOP == false)
			startAnimation(v);
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		Toast.makeText(this, "Animation rep", Toast.LENGTH_SHORT).show();
	}
}

2. Create a folder named “anim” inside the res folder and create a file named “animation.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
	android:shareInterpolator="true">
	<rotate android:fromDegrees="0" android:toDegrees="360"
		android:duration="10000" android:pivotX="50%" android:pivotY="50%"
		android:startOffset="10">
	</rotate>
</set>

3. copy this code to your “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"
    >

	<button
		android:id="@+id/Button01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Start Animation"
		android:onClick="startAnimation">
	</button>

	<button
		android:id="@+id/Button02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Stop Animation"
		android:onClick="stopAnimation">
	</button>

	<textView
		android:id="@+id/textview"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello" />

</linearLayout>

4. Clean your project and run it.

Click the start animation button will start the animation and stop button will stop the animation after one loop.
The code is self explanatory, so I am not going to explain the code.

ANDROID Animation example

ANDROID Animation example

Join the Forum discussion on this post

Applet FlowLayout Example

The FlowLayout class puts components in a row, sized at their preferred size.

Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. The hgap and vgap arguments specify the number of pixels to put between components.

import java.applet.*;
import java.awt.*;
/*
  <applet code="FlowLayoutApplet" width=300 height=200>
  </applet>
*/

public class test extends Applet
{

  public void init()
  {
    setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
    for (int i = 0; i < 20; i++)
    {
    	add(new Button("Button" + i));
    }
  }
}

The output window look like this

How to send email from and ANDROID Application programatically?

Hello all……..
In today’s post I will show you send mail from an android application progrmatically..
Let’s go to the code fast……
This is the code in the mail java file….

package com.coderzheaven;

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;
import android.widget.EditText;
import android.widget.Toast;

public class sendMailDemo extends Activity {
    Button send;
    EditText address, subject, emailbody;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        address = (EditText) findViewById(R.id.address);
        subject = (EditText) findViewById(R.id.subject);
        emailbody = (EditText) findViewById(R.id.body);
        send = (Button) findViewById(R.id.send);

        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	sendEmail();
            }
        });
    }

    public void sendEmail(){

    	if(!address.getText().toString().trim().equalsIgnoreCase("")){
    	  final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
	      emailIntent.setType("plain/text");
	      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ address.getText().toString()});
	      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
	      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailbody.getText());
	      sendMailDemo.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	    }
    	else{
    		Toast.makeText(getApplicationContext(), "Please enter an email address..", Toast.LENGTH_LONG).show();
    	}
      }
	}

Now the layout file (main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:background="@drawable/android"
	>
	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:id="@+id/emailaddress"
		android:text="Email Address"
		android:textStyle="bold">
	</TextView>

	<EditText
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:width="250dip"
		android:hint="email address"
		android:id="@+id/address">
	</EditText>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Subject"
		android:textStyle="bold">
	</TextView>

	<EditText
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:width="250dip"
		android:hint="Subject"
		android:id="@+id/subject">
	</EditText>

	<TextView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Your Message"
		android:textStyle="bold">
	</TextView>
	<EditText
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:lines="5"
		android:hint="Your message here!!"
		android:id="@+id/body">
	</EditText>
	<Button
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:id="@+id/send"
		android:text="Send Email"
		android:width="150dip">
	</Button>
</LinearLayout>

The AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="Send Mail Demo">
        <activity android:name=".sendMailDemo"
                  android:label="Send Mail Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Note: However if you test this in your emulator, it will not work. Install it in your device to test it.

ANDROID Tabbars Example……..

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

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

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

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

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

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

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}

Now ThirdTab.java.

package com.coderzheaven;

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

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Using Tabbars in ANDROID, A Simple illustration……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

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

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}

Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

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

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

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

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}
 

Now ThirdTab.java.

package com.coderzheaven;

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

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}
 

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tabbar.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Using Tabbars in ANDROID, A Simple Example……….

This is a simple example showing how to use tabbars in ANDROID.
First create a new project and copy this code to it.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

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

        /** TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

    }
}


Now create three another java files by right clicking the src folder and name it FirstTab.java, SecondTab.java, ThirdTab.java.

Now copy the following code to FirstTab.java.

package com.coderzheaven;

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

public class FirstTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* First Tab Content */
		TextView textView = new TextView(this);
		textView.setText("First Tab");
		setContentView(textView);
	}
}

SecondTab.java

package com.coderzheaven;

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

public class SecondTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Second Tab");
		setContentView(textView);

	}
}

Now ThirdTab.java.

package com.coderzheaven;

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

public class ThirdTab extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/* Second Tab Content */
		TextView textView = new TextView(this);
		textView.setText("Third Tab");
		setContentView(textView);

	}
}

Main.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:layout_width="fill_parent"
	android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost">
	<LinearLayout android:id="@+id/LinearLayout01"
		android:orientation="vertical" android:layout_height="fill_parent"
		android:layout_width="fill_parent">
		<TabWidget android:id="@android:id/tabs"
			android:layout_height="wrap_content" android:layout_width="fill_parent"></TabWidget>
		<FrameLayout android:id="@android:id/tabcontent"
			android:layout_height="fill_parent" android:layout_width="fill_parent"></FrameLayout>
	</LinearLayout>
</TabHost>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tabbar.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".FirstTab" />
	<activity android:name=".SecondTab" />
    <activity android:name=".ThirdTab" />
        <activity android:name=".tabbar"
                  android:label="TabBar Demo">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
TabBar in ANDROID

TabBar in ANDROID Demo

You can place anything in each tab by setting the contentView or dynamically adding controls.
You can do anything with this tabbar by editing the xml, like placing it below or giving images for each tab etc etc….

Please leave your valuable comments…

Listening incoming sms message in Android

When a new sms message is received by the device, a Broadcast Receiver is registered. For this

IntentFilter filter = new IntentFilter(SMS_RECEIVED);
registerReceiver(receiver_SMS, filter);

should be included . Also sms are sent in PDU’s(Protocol Description Units) format, which act as an encapsulation.
Inorder to extract from PDU to byte array

messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

method is used.
When sms comes, the BroadCast listener is activated and sms sender number is showed in a ListView

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class smsReceiver extends Activity
{
    /** Called when the activity is first created. */
	 public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
	 ListView list;
	 ArrayList<String> messageList;
	 ArrayAdapter< String> adapter;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        list = (ListView) findViewById(R.id.listView1);

        messageList  = new ArrayList<String>();
        //messageList.add("check");
       adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messageList);
       list.setAdapter(adapter);

        IntentFilter filter = new IntentFilter(SMS_RECEIVED);
        registerReceiver(receiver_SMS, filter);
    }
    BroadcastReceiver receiver_SMS = new BroadcastReceiver()
    {
		public void onReceive(Context context, Intent intent)
		{
			 if (intent.getAction().equals(SMS_RECEIVED))
			 {
			        Bundle bundle = intent.getExtras();
			        if (bundle != null)
			        {
			          Object[] pdus = (Object[]) bundle.get("pdus");
			          SmsMessage[] messages = new SmsMessage[pdus.length];

			          for (int i = 0; i < pdus.length; i++)
			            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

			          for (SmsMessage message : messages)
			          {
			            	 Toast.makeText(smsReceiver.this, "----"+message.getDisplayMessageBody(), Toast.LENGTH_LONG).show();
			            	 receivedMessage(message.getDisplayOriginatingAddress());
			          }
			        }
			      }
		}
	};
	private void receivedMessage(String message)
	{
		messageList.add(message);
		adapter.notifyDataSetChanged();
	}
}

The xml hold a 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:layout_height="fill_parent"
	android:id="@+id/listView1"
	android:layout_width="fill_parent"/>
</LinearLayout>

Also important part is that, for an application to listen an SMS Intent Broadcast should be added

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

This post explains How to get the SMS sent to your emulator within your application