Tuesday, 28 February 2017

Databases connectivity in android

Databases connectivity in android
....................................................................................
Android provides full relational database capabilities through the SQLite library, without imposing any additional limitations.
Using SQLite, you can create independent, relational databases for each application. Use them to store and manage complex, structured application data.
All 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. To share a database across applications, use Content Providers, as shown later in this chapter.Database design is a vast topic that deserves more thorough coverage than is possible within this book.However, it’s worth highlighting that standard database best practices still apply. In particular, when creating databases for resource-constrained devices, it’s important to reduce data redundancy using normalization.
The following sections focus on the practicalities of creating and managing SQLite databases in Android.

Introducing SQLite

SQLite is a relational database management system (RDBMS). It is well regarded, being:
  • Open source
  • Standards-compliant
  • Lightweight
  • Single-tier
It has been implemented as a compact C library that’s included as part of the Android software stack.By providing functionality through a library, rather than as a separate process, each database becomes an integrated part of the application that created it. This reduces external dependencies, minimizes latency, and simplifies transaction locking and synchronization.
SQLite has a reputation of being extremely reliable and is the database system of choice for many consumer electronic devices, including several MP3 players, the iPhone, and the iPod Touch.
Lightweight and powerful, SQLite differs from many conventional database engines by using a loosely typed approach to column definitions. Rather than requiring column values to conform to a single type, the values in each row for each column are individually typed. As a result, there’s no strict type checking when assigning or extracting values from each column within a row.

Cursors and Content Values

ContentValuesobjects are used to insert new rows into database tables (and Content Providers). Each Content Values object represents a single 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 act as pointers to a subset of the underlying data. Cursors are a managed way of controlling your position (row) in the result set of a database query.
The Cursor class includes several functions to navigate query results including, but not limited to, the following:
  • moveToFirstMoves the cursor to the fi rst row in the query result.
  • moveToNextMoves the cursor to the next row.
  • moveToPreviousMoves the cursor to the previous row.
  • getCountReturns the number of rows in the result set.
  • getColumnIndexOrThrowReturns an index for the column with the specified name (throwing an exception if no column exists with that name).
  • getColumnNameReturns the name of the specified column index.
  • getColumnNamesReturns a String array of all the column names in the current cursor.
  • moveToPositionMoves the cursor to the specified row.
  • getPositionReturns the current cursor position.
Android provides a mechanism to manage Cursor resources within your Activities. The startManagingCursormethod integrates the Cursor’s lifetime into the parent Activity’s lifetime management. When you’ve fi nished with the Cursor, call stopManagingCursorto do just that.Later in this chapter, you’ll learn how to query a database and how to extract specifi c row/column values from the resulting Cursor objects.

Working with Android Databases

It’s good practice to create a helper class to simplify your database interactions.
Consider creating a database adapter, which adds an abstraction layer that encapsulates database interactions.
It should provide intuitive, strongly typed methods for adding, removing, and updating items.A database adapter should also handle queries and wrap creating, opening, and closing the database.It’s often also used as a convenient location from which to publish static database constants, including table names, column names, and column indexes.
The following snippet shows the skeleton code for a standard database adapter class. It includes an extension of the SQLiteOpenHelperclass, used to simplify opening, creating, and upgrading the database.
import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
import android.database.sqlite.
SQLiteDatabase.CursorFactory;
import android.util.Log;
public class MyDBAdapter {
private static final String DATABASE_NAME = “myDatabase.db”;
private static final String DATABASE_TABLE = “mainTable”;
private static final int DATABASE_VERSION = 1;
// The index (key) column name for use in where clauses.
public static final String KEY_ID=”_id”;
// The name and column index of each column in your database.
public static final String KEY_NAME=”name”;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
private static final String DATABASE_CREATE = “create table “ +
DATABASE_TABLE + “ (“ + KEY_ID +
“ integer primary key autoincrement, “ +
KEY_NAME + “ text not null);”;
// Variable to hold the database instanceprivate SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private myDbHelper dbHelper;
public MyDBAdapter(Context _context) {
context = _context;
dbHelper = new myDbHelper(contextDATABASE_NAME, null,
DATABASE_VERSION);
}
public MyDBAdapter open() throws SQLException {
db dbHelper.getWritableDatabase();
return this;
}
public void close() {
db.close();
}
public long insertEntry(MyObject _myObject) {
ContentValuescontentValues = new ContentValues();
// TODO fill in ContentValues to represent the new row
return db.insert(DATABASE_TABLE, null, contentValues);
}
public boolean removeEntry(long _rowIndex) {
return db.delete(DATABASE_TABLE, KEY_ID +
“=” + _rowIndex, null) > 0;
}
public Cursor getAllEntries () {
return db.query(DATABASE_TABLEnew String[] {KEY_ID, KEY_NAME},
null, null, null, null, null);
}
public MyObject getEntry(long _rowIndex) {
MyObjectobjectInstance = new MyObject();
// TODO Return a cursor to a row from the database and
// use the values to populate an instance of MyObject
return objectInstance;
}
public int updateEntry(long _rowIndex, MyObject _myObject) {
String where = KEY_ID + “=” + _rowIndex;
Content ValuescontentValues = new ContentValues();
// TODO fill in the ContentValue based on the new object
return db.update(DATABASE_TABLE, contentValues, where, null);
}
private static class myDbHelper extends SQLiteOpenHelper {
super(context, name, factory, version);
}
// Called when no database exists in
// disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that
// the version of the database on disk needs to be upgraded to
// the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
int _newVersion) {
// Log the version upgrade.
Log.w(“TaskDBAdapter”, “Upgrading from version “ +
_oldVersion + “ to “ +
_newVersion +
“, which will destroy all old data”);
// Upgrade the existing database to conform to the new version.
// Multiple previous versions can be handled by comparing
// _oldVersion and _newVersion values.
// The simplest case is to drop the old table and create a
// new one.
_db.execSQL(“DROP TABLE IF EXISTS “ + DATABASE_TABLE);
// Create a new one.
onCreate(_db);
}
}
}

