GridView example android

GridView is used to display items in a two-dimensional, scrollable grid form. The grid items are automatically inserted to the layout using a Adapter.

For example, displaying grid of icons. Item is represented by a single item view. This pattern is quite handy as it shows several icons on screen at the same time. Its helps displaying grids of data in a very simple and scrollable grid manner.

The simplest way to display a grid view is using ArrayAdapter class . You can add lists or arrays of custom objects to it and these objects are referenced using index and displayed in the TextView of GridView.

We set the ArrayAdapter to the GridView to display the items of array adapter in it .

The following example explains the usage of GridView using ArrayAdapter.

Step1: Create the xml for the activity which contains a GridView

main.xml

<RelativeLayout 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"
    tools:context=".AdapterActivity" >

    <GridView
        android:id="@+id/grid_id"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="80dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </GridView>

</RelativeLayout>

Step 2:  Create the Activity and use the code mentioned below.

  • Create the ArrayAdapter and add a default layout grid style and string array of data to it.
  • Set GridView adapter as the ArrayAdapter.
  • You can set listeners on your grid view also.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterActivity extends Activity {
    GridView gridView;

    static final String[] numbers = new String[] {
            "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine", "ten",
            "eleven", "twelve", "thirteen", "fourteen",
            "fifteen","sixteen","seventeen","eighteen",
            "nineteen","twenty","twenty one","twenty two"
            };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gridView = (GridView) findViewById(R.id.grid_id);
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, numbers);

        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
               Toast.makeText(getApplicationContext(),
                ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}

Screenshot:

gridview

You can also download the above GridView Example here.

Related Posts:

Custom Gridview Example 

Custom Listview Example 

Simple ListView Example

Canvas in android example

Canvas class along with SurfaceView class can be used to create a custom view easily for a game or a live wallpaper etc. So, if you want to make a custom view then let’s start learning how to use canvas.

Canvas class lets you create graphical effects .It provides the drawing methods to draw on a bitmap. It provides methods for drawing, e.g. drawARGB() for drawing a color, drawBitmap() to draw a Bitmap, drawText() to draw a text, drawRoundRect() to draw a rectangle with rounded corners etc .Here is a reference to all its methods.

The Paint class specifies how you draw on the bitmap.The Paint class allows specifying the color, font and certain effects for the drawing operation.

Step 1

Firstly we need a class that extends SurfaceView and implements SurfaceHolder.Callback.SurfaceViewprovides a dedicated drawing surface which can be set as the content view of any activity and Callbackwill allow you to be notified when the surface is created and destroyed, starting and stopping any current tasks.

 

public class Preview extends SurfaceView implements SurfaceHolder.Callback
{	private Context context;
private  PreviewThread thread;

publicPreview(Context context) {
	super(context);
this.context = context;
getHolder().addCallback(this);
thread = new PreviewThread(this);
//code	
}

getHolder().addCallback(this) lets us setup the Callback interface and use its functions.thread = new PreviewThread(this) creates the instance of thread class

Step 2:

In Preview class create the following functions:

// called from thread to draw on canvas
	public void onDraw(Canvas canvas) {
		
		this.canvas = canvas;
canvas.drawBitmap(bitmap,0,0),
//rest of images/shapes/text you want to draw on the canvas
		
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	//code
	}

	public void surfaceCreated(SurfaceHolder holder) {
		 //start the thread
		if (!thread.isAlive()) {
			thread = new PreviewThread(this);
		}

		thread.setRunning(true);
		thread.start();

	}

	public void surfaceDestroyed(SurfaceHolder holder) {

		//set the condition for stopping doDraw() calls from the thread 
thread.setRunning(false);// sets booleanvar false
		
			try {
				thread.join();// destroy
				
			} catch (InterruptedException e) {
				//to do code				

			}
		}
	}

onDraw() will draw all the images,shapes,,textetc on the canvas each time it is called from the thread at updated positions as set by the program for updating x and y positions .

surfaceChanged() notifies the change of surface,surfaceCreated() notifies creation of surface and surfaceDestroyed() notifies destruction of surface. Add required code in these functions aacordingto the  action you want to perform when these are called.

Step 3:

Create the PreviewThread calls that will extend Threadclass and calls the doDraw() of the Preview class.

