Check internet connection status in android

Almost every android application these days require accessing internet for fetching and posting data. Posting and fetching data usually causes exceptions due unavailability of internet . Hence , to always good to check internet connection before starting tasks that requires  internet connection. Check this post if you want to how to make http connections.

You can also check the  kind of internet connection is available in handset.eg wifi or mobile data

The following code snippet will let you check internet availability and specify the type of internet connection available.

Step 1. Firstly  you need to add the following permission in the AndroidManifest.

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

Step 2: Use the following code to check internet status

private boolean isNetworkConnected() {
// checks for both mobile and wifi internet connection
boolean isConnectedWifi = false;
boolean isConnectedMobile = false;

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[]info = cm.getAllNetworkInfo();
for (NetworkInfo net : info) {
if (net.getTypeName().equalsIgnoreCase("WIFI"))
if (net.isConnected())
haveConnectedWifi = true;
if (net.getTypeName().equalsIgnoreCase("MOBILE"))
if (net.isConnected())
haveConnectedMobile = true;
}
return isConnectedWifi || isConnectedMobile;
}

Always remember to check to internet availability before performing any tasks that require internet .

Related Posts:

Making  http connection in android

Using shared preferences in android

Storing app data is an essential requirement of most applications. Android lets your store data using Shared Preferences and Sqlite database. You can use either of them, based on your requirement. Check this post to decide which one suits your requirement

Shared Preferences  stores data as key-pairs only. Key is required to read data from it. Reading amd storing data in it is very simple .But, it’s difficult to store and read large structured data . It saves  primitives data type like string, int ,booleans, floats ,long etc. It is best to use Shared Preferences when only small amount of data needs to be stored eg few app settings, user login /password etc.

Step 1: Create your shared preferences in the following way :

SharedPreferences myPreferences = this.getSharedPreferences("myPreferences", 0);

Step 2: Save values in shared preferences using editor.
“myInt” is the key and “2” is the value to be stored

SharedPreferences.Editor prefEditor = myPreferences.edit();
		prefEditor.putInt("myInt", 2);
		prefEditor.commit();

Step 3: Retrieve values from shared preferences using the key. Second parameter of getInt(“myInt”, 0) denotes the default value to be returned if no value is saved yet.

myPreferences.getInt("myInt", 0);

Complete Example:

public class SharedPreferenceActivity extends Activity implements
		OnClickListener {
	SharedPreferences myPreferences;
	EditText nameEditText, AgeEditText;
	Button saveBtn, showBtn;
	TextView showTextview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		nameEditText = (EditText) findViewById(R.id.nameEdittext_id);
		AgeEditText = (EditText) findViewById(R.id.ageEdittext_id);
		saveBtn = (Button) findViewById(R.id.saveBtn_id);
		showBtn = (Button) findViewById(R.id.showBtn_id);
		showTextview = (TextView) findViewById(R.id.showText_id);
		// creating "myPreferences" sharedPreference
		myPreferences = this.getSharedPreferences("myPreferences", 0);

		saveBtn.setOnClickListener(this);
		showBtn.setOnClickListener(this);

	}

	void setIntAppPref(int a) {
		SharedPreferences.Editor prefEditor = myPreferences.edit();
		prefEditor.putInt("myInt", a);
		prefEditor.commit();
	}

	int getIntAppPref() {
		return myPreferences.getInt("myInt", 0);
	}

	void setStringAppPref(String a) {
		SharedPreferences.Editor prefEditor = myPreferences.edit();
		prefEditor.putString("myString", a);
		prefEditor.commit();
	}

	String getStringAppPref() {
		return myPreferences.getString("myString", "");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.saveBtn_id:
			setStringAppPref(nameEditText.getText().toString());
			setIntAppPref(Integer.parseInt(AgeEditText.getText().toString()));

			break;
		case R.id.showBtn_id:
			showTextview.setText("Name:" + getStringAppPref() + '\n' + "Age:"
					+ getIntAppPref());

			break;

		default:
			break;
		}

	}

}

Screenshots:

pref1              pref2

Download the example code here

download_image.

Related Posts:

