Codes

Toast:
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),Toast.LENGTH_SHORT).show();
------------------------
Intents:
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);
------------------------

Service

Most confusion about the Service class actually revolves around what it is not:

-A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
-A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:
A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread. It is up to the Service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Service Lifecycle :
There are two reasons that a service can be run by the system.

If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface that has been written in aidl. A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

Audio and Video

Android includes a comprehensive Media Player to simplify the playback of audio and video.

Multimedia playback in Android is handled by the MediaPlayer class. You can play media stored in application resources, local files, Content Providers, or streamed from a network URL. In each case,
the file format and type of multimedia being played is abstracted from you as a developer.

The Media Player’s management of audio and video files and streams is handled as a state machine. In the most simplistic terms, transitions through the state machine can be described as follows:
- Initialize the Media Player with media to play.
- Prepare the Media Player for playback.
- Start the playback
- Pause or stop the playback prior to its completing.
- Playback complete.

To play a media resource you need to create a new MediaPlayer instance, initialize it with a media
source, and prepare it for playback.

Initializing Audio Content for PlaybackTo play back audio content using the Media Player, you need to create a new Media Player object and set the data source of the audio in question.

To play back audio using the Media Player, you can use the static create method, passing in the application Context and one of the following:
- A resource identifier
- A URI to a local file using the file:// schema
- A URI to an online audio resource as a URL
- A URI to a local Content Provider row

Initializing audio content for playback
Context appContext = getApplicationContext();
MediaPlayer resourcePlayer = MediaPlayer.create(appContext,R.raw.my_audio);
MediaPlayer filePlayer = MediaPlayer.create(appContext,Uri.parse("file:///sdcard/localfile.mp3"));
MediaPlayer urlPlayer = MediaPlayer.create(appContext,Uri.parse("http://site.com/audio/audio.mp3"));
MediaPlayer contentPlayer = MediaPlayer.create(appContext,Settings.System.DEFAULT_RINGTONE_URI);

Alternatively, you can use the setDataSource method on an existing Media Player instance. This method accepts a file path, Content Provider URI, streaming media URL path, or File Descriptor.

When using the setDataSource method it is vital that you call prepare on the Media Player before you
begin playback.

Using setDataSource and prepare to initialize audio playback
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/sdcard/test.3gp");
mediaPlayer.prepare();

In each case, once you’ve finished playback, callrelease on your Media Player object to free the associated resources:
mediaPlayer.release();

Android supports a limited number of simultaneous Media Player objects; not releasing them can cause runtime exceptions when the system runs out of resources.

Preparing for Video Playback
Playback of video content is slightly more involved than audio. To show a video, you must specify a display surface on which to show it. The following sections describe two alternatives for the playback of video content.

The first, using the Video View control, encapsulates the creation of a display surface and allocation and preparation of video content within a Media Player. The second technique allows you to specify your own display surface and manipulate the underlying Media Player instance directly.

Playing Video Using the Video ViewThe simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback.

The Video View supports the playback of local or streaming video as supported by the Media Player
component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play simply call setVideoPath or setVideoUri to specify the path to a local file, or the URI of a ContentProvider or remote video stream:
streamingVideoView.setVideoUri("http://www.mysite.com/videos/myvideo.3gp");
localVideoView.setVideoPath("/sdcard/test2.3gp");

Once initialized, you can control playback using the start, stopPlayback, pause, and seekTo methods. The Video View also includes the setKeepScreenOn method to apply a screen Wake Lock that will prevent the screen from being dimmed while playback is in progress.

Video playback using a Video View
VideoView videoView = (VideoView)findViewById(R.id.surface);
videoView.setKeepScreenOn(true);
videoView.setVideoPath("/sdcard/test2.3gp");
if (videoView.canSeekForward())
videoView.seekTo(videoView.getDuration()/2);
videoView.start();
[ . . . do something . . . ]
videoView.stopPlayback();
 
Setting up a Surface for Video Playback
The first step to using the Media Player to view video content is to prepare a Surface onto which the
video will be displayed. TheMedia Player requires a SurfaceHolder object for displaying video content,
assigned using the setDisplay method.


Sample layout including a Surface View
<?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">
<SurfaceView
android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</LinearLayout>
 