Using the SQLiteOpenHelper

SQLiteOpenHelperis an abstract class that wraps up the best practice pattern for creating, opening,and upgrading databases. By implementing and using anSQLiteOpenHelper, you hide the logic used to decide if a database needs to be created or upgraded before it’s opened.
The code snippet above shows how to extend the SQLiteOpenHelperclass by overriding the constructor,onCreate, and onUpgrademethods to handle the creation of a new database and upgrading to a new version, respectively.
In the previous example, onUpgradesimply drops the existing table and replaces it with the new definition. In practice, a better solution is to migrate existing data into the new table.To use an implementation of the helper class, create a new instance, passing in the context, database name, current version, and a CursorFactory(if you’re using one)
Call getReadableDatabase or getWriteableDatabase to open and return a readable/writable instance of the database.
A call to getWriteableDatabasecan fail because of disk space or permission issues, so it’s good practice to provide fallback to the getReadableDatabasemethod as shown below:
dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabasedb;
try {
db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex){
db = dbHelper.getReadableDatabase();
}
Behind the scenes, if the database doesn’t exist, the helper executes its onCreatehandler. If the database version has changed, the onUpgradehandler will fi re. In both cases, the get <read/write> ableDatabase call will return the existing, newly created, or upgraded database as appropriate.

Opening and Creating Databases without the SQLiteHelper

You can create and open databases without using the SQLiteHelperclass with the openOrCreateDatabasemethod on the application Context.
Setting up a database is a two-step process. First, call openOrCreateDatabaseto create the new database.Then, call execSQLon the resulting database instance to run the SQL commands that will create your tables and their relationships. The general process is shown in the snippet below:
private static final String DATABASE_NAME = “myDatabase.db”;
private static final String DATABASE_TABLE = “mainTable”;
private static final String DATABASE_CREATE =
“create table “ + DATABASE_TABLE +
“ ( _id integer primary key autoincrement,” +
“column_one text not null);”;
SQLiteDatabasemyDatabase;
private void createDatabase() {
myDatabase = openOrCreateDatabase(DATABASE_
NAME, Context.MODE_PRIVATE, null);
myDatabase.execSQL(DATABASE_
CREATE); }

Querying Your Database

All database queries are returned as a Cursor to a result set. This lets Android manage resources more efficiently by retrieving and releasing row and column values on demand.
To execute a query on a database, use the query method on the database object, 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 stored in 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” fi lter 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 to the returned rows The following skeleton code shows snippets for returning some, and all, of the rows in a particular table:
// 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);
In practice, it’s often useful to abstract these query commands within an adapter class to simplify data access.

Extracting Results from a Cursor

To extract actual values from a result Cursor, fi rst use the moveTo <location> methods described previously to position the Cursor at the correct row of the result set.
With the Cursor at the desired row, use the type-safe getmethods (passing in a column index) to return the value stored at the current row for the specified column, as shown in the following snippet:
String columnValue = myResult.getString(columnIndex);
Database implementations should publish static constants that provide the column indexes using more easily recognizable variables based on the column names. They are generally exposed within a database adapter as described previously.
The following example shows how to iterate over a result cursor, extracting and summing a column offl oats:
int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query(“GoldHoards”, null, null, null, null,
null, null
);
floattotalHoard = 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());
}
floataverageHoard = totalHoard / myGold.getCount();
Because SQLite database columns are loosely typed, you can cast individual values into valid types as required. For example, values stored as floats can be read back as Strings.