Difference between sqlite and shared preferences in android

PreferenceActivity in Android

 

Difference between sqlite and shared preferences in android

Storing app data is an essential requirement of most applications. Android lets your store data using Shared Preferences and Sqlite database. You can use either of them, based on your requirement.

Shared Preferences

Shared Preferences stores data as key-pairs only. Key is required to read data from it. Reading amd storing data in it is very simple .But, it’s difficult to store and read large structured data . It saves  primitives data type like string, int ,booleans, floats ,long etc. It is best to use Shared Preferences when only small amount of data needs to be stored eg few app settings, user login /password etc.

Sqlite Database

It stores structured data as a database. The data can be queried and hence ,this makes it possible to search database. Reading data from sqlite database is slower and more expensive then shared preferences. SQLite database is useful for just about anything and very flexible. It is best to use Sqlite when the data to be stored is large , structured and required searching .eg storing complete user details , storing data fetched by http request etc.

Related Posts:

PreferenceActivity in Android

Using shared preferences in android

Listview with header footer view android

At times we need to add some title to a list view or show some data at the very end of list view . For this we need not pass this data in adapter of listview , instead we can add it as header and views in the following way.

If you are not sure how to create a listview  you can refer these examples.

Step 1: Create a layout xml for the header and footer as per your requirement.

header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="HEADER"
    android:background="#cf9f99" />

</LinearLayout>

footer.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="FOOTER"
    android:background="#cf9f99" />

</LinearLayout>

Step 2: Now let’s inflate these header and footer views and add it to our list view .

LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
				false);
		ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
				false);
		listView.addHeaderView(header, null, false);
		listView.addFooterView(footer, null, false);



Complete Code 

LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
				false);
		ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
				false);
		listView.addHeaderView(header, null, false);
		listView.addFooterView(footer, null, false);

Complete Code

public class MainActivity extends Activity {
	ListView listView;

	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" };
	View header;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listView = (ListView) findViewById(R.id.list_id);

		//code to add header and footer to listview
		LayoutInflater inflater = getLayoutInflater();
		ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
				false);
		ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
				false);
		listView.addHeaderView(header, null, false);
		listView.addFooterView(footer, null, false);

		ArrayAdapter adapter = new ArrayAdapter(this,
				android.R.layout.simple_list_item_1, numbers);

		listView.setAdapter(adapter);

	}

}

Screenshots:

footerList                        headerList

Download this example form here .

Related Links:

GridView Array Adapter Example

ListView ArrayAdapter Example

Custom ListView Example

Custom Grid View Example

Custom GridView 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 find the gridview arrayadapter example here.

We can also create our own custom adapters using BaseAdapter class. Custom Adapters are way better than array adapters, they give you more control over the list/grid view content and UI .Here we inflate each row of GridView using a layout.

The following example explains the usage of ListView using a custom adapter.

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

 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=".GridViewActivity" >

<GridView
android:id="@+id/grid_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>

</RelativeLayout>

Step 2: Create a custom layout for each row of the Grid View.

 grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/textView_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal" />

</LinearLayout>

Step 3: Create a custom adapter in the following way .

GridAdapter.java 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class GridAdapter extends BaseAdapter {

	String[] textArray;
	Context contxt;

	public GridAdapter(String[] textArr, Context context) {
		textArray = textArr;
		contxt=context;
	}

	@Override
	public int getCount() {

		return textArray.length;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		// create a new LayoutInflater
		LayoutInflater inflater = (LayoutInflater) contxt
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;
		gridView = null;
		convertView = null;// avoids recycling of grid view
		if (convertView == null) {

			gridView = new View(contxt);
			// inflating grid view item
			gridView = inflater.inflate(R.layout.grid_item, null);

			// set value into textview
			TextView textView = (TextView) gridView
					.findViewById(R.id.textView_id);
			textView.setText(textArray[position]);

		}

		return gridView;
	}

}

Step 4: Create the Activity and implement custom adapter in the activity using the code mentioned below.

  • Create  GridAdapter type adapter .
  • Set GridView adapter as this custom adapter.
  • You can set listeners on your list view also.

GridViewActivity.java

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