The Surface View is a wrapper around the Surface Holder object, which in turn is a wrapper around the Surface that is used to support visual updates from background threads.

Surface Holders are created asynchronously, so you must wait until the surfaceCreated handler has been fired before assigning the returned Surface Holder object to the Media Player.

Initializing and assigning a Surface View to a Media Player
public class MyActivity extends Activity implements SurfaceHolder.Callback
{
private MediaPlayer mediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
SurfaceView surface = (SurfaceView)findViewById(R.id.surface);
SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());

} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mediaPlayer.release();
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) { }
}



Initializing Video Content for Playback
Once you have created and assigned the Surface Holder to your Media Player, use the setDataSource method to specify the path, URL, or Content Provider URI of the video resource to play.

As with audio playback, if you’re passing a URL to an online media file, the file must be capable of
progressive download using the RTSP or HTTP protocols.

Once you’ve selected your media source, callprepare to initialize the Media Player in preparation for
playback.

Initializing video for playback using the Media Player
public void surfaceCreated(SurfaceHolder holder) {
try {
mediaPlayer.setDisplay(holder);
mediaPlayer.setDataSource("/sdcard/test2.3gp");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IllegalStateException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
} catch (IOException e) {
Log.d("MEDIA_PLAYER", e.getMessage());
}
}

Notification

Your applications can use Notifications to alert users without using an Activity. Notifications are handled by the Notification Manager, and currently have the ability to:
- Create new status bar icons
- Display additional information (and launch an Intent) in the extended status bar window
- Flash the lights/LEDs
- Vibrate the phone
- Sound audible alerts (ringtones, Media Store audio)


Using Notifications is the preferred way for invisible application components (Broadcast Receivers, Services, and inactive Activities) to alert users that events have occurred that may require attention. They are also used to indicate ongoing background Services — particularly Services that have been
set to foreground priority.

As a user interface metaphor, Notifications are particularly well suited to mobile devices. It’s likely that your users will have their phones with them at all times but quite unlikely that they will be paying attention to them, or your application, at any given time. Generally users will have several applications open in the background, and they won’t be paying attention to any of them.

In this environment it’s important that your applications be able to alert users when specific events occur that require their attention. Notifications can be persisted through insistent repetition, being marked ongoing, or simply by displaying an icon on the status bar. Status bar icons can be updated regularly or expanded to show additional information using the expanded status bar window

Permissions

Permissions are an application-level security mechanism that lets you restrict access to application components. Permissions are used to prevent malicious applications from corrupting data, gaining access to sensitive information, or making excessive (or unauthorized) use of hardware resources or external communication channels.

The native permission strings used by native Android Activities and Services can be found as static constants in the android.Manifest.permission class. To use permission-protected components, you need to add <uses-permission> tags to application manifests, specifying the permission string that each application requires.

When an application package is installed, the permissions requested in its manifest are analyzed and granted (or denied) by checks with trusted authorities and user feedback.

Declaring and Enforcing Permissions:
 <uses-permission
        android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission
        android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
    <uses-permission
        android:name="android.permission.INTERNET" />
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission
        android:name="android.permission.WRITE_SECURE_SETTINGS" />
    <uses-permission
        android:name="android.permission.READ_CONTACTS" />
    <uses-permission
        android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission
        android:name="android.permission.READ_SYNC_STATS" />
    <uses-permission
        android:name="android.permission.READ_SYNC_SETTINGS" />
    <uses-permission
        android:name="android.permission.WRITE_SYNC_SETTINGS" />


To include permission requirements for your own application components, use the permission attribute in the application manifest. Permission constraints can be enforced throughout your application, most usefully at application interface boundaries, for example:- Activities Add a permission to limit the ability of other applications to launch an Activity.
- Broadcast Receivers Control which applications can send broadcast Intents to your Receiver.
- Content Providers Limit read access and write operations on Content Providers.
- Services Limit the ability of other applications to start, or bind to, a Service.

In each case, you can add a permission attribute to the application component in the manifest, specifying a required permission string to access each component

Content Providers let you set readPermission and writePermission attributes to offer a more granular
control over read/write access.

Android Database

SQLite offers a powerful SQL database library that provides a robust persistence layer over which you have total control. Using SQLite you can create independent relational databases for your applications. Use them to store and manage complex, structured application data. Android databases are stored in the /data/data/<package_name>/databases folder on your device (or emulator). By default all databases are private, accessible only by the application that created them.