Adding, Updating, and Removing Rows

The SQLiteDatabaseclass exposes specialized insert, delete, and update methods to encapsulate the SQL statements required to perform these actions. Nonetheless, the execSQLmethod lets you execute any valid SQL on your database tables should you want to execute these operations manually. Any time you modify the underlying database values, you should call refreshQueryon any Cursors that currently have a view on the table

Inserting New Rows

To create a new row, construct a ContentValuesobject, and use its put methods to supply values for each column. Insert the new row by passing the Content Values object into the insert method called on the target database object — along with the table name — as shown in the snippet below:
// Create a new row of values to insert.
ContentValuesnewValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);
Create a new ContentValuesobject, using the put methods to assign new values to each column you want to update. Call update on the database object, passing in the table name, the updated Content Values object, and a where statement that returns the row(s) to update. The update process is demonstrated in the snippet below:
// Define the updated row content.
ContentValuesupdatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + “=” + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE, updatedValues, where, null);

Deleting Rows

To delete a row, simply call delete on your database object, specifying the table name and a where clause that returns the rows you want to delete, as shown in the code below:
myDatabase.delete(DATABASE_TABLE, KEY_ID + “=” + rowId, null);

What is Exception in android ?

What is Exception in android....

There are three different situations that cause exceptions to be thrown: Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.
Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.
Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a halt.
Before you begin to explore Android, you will need to be able to get information from your app and deal with errors.
Following Exception are occurred in android applications-

Exception Handling

Before you begin to explore Android, you will need to be able to get information from your app and deal with errors.There is LogCat Android tool for exception handling. Once you have your “Hello World” app running , you can start learning about handling errors and getting debug information.
To begin, let’s add a log message to your Hello World application:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
}
After entering the line of code, press Ctrl+Shift+O (organise imports) to import the android.util.Log class. The call to Log.i() creates an info log message. The first parameter is a tag, typically the name of your app, which you can use later to filter out specific log messages. The second parameter is the message to log.
To view the message, you will need to open the LogCat view in Eclipse. Click Window > Show View > Other > Android > LogCat > OK. Once open, you can run the app and watch the view. You will see a lot of messages from various parts of the Android system (OS and apps). Your message will come out in there somewhere! To make it easier to see just your message, click the + sign on the top right of the LogCat view, then fill in the dialog as follows, then click OK: This will create a new tab in your LogCat view titled “HelloWorld” which will only display log messages tagged as “HelloWorld”, and when messages appear in this tab while it is unfocused, it will display a count of unread messages in the tab title.
Log messages can be one of several types: verbose (V), debug (D), info (I), warning (W), or error (E). You can click the corresponding letter in the top bar of the LogCat view to filter by that type of message or above. These are in increasing order of importance, so if you choose to see debug and above, you will also see info, warning, and error messages. Similarly, the Log class has methods for each type of message, e.g. Log.d() for debug.
Right, so you now have an easy way of displaying information from your application without having to worry about adding breakpoints and inspecting variables. Now let’s look at handling errors. To see how an error is naturally handled in Android, let’s create one in our app:
Now let’s look at handling errors. To see how an error is naturally handled in Android, let’s create one in our app:
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
String test = null;
if (test.equals("hello")) Log.i("HelloWorld", "The test string is hello");
Eclipse will actually warn you about the impending doom, but since we’re too clever for that, let’s go ahead and run our app anyway. Suddenly, we are faced with the infamous “Force close” dialog:
At this point, it will be useful to know that there are two main reasons for a Force Close dialog: an unhandled exception (like this one), or an unresponsive app (perhaps stuck in an infinite loop or using too much CPU for too long). What went wrong? Well, our “HelloWorld” LogCat tab shows nothing, but the “Log” tab shows an error with a stack trace. Helpful, but that might get lost in the sea of log messages, so let’s add some error handling to our app:
Log.i("HelloWorld", "Hello LogCat!");
// LogCat message
try {
String test = null;
if (test.equals("hello")) Log.i("HelloWorld",
"The test string is hello");
catch (Exception e) {
// handle any errors
Log.e("HelloWorld", "Error in activity", e);
// log the error
// Also let the user know something went wrong
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
The try-catch block of code is standard Java exception handling. We log the error to LogCat in the catch block, and also display a Toast message to the user to show that there was an error. Now, when you run the app, you will see a notification come up about a NullPointerException, alerting you that something went wrong. This prompts you to look at your LogCat output, where the spilled guts of an exception are awaiting your postmortem. Since we have consumed the exception, no Force Close dialog appears. I recommend surrounding the entire code block in the onCreate() method with a try-catch block like this to avoid Force Closes entirely. For more complex applications, there will be several places where you will need to surround your code with try-catch blocks
In summary, Android provides an easy way to log messages to a “console” (which in this case is LogCat). It is important to handle all exceptions thrown by your app (including RuntimeExceptions) to avoid Force Close dialogs. A good way to do this is to surround all executing code with a try-catch block, tag your messages and errors, log them to LogCat, and also present the user with a message about the error (using a Toast). Once you have this base covered, you can begin to code more freely and you will spend a lot less time tracking down errors and Force Closes.

Hello world first application of android

To run the Hello World application, you need to install at least one Android platform in your SDK environment. If you have not already performed this step, you need to do it now.
To install a platform in Eclipse:
  • In the Android SDK and AVD Manager, choose Available Packages in the left panel.
  • In the right panel, expand the Android Repository list to display the components available for installation.
  • Select at least one platform to install, and click Install Selected. If you aren't sure which platform to install, use the latest version.

Create an AVD

In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD:
  • In Eclipse, select Window > Android SDK and AVD Manager.
  • Select Virtual Devices in the left panel.
  • Click New.... The Create New AVD dialog appears.
  • Type the name of the AVD, such as "my_avd".
  • Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.3.3) you want to run on the emulator. For this tutorial, choose the latest platform that you have installed and ignore the rest of the fields.
  • Click Create AVD.

Create a New Android Project

After you've created an AVD you can move to the next step and start a new Android project in Eclipse.
  • In Eclipse, select File > New > Project.... If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available.)
  • Select "Android Project" and click Next