classPreviewThread extends Thread {
		privatebooleanRunThread = false;
//constructor
PreviewThread(Context con)
{
 Context=con;
}

private Preview preview;
Context context;
	/*
	 *            Should the loop keep running?
	 */
	public void setRunning(boolean run) {
		mRunThread = run;

	}



/**
	 * Perform the game loop. 
	 */
	@Override
	public void run() {
	
		Canvas c = null;
		
while (mRunThread) {
updateCordinates();//function that updates x and y positions of views 
			try {
					c = preview.getHolder().lockCanvas(null);
					synchronized (preview.getHolder()) {

						
						if(c!=null)
						preview.onDraw(c);

					}
				} finally {
					// do this in a finally so that if an exception is thrown
					// during the above, we don't leave the Surface in an
					// inconsistent state
					if (c != null) {
						preview.getHolder().unlockCanvasAndPost(c);
					}

				}
		}
}//class


Step 4:

Set instance of Preview class as the content view of your activity.

public class GameActivity extends Activity {

	public Preview mPreview;
	

	/**
	 * Method called on application start.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mPreview = new Preview(this);
		setContentView(mPreview); // game preview is a view
	}


This is it! Now you are ready for using Canvas and SurfaceView .Go ahead and make some great apps and games using this blog .

How to record voice in android

To record sound in android we have MediaRecorder class. It is used to record audio and video.

Its is a very flexible class ,it lets you set the encoding type, audio source type , output type etc

The example bellow will explain the usage of MediaRecorder class and saving it in sd card if available.

PERMISSIONS REQUIRED
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>

<uses-permission android:name=”android.permission.RECORD_AUDIO” />

Step 1.

Set the path where we wish to store the recoreded sound file.

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/audioRecord/record.3gp";

Environment.getExternalStorageDirectory().getAbsolutePath() returns the absolute path of he sdcard .This path refers to audioRecord folder in sdcard that will contain the recourded sound file in .3gp format.We can use other formats also like mp3,wav etc .

Step 2.

Creating and using MediaRecorder class object

MediaRecorder recorder = new MediaRecorder();

//Sets the audio source to be used for recording.
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

//setting 3gp as output format recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

//setting encoding format	 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

recorder.setOutputFile(path);//path of the audio recording to be stored

Step 3 

Before we start recording ,we check the availability of sd card.If sd card is mounted then we start the recording.

String state = android.os.Environment.getExternalStorageState();

if(!state.equals(android.os.Environment.MEDIA_MOUNTED))
{
recorder.prepare();//Prepares the recorder to begin
recorder.start();//begins capturing data
}

Step 4

Stop recording and release the resources in the following way .

recorder.stop();//stops recording
recorder.release();//releases resources

This is how we record and save recorded sound in android.

Here’s the complete example and recordDemo project for your reference.

import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import java.io.File;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

//records and saves a sound in sd card

File audiofile = null;
private static final String TAG = "SoundRecordingActivity";
Button startButton, stopButton;
String path;
MediaRecorder recorder;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startButton = (Button) findViewById(R.id.start);
stopButton = (Button) findViewById(R.id.stop);
startButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
recorder = new MediaRecorder();
path=Environment.getExternalStorageDirectory().getAbsolutePath() + "/audioRecord/record.3gp";

}

public void onClick(View v)

{
Log.i("hi", "in onclick() of main Act.");

switch (v.getId()) {
case R.id.start:
try {

String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Log.i("hi", "SD Card is not mounted" );
}

// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
Log.i("hi","Path to file could not be created.");
}
//Sets the audio source to be used for recording.
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//setting 3gp as output format
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
/setting encoding format
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//path of the audio recording to be stored
recorder.setOutputFile(path);
//Prepares the recorder to begin
recorder.prepare();
//begins capturing data
recorder.start();

} catch (Exception e) {

// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.stop:
try {
recorder.stop();//stops recording
recorder.release();//releases resources
//recorder1.stop();//stops the recording
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}

}// class

Screen shots of the above example :

Record Sound R2

 

Download the example project here.

Frame animation in android

Frame animation is explained below using a example that uses different loading images to creating a animation which continues for the specified time.
An animation defined which shows a sequence of images in order (like a film).

android.graphics.drawable.AnimationDrawable class is used for animations

The AnimationDrawable class is the basis for loading drawable resources one after another to create an animation. Notice that the animation is started in class starter’s in public void run() .

Example:

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;
public class SplashScreenActivity extends Activity
{
AnimationDrawable animation;
protected boolean _active = true;
protected int _splashTime = 5000;
@Override
public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
animation = new AnimationDrawable();

// the following code adds frames AnimationDrawable type animation and each frame //fetches the image from drawable ,which is fetched from resource folder. animation.addFrame(getResources().getDrawable(R.drawable.loading1_image), 100);
animation.addFrame(getResources().getDrawable(R.drawable.loading2_image), 100);
animation.addFrame(getResources().getDrawable(R.drawable.loading3_image), 100);
animation.setOneShot(false);// Sets whether the animation should play once or repeat

ImageView anim = (ImageView) findViewById(R.id.frame_id);
anim.setBackgroundDrawable(animation);// Set the background to a given Drawable
anim.post(new Starter());
/* a thread is being created */
Thread splashThread = new Thread() {
@Override
public void run()
{
try
{
int waited = 0;

while (_active && (waited < _splashTime))
{
sleep(1000);//waiting time
if (_active)
{
waited += 1000;
}
}
} catch (InterruptedException e)
{
}

finally {
finish();
);

//the next activity is called

Intent info = new Intent(SplashScreenActivity.this,SoundActivity.class
startActivity(info);
}
}
};
splashThread.start();
}
class Starter implements Runnable {
public void run() {
animation.start(); // Starts the animation
}
}
}