Content Providers offer a generic interface to any data source by decoupling the data storage layer from the application layer. Content Providers offer a standard interface your applications can use to share data with and consume data from other applications— including many of the native data stores.

SQLite is a well regarded relational database management system (RDBMS). It is Open-source, Standards-compliant, Lightweight & Single-tier.

CURSORS AND CONTENT VALUES:ContentValues are used to insert new rows into tables. Each Content Values object represents a single
table row as a map of column names to values.

Queries in Android are returned as Cursor objects. Rather than extracting and returning a copy of the result values, Cursors are pointers to the result set within the underlying data. Cursors provide a managed way of controlling your position (row) in the result set of a database query.
The Cursor class includes a number of navigation functions including, but not limited to, the following:
moveToFirst Moves the cursor to the first row in the query result
moveToNext Moves the cursor to the next row
moveToPrevious Moves the cursor to the previous row
getCount Returns the number of rows in the result set
getColumnIndexOrThrow Returns the index for the column with the specified name (throwing
an exception if no column exists with that name)
getColumnName Returns the name of the specified column index
getColumnNames Returns a string array of all the column names in the current Cursor
moveToPosition Moves the Cursor to the specified row
getPosition Returns the current Cursor position

Android provides a convenient mechanism for simplifying the management of Cursors within your Activities. The startManagingCursor method integrates the Cursor’s lifetime into the calling Activity’s. When you’ve finished with the Cursor, call stopManagingCursor to do just that.

Querying a Database
To execute a query on a database use the query method, passing in:
- An optional Boolean that specifies if the result set should contain only unique values.
- The name of the table to query.
- A projection, as an array of strings, that lists the columns to include in the result set.
- A ‘‘where’’ clause that defines the rows to be returned. You can include ? wildcards that will
be replaced by the values passed in through the selection argument parameter.
- An array of selection argument strings that will replace the ?’s in the where clause.
- A ‘‘group by’’ clause that defines how the resulting rows will be grouped.
- A ‘‘having’’ filter that defines which row groups to include if you specified a group by clause.
- A string that describes the order of the returned rows.
- An optional string that defines a limit for the number of returned rows.

// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order);

Extracting values from a Cursor
int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
float totalHoard = 0f;

// Make sure there is at least one row.
if (myGold.moveToFirst()) {
// Iterate over each cursor.
do {
float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
totalHoard += hoard;
} while(myGold.moveToNext());
}
float averageHoard = totalHoard / myGold.getCount();

Because SQLite database columns are loosely typed, you can cast individual values into valid types as
required.

SAVING AND LOADING FILES

It’s good practice to use Shared Preferences or a database to store your application data, but there are still times when you’ll want to use files directly rather than rely on Android’s managed mechanisms. As well as the standard Java I/O classes and methods, Android offers openFileInput and openFileOuput to simplify reading and writing streams from and to local files.

Saving and loading files
String FILE_NAME = "tempfile.tmp";
// Create a new output file stream that’s private to this application.
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
FileInputStream fis = openFileInput(FILE_NAME);

These methods support only those files in the current application folder; specifying path separators will cause an exception to be thrown. If the file name you specify when creating a FileOutputStream does  not exist, Android will create it for you.

INCLUDING STATIC FILES AS RESOURCES
If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.

To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the file name (without extension) as the variable name from the R.raw class, as shown in the following skeleton code:

Resources myResources = getResources();
InputStream myFile = myResources.openRawResource(R.raw.myfilename);

Adding raw files to your resources hierarchy is an excellent alternative for large, preexisting data sources (such as dictionaries) for which it’s not desirable (or even possible) to convert them into Android databases.

Android’s resource mechanism lets you specify alternative resource files for different languages, locations, and hardware configurations. You could, for example, create an application that loads a different dictionary resource based on the user’s language settings.

FILE MANAGEMENT TOOLS
Android supplies some basic file management tools to help you deal with the file system. Many of these utilities are located within the standard java.io.File package.

➤ deleteFile Enables you to remove files created by the current application.
➤ fileList Returns a string array that includes all the files created by the current application.

These methods are particularly useful for cleaning up temporary files left behind if your application
crashes or is killed unexpectedly.

Shared Preferences