Fill in the project details with the following values:
  • Project name: HelloAndroid
  • Build Target: Select a platform version that is equal to or lower than the target you chose for your AVD.
  • Application name: Hello, Android
  • Package name: com.example.helloandroid (or your own private namespace)
  • Create Activity: HelloAndroid
  • Click Finish.


    Here is a description of each field:
Project Name
This is the Eclipse project name — the name of the directory that contains the project files.
Build Target
This is the version of the Android SDK that you're using to build your application. For example, if you choose Android 2.1, your application will be compiled against the Android 2.1 platform library. The target you choose here does not have to match the target you chose for your AVD; however, the target must be equal to or lower than the target you chose for your AVD. Android applications are forward-compatible, which means an application will run on the platform against which it is built as well as all platforms that are released in the future. For example, an application that is built against the 2.1 platform library will run normally on an AVD or device that is running the 2.3.3. The reverse is not true.
Application Name
This is the human-readable title for your application — the name that appears on the Android device.
Package Name
This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity is generated. Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.

Create Activity
This is the name for the class stub that is generated by the plugin. This is a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.
Min SDK Version
This value specifies the minimum API Level on which your application will run. The Min SDK Version should be the same as the Build Target you chose. For example, if the Build Target is Android 2.1, then the Min SDK Version should be 7 or lower (it can never be higher than 7). For more information, see Android API Levels. 

Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files are generated and stored.
Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid). It should look like this:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Construct the UI

Take a look at the revised code below and then make the same changes to your HelloAndroid class. The bold items are lines that have been added.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}
Tip: An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you. You may have to expand the import statements in your code for this to work.
An Android user interface is composed of hierarchies of objects called Views. A View is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subclass of the View class and the subclass that handles text is TextView.
In this change, you create a TextView with the class constructor, which accepts an Android Context instance as its parameter. A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. The Activity class inherits from Context, and because your HelloAndroid class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the TextView.
Next, you define the text content with setText().
Finally, you pass the TextView to setContentView() in order to display it as the content for the Activity UI. If your Activity doesn't call this method, then no UI is present and the system will display a blank screen.

Run the Application

The Eclipse plugin makes it easy to run your applications:
  • Select Run > Run.
  • Select "Android Application".
The Eclipse plugin automatically creates a new run configuration for your project and then launches the Android Emulator. Depending on your environment, the Android emulator might take several minutes to boot fully, so please be patient. When the emulator is booted, the Eclipse plugin installs your application and launches the default Activity. You should now see something like this:


Friday, 24 February 2017

User interface inUser Interface In an Android

User Interface

In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a descendant of the View class.
View objects are the basic units of user interface expression on the Android platform. The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons. The ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, tabular and relative.
A View object is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. A View object handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides. As an object in the user interface, a View is also a point of interaction for the user and the receiver of the interaction events.

View Hierarchy

On the Android platform, you define an Activity's UI using a hierarchy of View and ViewGroup nodes, as shown in the diagram below. This hierarchy tree can be as simple or complex as you need it to be, and you can build it up using Android's set of predefined widgets and layouts, or with custom Views that you create yourself.