Steps:
• Create a Project .
• Create the xml file.
• Add some images into your drawable folder.
• Add the above code in your Activity class.
• Run the application.

Screen shots of the animation :

splashanim1 splashanim2

Custom Dialog Boxes in Android Example

A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress . The default dialog example I have already posted before.Here’s how a custom dialog is created.

The Dialog class is the base class for creating dialogs.

Types of default dialog  boxes are:

If we wish to create a customized dialog box then we can do so in the following way:

Step 1. Create a xml layout for the dialog box and a transparent background is preferable in order to show the Activity screen underneath it.

dialog_screen.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg_dialog" >

    <ImageView
        android:id="@+id/dialogImgView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/mid_box" />

    <ImageButton
        android:id="@+id/ImgBtn2_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/ImgBtn1_id"
        android:background="@drawable/female_selector" />

</RelativeLayout>

 

Step2. Add the following code for dialog box in oncreate(),onclick() etc based on where you want the dialog box to  pop. In the given example the dialog box appears  as soon as the activity starts .Hence, the code is placed in oncreate() .

public void onCreate(Bundle savedInstanceState)
	 {
	        super.onCreate(savedInstanceState);
		  setContentView(R.layout.play_menu_screen);//setting layout foractivity

              //put your activity related code here

		Dialog();   //function call for dialog box

	 }

	 /*code for creating a custom dialog box  */

	 private void Dialog()
 {    String gender;

// creating a dialog object and specifying the activity it pops on .
// R.style.FullHeightDialog specifies that dialog box has height
// equivalent to screen height

final Dialog dialog = new Dialog(PlayActivity.this,R.style.FullHeightDialog);

	dialog.setContentView(R.layout.dialog_screen);//setting the dialog xml layout

		/* adding action when image buttons of dialog are clicked */
			dialog.findViewById(R.id.ImgBtn_id).setOnClickListener(
					new OnClickListener() {
						public void onClick(View v) {
						//put your code here
						dialog.dismiss();//closes the dialog box
						}
					});

			dialog.show();//pops the dialog box

		}

This way we can create a customized dialog box .Why use the boring default dialog boxes when we can create our own.

Screenshot:

Custom Dialog

Custom Dialog

Opening http connection in android

Android has the java.net package which can be used to access network resources. The base class for HTTP network access in the java.net package is the HttpURLConnection class.

HttpURLConnection class can be used for the following:
1. Obtaining a HttpURLConnection by calling URL.openConnection()
2. Prepare the request.
3. Upload a request body.
4. Read the response. If the response has no body, that method returns an empty stream.
5. Disconnect, after the response has been read, by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