Using the SharedPreferences class you can create named maps of key/value pairs within your application that can be shared among application components running in the same application context.

Shared Preferences support the primitive types Boolean, string, float, long, and integer, making them an ideal means of quickly storing default values, class instance variables, the current UI state, and user preferences. They are most commonly used to persist data across user sessions and to share settings among application components.

Activities also offer the onSaveInstanceState handler. It’s designed specifically to persist UI state when the Activity becomes eligible for termination by a resource-hungry run time.

The handler works like the Shared Preference mechanism. It offers a Bundle parameter that represents a key/value map of primitive types that can be used to save the Activity’s instance values. This Bundle is then made available as a parameter passed in to the onCreate and onRestoreInstanceState method handlers.

This UI state Bundle should be used to record the values needed for an Activity to present an identical UI when it’s displayed after an unexpected close.

CREATING AND SAVING PREFERENCES
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean("isTrue", true);
editor.putFloat("lastFloat", 1f);
editor.putInt("wholeNumber", 2);
editor.putLong("aNumber", 3l);
editor.putString("textEntryValue", "Not Empty");
// Commit the changes.
editor.commit();
}

RETRIEVING SHARED PREFERENCES
public static String MY_PREFS = "MY_PREFS";
public void loadPreferences() {
// Get the stored preferences
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, mode);
// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean("isTrue", false);
float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f);
int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1);
long aNumber = mySharedPreferences.getLong("aNumber", 0);
String stringPreference = mySharedPreferences.getString("textEntryValue", "");
}

The Preference Activity framework consists of three parts:
- Preference Screen Layout: An XML file that defines the hierarchy displayed in your Preference Activity. It specifies the controls to display, the values to allow, and the Shared Preference keys to use for each UI control.
-Preference Activity: An extension of PreferenceActivity that will be used to host your application preference screens.
- Shared Preference Change Listener: An implementation of the onSharedPreferenceChangeListener class used to listen for changes to Shared Preferences.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="My Preference Category"/>
<CheckBoxPreference android:key="PREF_CHECK_BOX" android:title="Check Box Preference"
android:summary="Check Box Preference Description" android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>

Native Preference Controls:
Android includes several preference controls to build your Preference Screens:
- CheckBoxPreference: A standard preference checkbox control. Used to set preferences to true or false.
- EditTextPreference: Allows users to enter a string value as a preference. Selecting the preference text will display a text entry dialog.
- ListPreference: The preference equivalent of a spinner. Selecting this preference will display a dialog
box containing a list of values from which to select. You can specify different arrays to contain the display text and selection values.
- RingtonePreference: A specialized List Preference that presents the list of available ringtones for user selection. This is particularly useful when you’re constructing a screen to configure notification settings.

Dialog

Dialog boxes are a common UI metaphor in desktop, web, and mobile applications. They’re used to help users answer questions, make selections, and confirm actions, and to display warning or error  messages. Dialog boxes in Android are partially transparent, floating Activities that partially obscure the Activities that launched them.

There are three ways to implement a dialog in Android: .

- Using the Dialog class: As well as the general-purpose AlertDialog class, Android includes a number of specialist classes that extend Dialog. Each is designed to provide specific dialog box functionality. A Dialog-class-based screen is constructed entirely within its calling Activity, so it doesn’t need to be registered in the manifest as its life cycle is controlled entirely by the calling Activity.

- Dialog-themed Activities: You can apply the dialog theme to a regular Activity to give it the appearance of a standard dialog box.

- Toasts: Toasts are special non-modal transient message boxes, often used by Broadcast Receivers and Services to notify users of events occurring in the background.

The Alert Dialog Class
The AlertDialog class is one of the most versatile Dialog-class implementations. It offers a number of
options that let you construct screens for some of the most common dialog-box use cases, including:

- Presenting a message to the user offering them one to three options in the form of buttons. This functionality is probably familiar to you if you’ve done any desktop programming for which the buttons presented are usually a combination of OK, Cancel, Yes, and No.
- Offering a list of options in the form of checkboxes or radio buttons.
- Providing a text entry box for user input.

To construct the Alert Dialog user interface, create a new AlertDialog.Builder object as follows:
AlertDialog.Builder ad = new AlertDialog.Builder(context);