In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the setContentView() method and pass a reference to the root node object. The Android system receives this reference and uses it to invalidate, measure, and draw the tree. The root node of the hierarchy requests that its child nodes draw themselves — in turn, each view group node is responsible for calling upon each of its own child views to draw themselves. The children may request a size and location within the parent, but the parent object has the final decision on where how big each child can be. Android parses the elements of your layout in-order (from the top of the hierarchy tree), instantiating the Views and adding them to their parent(s). Because these are drawn in-order, if there are elements that overlap positions, the last one to be drawn will lie on top of others previously drawn to that space.
For a more detailed discussion on how view hierarchies are measured and drawn, read How Android Draws Views.

Layout

The most common way to define your layout and express the view hierarchy is with an XML layout file. XML offers a human-readable structure for the layout, much like HTML. Each element in XML is either a View or ViewGroup object (or descendant thereof). View objects are leaves in the tree, ViewGroup objects are branches in the tree (see the View Hierarchy figure above).
The name of an XML element is respective to the Java class that it represents. So a <TextView> element creates a TextView in your UI, and a <LinearLayout> element creates a LinearLayout view group. When you load a layout resource, the Android system initializes these run-time objects, corresponding to the elements in your layout.
For example, a simple vertical layout with a text view and a button looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/
android"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
Notice that the LinearLayout element contains both the TextView and the Button. You can nest another LinearLayout (or other type of view group) inside here, to lengthen the view hierarchy and create a more complex layout.
For more on building a UI layout, read XML Layouts.
Tip: You can also draw View and ViewGroups objects in Java code, using the addView(View) methods to dynamically insert new View and ViewGroup objects.
There are a variety of ways in which you can layout your views. Using more and different kinds of view groups, you can structure child views and view groups in an infinite number of ways. Some pre-defined view groups offered by Android (called layouts) include LinearLayout, RelativeLayout, TableLayout, GridLayout and others. Each offers a unique set of layout parameters that are used to define the positions of child views and layout structure.
To learn about some of the different kinds of view groups used for a layout, read Common Layout Objects.

Widgets

A widget is a View object that serves as an interface for interaction with the user. Android provides a set of fully implemented widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI. Some widgets provided by Android are more complex, like a date picker, a clock, and zoom controls. But you're not limited to the kinds of widgets provided by the Android platform. If you'd like to do something more customized and create your own actionable elements, you can, by defining your own View object or by extending and combining existing widgets.
For a list of the widgets provided by Android, see the android.widget package.
Input Events
Once you've added some Views/widgets to the UI, you probably want to know about the user's interaction with them, so you can perform actions. To be informed of user input events, you need to do one of two things:
  • Define an event listener and register it with the View. More often than not, this is how you'll listen for events. The View class contains a collection of nested interfaces named On <something> Listener, each with a callback method called On<something>(). For example, View.OnClickListener (for handling "clicks" on a View), View.OnTouchListener (for handling touch screen events in a View), and View.OnKeyListener (for handling device key presses within a View). So if you want your View to be notified when it is "clicked" (such as when a button is selected), implement OnClickListener and define its onClick() callback method (where you perform the action upon click), and register it to the View with setOnClickListener().
  • Override an existing callback method for the View. This is what you should do when you've implemented your own View class and want to listen for specific events that occur within it. Example events you can handle include when the screen is touched (onTouchEvent()), when the trackball is moved (onTrackballEvent()), or when a key on the device is pressed (onKeyDown()). This allows you to define the default behavior for each event inside your custom View and determine whether the event should be passed on to some other child View. Again, these are callbacks to the View class, so your only chance to define them is when you build a custom component.
Continue reading about handling user interaction with Views in the Input Events document.

Menus

Application menus are another important part of an application's UI. Menus offers a reliable interface that reveals application functions and settings. The most common application menu is revealed by pressing the MENU key on the device. However, you can also add Context Menus, which may be revealed when the user presses and holds down on an item.
Menus are also structured using a View hierarchy, but you don't define this structure yourself. Instead, you define the onCreateOptionsMenu() or onCreateContextMenu() callback methods for your Activity and declare the items that you want to include in your menu. At the appropriate time, Android will automatically create the necessary View hierarchy for the menu and draw each of your menu items in it.
Menus also handle their own events, so there's no need to register event listeners on the items in your menu. When an item in your menu is selected, the onOptionsItemSelected() or onContextItemSelected() method will be called by the framework.
And just like your application layout, you have the option to declare the items for you menu in an XML file.

Monday, 20 February 2017

How to create emulator in ADT eclipse

Using the Emulator

Create an Android Emulator Device

The Android tools include an emulator. The emulator behaves like a real Android device in most cases and allows you to test your application without having a real device. You can emulate one or several devices with different configurations. Each configuration is defined via an "Android Virtual Device" (AVD).
To define an AVD open the "AVD Manager" via Windows → AVD Manager and press "New".
Enter The Following Details-