Permissions Required:

android.permission.INTERNET for http connection and android.permission.ACCESS_NETWORK_STATE for checking network status.

STEP 1:

Firstly check if network is connected or not by using ConnectivityManager class.NetworkInfo gets an instance that represents the current network connection.

ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
Log.i("hi", "connected internet");
} else
Log.i("hi", "not connected to internet");

STEP 2:

Opening a Http connection to a url in the following way:

URL url = new URL("http://www.blograchita.wordpress.com");
URLConnection conn = url.openConnection();

STEP 3
Use HttpURLConnection object to connect and get response input stream using
getInputStream() in the following way:
Code:

InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection")
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect(); response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK)
{
in = httpConn.getInputStream();
in.close();
}
} catch (Exception ex) {
Toast.makeText(this, "Error in connecting to the server", Toast.LENGTH_LONG).show();
throw new IOException("Error connecting");
}

Lets say that the response is a image ,then we can decode the input stream into a bitmap in the following way.
bitmap = BitmapFactory.decodeStream(in);
The response can a be a image or a string ,depending upon the type of response we can decode the stream.

Related Post:

Check internet connection status in android

App gallery in android

App gallery can be created using the below mentioned example.This code  displays  thumbnail images below a image view. Once click on these thumbnail images, the actual image will be displayed in the image view above.

I have used  ImageAdapter class that  extends BaseAdapter which sets the images in the gallery below and its corresponding preview in the image view ,according to the array passed to it.

You will also need to declare-styleable in the attributes.xml of res folder.This is used by ImageAdapater class.

A screenshot is also provided for your reference.

public class GalleryView extends Activity {
	//array of background images that appear in the gallery
    Integer[] pics = {
    		R.drawable.image01,
    		R.drawable.image02,
    		R.drawable.image03,
    		R.drawable.image04
    		    };
    ImageView imageView;
    private Context ctx;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery);//set layout
    // Gallery  view  shows items in a center-locked, horizontally scrolling list.
   	Gallery ga = (Gallery)findViewById(R.id.Gallery01);
     ga.setAdapter(new ImageAdapter(this));//setting adapter for adding many images
  imageView = (ImageView)findViewById(R.id.ImageView01);//fetching image view by id
 //when clicking on gallery thumbnail the image is displayed in the image view
        ga.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
		imageView.setImageResource(pics[arg2]);//setting image from array passed
			}
        });
    }
    public class ImageAdapter extends BaseAdapter {
    	int imageBackground;
    	public ImageAdapter(Context c) {
			ctx = c;
	//TypedArray stores styled attributes
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
// Retrieve the resource identifier for the attribute at index
imageBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
	//Give back a previously retrieved StyledAttributes, for later re-use.
			ta.recycle();
		}
		public int getCount() {
    		return pics.length;//no. of pics in gallery
    	}
    	public Object getItem(int arg0) {
    		return arg0;
    	}
    	public long getItemId(int arg0) {
    		return arg0;
    	}
	@Override
	//Get a View that displays the data at the specified position in the data set
    	public View getView(int arg0, View arg1, ViewGroup arg2) {
    		ImageView iv = new ImageView(ctx);
    		iv.setImageResource(pics[arg0]);//setting image thumbnail
// Controls how the image should be resized or moved to match the size of this
//ImageView.
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
// Set the layout parameters associated with this view

iv.setLayoutParams(new Gallery.LayoutParams(150,120));
// Set the background to a given resource    		iv.setBackgroundResource(imageBackground);
    		return iv;
    	}
    }
    }

Attributes.xml in res folder

<?xml version="1.0" encoding="utf-8"?>

  <resources>
	<declare-styleable name="Gallery1">
		<attr name="android:galleryItemBackground"/>
	</declare-styleable>
</resources>  

gallery.xml in layout folder

Here we create a gallery type view which displays a horizontally scrollable gallery


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

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="fill_parent"
        android:layout_height="2px"
        android:layout_margin="10dip"
        android:layout_weight="1"
        android:scaleType="centerInside" >
    </ImageView>

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerInside" >
    </Gallery>

</LinearLayout>

Screenshot :

App gallery