import com.example.customgridviewexample.R;

public class GridViewActivity extends Activity {
	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" };
	GridView gridView;
	GridAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gridView = (GridView) findViewById(R.id.grid_id);
		adapter=new  GridAdapter(numbers, this);
		gridView.setAdapter(adapter);

	}

}

 

Screenshot:

customgrid

Download

You can also download the above ListView Example here.

Related Posts:

GridView Array Adapter Example

ListView ArrayAdapter Example

Custom ListView Examle

Custom list view in android

ListView  is used for arranging items in a vertical and scrollable list. ListViews are commonly used to display a large set of similar data.

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

The simplest way to display a list view is using ArrayAdapter class . You can study how to create ListViews using array adapter here. We can also create our own custom adapters using BaseAdapter class. Custom Adapters are way better than array adapters, they give you more control over the list/grid view content and UI .Here we inflate each row of listView using a layout.

The following example explains the usage of ListView using a custom adapter.

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

activity_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=".MainActivity" >

    <ListView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        >
    </ListView>

</RelativeLayout>

Step 2: Create a custom layout for each row of the List View.

list_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/list_item_image"
        android:layout_width="50px"
        android:layout_height="50px"
        android:layout_marginRight="10px"
        android:background="@drawable/ic_launcher" >
    </ImageView>

    <TextView
        android:id="@+id/list_item_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5px"
        android:text="@+id/label"
        android:textSize="15px" >

    </TextView>

</LinearLayout>

Step 3: Create a custom adapter in the following way .

ImageAdapter.java 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ImageAdapter extends BaseAdapter {
	private Context context;
	private final String[] StrValues;

	public ImageAdapter(Context context, String[] StrValues) {
		this.context = context;
		this.StrValues = StrValues;
	}

	// getView that displays the data at the specified position in the data set.
	public View getView(int position, View convertView, ViewGroup parent) {
		// create a new LayoutInflater
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View gridView;
		gridView = null;
		convertView = null;// avoids recycling of grid view
		if (convertView == null) {

			gridView = new View(context);
			// inflating grid view item
			gridView = inflater.inflate(R.layout.list_view_item, null);

			// set value into textview
			TextView textView = (TextView) gridView
					.findViewById(R.id.list_item_label);
			textView.setText(StrValues[position]);

		}

		return gridView;
	}

	// Total number of items contained within the adapter
	@Override
	public int getCount() {
		return StrValues.length;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

}

Step 4: Create the Activity and implement custom adapter in the activity using the code mentioned below.

  • Create  ImageAdapter type adapter .
  • Set ListView adapter as this custom adapter.
  • You can set listeners on your list view also.

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	static final String[] StrValues = 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" };
	ListView listView;

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

		listView = (ListView) findViewById(R.id.listView1);
		// setting adapter on listview
		listView.setAdapter(new ImageAdapter(this, StrValues));
		//setting on item click listener
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {//displaying toast
				Toast.makeText(
						getApplicationContext(),
						((TextView) v.findViewById(R.id.list_item_label))
								.getText(), Toast.LENGTH_SHORT).show();

			}
		});

	}
}

Screenshot:

custom Listview

Download

You can also download the above ListView Example here.

Related Posts:

Simple ListView in android

Simple GridView in android

Custom GridView in android

ListView example android

ListView  is used for arranging items in a vertical and scrollable list. ListViews are commonly used to display a large set of similar data.

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

The simplest way to display a list 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 ListView.

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

The following example explains the usage of ListView using ArrayAdapter.

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

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=".MainActivity" >

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

</RelativeLayout>

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

  • Create the ArrayAdapter and add a default layout list style and string array of data to it.
  • Set ListView adapter as the ArrayAdapter.
  • You can set listeners on your list view also.
public class MainActivity extends Activity {
	ListView listView;

	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.activity_main);
		listView = (ListView) findViewById(R.id.list_id);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, numbers);

		listView.setAdapter(adapter);
		listView.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:

ListView

You can also download the above ListView Example here

Related Posts:

GridView ArrayAdapter Example

Custom Gridview Example 

Custom Listview Example 

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.