At the end press the button "Create AVD".This will create the device and display it under the "Virtual devices". To test if your setup is correct, select your device and press "Start".
Your device will be started.




Performance

Try to use a smaller resolution for your emulator as for example HVGA. The emulator gets slower the more pixels its needs to render as it is using software rendering.
Also if you have sufficient memory on your computer, add at least 1 GB of memory to your emulator. This is the value "Device ram size" during the creation of the AVD.

Installation of ADT

You have to install Eclipse IDE to develop Android applications.

After that install ADT (android development kit) plugin in Eclipse IDE.

ADT Plugin for Eclipse

Android Development Tools (ADT) is a plugin for the Eclipse IDE that is designed to give you a powerful, integrated environment in which to build Android applications.
ADT extends the capabilities of Eclipse to let you quickly set up new Android projects, create an application UI, add components based on the Android Framework API, debug your applications using the Android SDK tools, and even export signed (or unsigned) .apk files in order to distribute your application.

Installing ADT Plugin

The sections below provide instructions on how to download and install ADT into your Eclipse environment

Configuring the ADT Plugin

After you've successfully downloaded the ADT as described above, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory:

Android development tools

Android Development Tools

The Android SDK includes several tools and utilities to help you create, test, and debug your projects. A detailed examination of each developer tool is outside the scope of this book, but it’s worth briefl y reviewing what’s available. For more detail than is included here, check out the Android documentation at: http://code.google.com/android/intro/tools.html
As mentioned earlier, the ADT plug-in conveniently incorporates most of these tools into the Eclipse IDE, where you can access them from the DDMS perspective, including:
  • The Android Emulator An implementation of the Android virtual machine designed to run on your development computer. You can use the emulator to test and debug your android applications.
  • Dalvik Debug Monitoring Service (DDMS) Use the DDMS perspective to monitor and control theDalvik virtual machines on which you’re debugging your applications.
  • Android Asset Packaging Tool (AAPT) Constructs the distributable Android package files (.apk).
  • Android Debug Bridge (ADB) The ADB is a client-server application that provides a link to a running emulator. It lets you copy fi les, install compiled application packages (.apk), and run shell commands.
    The following additional tools are also available:
  • SQLite3 A database tool that you can use to access the SQLite database fi les created and used by Android
  • TraceviewGraphical analysis tool for viewing the trace logs from your Android application
  • MkSDCardCreates an SDCard disk image that can be used by the emulator to simulate an external storage card.
  • dxConverts Java .class bytecode into Android .dexbytecode.
  • activityCreatorScript that builds Ant build fi les that you can then use to compile your Android applications without the ADT plug-in
Let’s take a look at some of the more important tools in more detail.

The Android Emulator

The emulator is the perfect tool for testing and debugging your applications, particularly if you don’t have a real device (or don’t want to risk it) for experimentation.



The emulator is an implementation of the Dalvik virtual machine, making it as valid a platform for running Android applications as any Android phone. Because it’s decoupled from any particular hardware, it’s an excellent baseline to use for testing your applications
A number of alternative user interfaces are available to represent different hardware configurations,each with different screen sizes, resolutions, orientations, and hardware features to simulate a variety of mobile device types.
Full network connectivity is provided along with the ability to tweak the Internet connection speed and latency while debugging your applications. You can also simulate placing and receiving voice calls and SMS messages.
The ADT plug-in integrates the emulator into Eclipse so that it’s launched automatically when you run or debug your projects. If you aren’t using the plug-in or want to use the emulator outside of Eclipse, you can telnet into the emulator and control it from its console. For more details on controlling the emulator, check the documentation at http://code.google.com/android/reference/
emulator.html.
At this stage, the emulator doesn’t implement all the mobile hardware features supported by Android,including the camera, vibration, LEDs, actual phone calls, the accelerometer, USB connections,Bluetooth, audio capture, battery charge level, and SD card insertion/ejection.

Dalvik Debug Monitor Service (DDMS)

The emulator lets you see how your application will look, behave, and interact, but to really see what’s happening under the surface, you need the DDMS. The Dalvik Debug Monitoring Service is a powerful debugging tool that lets you interrogate active processes, view the stack and heap, watch and pause active threads, and explore the filesystem of any active emulator.



The DDMS perspective in Eclipse also provides simplified access to screen captures of the emulator and the logs generated by LogCat.
If you’re using the ADT plug-in, the DDMS is fully integrated into Eclipse and is available from the DDMS perspective. If you aren’t using the plug-in or Eclipse, you can run DDMS from the command line, and it will automatically connect to any emulator that’s running.

The Android Debug Bridge (ADB)