You can then assign values for the title and message to display, and optionally assign values to be used
for any buttons, selection items, and text input boxes you wish to display. That includes setting event
listeners to handle user interaction.

Specialist Input Dialogs
One of the major uses of dialog boxes is to provide an interface for user input. Android includes several
specialist dialog boxes that encapsulate controls designed to facilitate common user-input requests.

They include the following:
- CharacterPickerDialog: Lets users select an accented character based on a regular character source.
- DatePickerDialog: Lets users select a date from a DatePicker View. The constructor includes a callback listener to alert your calling Activity when the date has been set.
-TimePickerDialog: Similar to the Date Picker Dialog, this dialog lets users select a time from a TimePicker View.
- ProgressDialog: A dialog that displays a progress bar beneath a message text box. Perfect for keeping the user informed of ongoing progress of a time-consuming operation.

Configuring an Alert Dialog
Context context = MyActivity.this;
String title = "It is Pitch Black";
String message = "You are likely to be eaten by a grue.";
String button1String = "Go Back";
String button2String = "Move Forward";
AlertDialog.Builder ad = new AlertDialog.Builder(context);
ad.setTitle(title);
ad.setMessage(message);
ad.setPositiveButton(button1String,new OnClickListener() {
public void onClick(DialogInterface dialog, int arg1) {
eatenByGrue();
} });
ad.setNegativeButton(button2String,
new OnClickListener(){
public void onClick(DialogInterface dialog, int arg1) {
// do nothing
}
});
ad.setCancelable(true);
ad.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
eatenByGrue();
}
});

To display an Alert Dialog that you’ve created callshow:
ad.show();

A better alternative is using your Activity’sonCreateDialog and onPrepareDialog handlers to create dialog instances that can persist state.

Adapters

Adapters are bridging classes that bind data to Views (such as List Views) used in the user interface. The adapter is responsible for creating the child Views used to represent each item within the parent View, and providing access to the underlying data. Views that support Adapter binding must extend the AdapterView abstract class.

- ListAdapter: Extended Adapter that is the bridge between a ListView and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.

- ArrayAdapter: A listAdapter that manages a ListView backed by an array of arbitrary objects. By default, this class expects  that the provided resource id references a single text view.

- CursorAdapter: Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.

- HeaderViewListAdapter: ListAdapter used when a ListView has header views. This ListAdapter wraps another one and also keeps track of the header views and their associated data objects.

- SourceCursorAdapter: It is used to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views

- SimpleAdapter: It is used to to map static data to views defined in an XML file.

- SpinnerAdapter: It  is the bridge between a Spinner and its data. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.

- WrappedListAdapter: List adapter that wraps another list adapter. The wrapped adapter can be retrieved by calling getWrappedAdapter().

Intents

Intents are used as a message-passing mechanism that works both within your application, and between
applications. Intents can be used to:

- Declare your intention that an Activity or Service be started to perform an action, usually with (or on) a particular piece of data.
- Broadcast that an event (or action) has occurred.
- Explicitly start a particular Service or Activity.

You can use Intents to support interaction among any of the application components installed on an Android device, no matter which application they’re a part of. This turns your device from a platform containing a collection of independent components into a single interconnected system.

One of the most common uses for Intents is to start new Activities, either explicitly (by specifying the class to load) or implicitly (by requesting that an action be performed on a piece of data).
 
Intent intent = new Intent(MyActivity.this, MyOtherActivity.class);
startActivity(intent);


Starting an Activity for a result
private static final int SHOW_SUBACTIVITY = 1;
Intent intent = new Intent(this, MyOtherActivity.class);
startActivityForResult(intent, SHOW_SUBACTIVITY);

Intents can also be used to broadcast messages across the system. Any application can register Broadcast Receivers to listen for, and react to, these broadcast Intents. This lets you create event-driven applications based on internal, system, or third-party-application events.

Android broadcasts Intents to announce system events, like changes in Internet connection status or battery charge levels. The native Android applications, such as the phone dialer and SMS manager, simply register components that listen for specific broadcast Intents — such as ‘‘incoming phone call’’ or ‘‘SMS message received’’ — and react accordingly.

Using Intents to propagate actions — even within the same application — is a fundamental Android design principle. It encourages the decoupling of components, to allow the seamless replacement of application elements. It also provides the basis of a simple model for extending an application’s functionality.