The Android debug bridge (ADB) is a client-service application that lets you connect with an Android Emulator or device. It’s made up of three components: a daemon running on the emulator, a service that runs on your development hardware, and client applications (like the DDMS) that communicate with the daemon through the service.



As a communications conduit between your development hardware and the Android device/emulator,the ADB lets you install applications, push and pull fi les, and run shell commands on the target device.Using the device shell, you can change logging settings, and query or modify SQLite databases available on the device.
The ADT tool automates and simplifies a lot of the usual interaction with the ADB, including application installation and update, log fi les, and fi le transfer (through the DDMS perspective).To learn more about what you can do with the ADB, check out the documentation at http://code.google.com/android/reference/
adb.html.

Thursday, 16 February 2017

Tools required for android programming

Tool Required to learn Android Development :-

The Eclipse IDE.
The Android SDK.
The Android Development Tools(ADT) Eclipse plugin

System Requirements

The sections below describe the system and software requirements for developing Android applications using the Android SDK.

Supported Operating Systems

  • Windows XP (32-bit), Vista (32- or 64-bit), or Windows 7 (32- or 64-bit)
  • Mac OS X 10.5.8 or later (x86 only)
  • Linux (tested on Ubuntu Linux, Lucid Lynx)
  • GNU C Library (glibc) 2.7 or later is required
  • On Ubuntu Linux, version 8.04 or later is required
  • 64-bit distributions must be capable of running 32-bit applications. For information about how to add support for 32-bit applications.

Wednesday, 15 February 2017

Android Application Architecture...

Android Application Architecture

1.AndroidManifest.xml

An Android application is described in the file AndroidManifest.xml. This file must declare all Activities, Services, BroadcastReceivers and ContentProvider of the application. It must also contain the required permissions for the application. AndroidManifest.xml can be thought as the deployment descriptor for an Android application.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=
"http://schemas.android.com/apk/res/
android"

package="Tutorial.android.
temperature"
 android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label=
@string/app_name">
<activity android:name=".Convert"
android:label="@string/app_name"
<intent-filter>
<action android:name="android.intent.action.
MAIN" 
/>
<category android:name="android.intent.
category.
LAUNCHER"
 />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="9" />
</manifest>



Here is the description for all tags :-
<manifest>
This is the root node of each AndroisManifest.xml. It contains the package-attribute, which points to any package in out Activity. Other Activities-path will base relative to its value.
<manifest xmlns:android="http://schemas.android.com/
apk/res/android" package="org.anddev.android.smstretcher">
<uses-permission>
Describes a security permission, which your package must be granted in order for it to operate correctly (i.e. when you want to send SMS or use the Phone-Contacts). The permissions get granted by the user during installation of your application. Quantity:
<uses-permission android:name=" android.permission.RECEIVE_SMS"/>
<permission>
Declares a security permission that can be used to restrict which applications can access components or features in your (or another) package. Quantity:
<instrumentation>
Declares the code of an instrumentation component that is available to test the functionality of this or another package. See Instrumentation for more details. Quantity
<application>
Root element containing declarations of the application-level components contained in the package. This element can also include global and/or default attributes for the application, such as a label, icon, theme, required permission, etc. Quantity: 0 or 1.
<application android:icon="@drawable/icon">
You can place 0+of each of the following children:
<activity>
An Activity is the primary thing for an application to interact with the user. The initial screen the user sees when launching an application is an activity, and most other screens they use will be implemented as separate activities declared with additional activity tags.
<activity android:name=".Welcome"
android:label="@string/app_name">
Note: Every Activity must have an <activity> tag in the manifest whether it is exposed to the world or intended for use only within its own package. If an Activity has no matching tag in the manifest, you won't be able to launch it. Optionally, to support late runtime lookup, you can include 1+ <intent-filter> elements to describe the actions the activity supports.
<intent-filter>
Declares what kind of Intents a component supports. In addition to the various kinds of values that can be specified under this element, attributes can be given here to supply a unique label, icon, and other information for the action being described.
<intent-filter>
<action>
An action-type that the component supports. Example:
<action android:name="android.intent.action.MAIN" />
<category>
A category-type that the component supports. Example:
<category android:name="android.intent.category.
LAUNCHER" />
<data>
An MIME type, URI scheme, URI authority, or URI path that the component supports. You can also associate 1+ pieces of meta-data with your activity:
<meta-data>
Adds a new piece of meta data to the activity, which clients can retrieve through ComponentInfo.metaData.
<receiver>
An IntentReceiver allows an application to be told about changes to data or actions that happen, even if it is not currently running. As with the activity tag, you can optionally include 1+ <intent-filter> elements that the receiver supports or <meta-data> values, just all the same as with <activity>.
<receiver android:name=".SMSReceiver">
<service>
A Service is a component that can run in the background for an arbitrary amount of time. As with the activity tag, you can optionally include one or more <intent-filter> elements that the service supports or <meta-data> values; see the activity's <intent-filter> and <meta-data> descriptions for more information.
<provider>
A ContentProvider is a component that manages persistent data and publishes it for access by other applications. You can also optionally attach one or more <meta-data> values, as described in the activity's <meta-data> description. Of course all <tags> have to be </closed> or closed <directly/>.
The package attribute defines the base package for the following Java elements. It also must be unique as the Android Marketplace only allows application for a specific package once. Therefore a good habit is to use your reverse domain name as a package to avoid collisions with other developers.
android:versionName and android:versionCode specify the version of your application. versionName is what the user sees and can be any string. versionCode must be an integer and the Android Market uses this to determine if you provided a newer version to trigger the update on devices which have your application installed. You typically start with "1" and increase this value by one if you roll-out a new version of your application.
The tag <activity> defines an Activity. An intent filter is registered for this class which defines that this Activity is started once the application starts (action android:name="android.intent.action.MAIN" ). The category definition category android:name="android.intent.category.
LAUNCHER" defines that this application is added to the application directory on the Android device. The @string/app_name value refer to resource files which contain the actual values. This makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications.
The "uses-sdk" part of the "AndroidManifest.xml" defines the minimal SDK version for which your application is valid. This will prevent your application being installed on devices with older SDK versions.

2. R.java, Resources and Assets

The directory gen in an Android project contains generated values. R.java is a generated class which contains references to resources of the res folder in the project. These resources are defined in the res directory and can be values, menus, layouts, icons or pictures or animations. For example a resource can be an image or an XML file which defines strings.
If you create a new resource, the corresponding reference is automatically created in R.java. The references are static int values, the Android system provides methods to access the corresponding resource. For example to access a String with the reference id R.string.yourString use the method getString(R.string.yourString));.
While the directory res contains structured values which are known to the Android platform the directory assets can be used to store any kind of data. In Java you can access this data via the AssetsManager and the method getAssets().

3. Reference to resources in XML files

In your XML files, e.g. your layout files you can refer to other resources via the @ sign. For example if you want to refer to a color you defined as resources you can refer to it via @color/your_id or if you have defined a "hello" string as resource you can access it via @string/hello .

4. Activities and Layouts

The user interface for Activities is defined via layouts. At runtime, layouts are instances of android.view.ViewGroups . The layout defines the UI elements, their properties and their arrangement.
UI elements are based on the class android.view.View . ViewGroup is a subclass of the class View and a layout can contain UI components ( Views ) or other layouts ( ViewGroups ). You should not nestle ViewGroups too deeply as this has a negative impact on performance.
A layout can be defined via Java code or via XML. You typically uses Java code to generate the layout if you don't know the content until runtime; for example if your layout depends on content which you read from the Internet.
XML based layouts are defined via a resource file in the folder /res/layout . This file specifies the ViewGroups , Views , their relationship and their attributes for a specific layout. If a UI element needs to be accessed via Java code you have to give the UI element an unique id via the android:id attribute. To assign a new id to an UI element use @+id/yourvalue . By conversion this will create and assign a new id yourvalue to the corresponding UI element. In your Java code you can later access these UI elements via the method findViewById(R.id.yourvalue) .
Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout definition. It also allows the definition of different layouts for different devices. You can also mix both approaches.

5. Activities and Lifecycle

The operating system controls the life cycle of your application. At any time the Android system may stop or destroy your application, e.g. because of an incoming call. The Android system defines a life cycle for activities via pre-defined methods. The most important methods are:
  • onSaveInstanceState() - called if the activity is stopped. Used to save data so that the activity can restore its states if re-started
  • onPause() - always called if the Activity ends, can be used to release resource or save data
  • onResume() - called if the Activity is re-started, can be used to initialize fields
The activity will also be restarted if a so called "configuration change" happens. A configuration change for example happens if the user changes the orientation of the device (vertical or horizontal). The activity is in this case restarted to enable the Android platform to load different resources for these configuration, e.g. layouts for vertical or horizontal mode. In the emulator you can simulate the change of the orientation via CNTR+F11.
You can avoid a restart of your application for certain configuration changes via the configChanges attribute on your activity definition in your AndroidManifest.xml. The following activity will not be restarted in case of orientation changes or position of the physical keyboard (hidden / visible).
<activity android:name=".ProgressTestActivity"
android:label="@string/app_name"
android:configChanges="orientation|
keyboardHidden|keyboard"

</activity>

6. Context

The class android.content.Context provides the connections to the Android system. It is the interface to global information about the application environment. Context also provides access to Android Services, e.g. theLocation Service. As Activities and Services extend the class Context you can directly access the context via this.