MY mENU


Wednesday, 22 February 2012

Data Base in Android (SQLite)

SQLite Database in Android: SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements. In addition it requires only little memory at runtime (approx. 250KByte). SQLite is available on every Android device. Using an SQLite database in Android does not require any database setup or administration.

Things to consider when dealing with SQLite:
  1. Data type integrity is not maintained in SQLite, you can put a value of a certain data type in a column of another dataype (put string in an integer and vice versa).
  2. Referential integrity is not maintained in SQLite, there is no FOREIGN KEY constraints or JOIN statements.
  3. SQLite Full Unicode support is optional and not installed by default.
You only have to define the SQL statements for creating and updating the database. Afterwards 
the database is automatically managed for you by the Android platform. Access to an SQLite database involves accessing the filesystem. This can be slow. Therefore it is recommended to perform database operations asynchronously, for example via the AsyncTask class. .
- If your application creates a database, this database is saved in the directory DATA/data/APP_NAME/database/filename. The parts of the above directory are constructed based on the following rules. DATA is the path which the Environment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME  is the name you specify in your application code for the database.

SQLite Architecture

 1.Packages: The package Android.database contains all general classes for working with databases. android.database.SQlite contains the SQLite specific classes.

2. SQLiteOpenHelper: To create and upgrade a database in your Android application you usually subclass SQLiteOpenHelper. In the constructor of your subclass you call the super() method of SQLiteOpenHelper specifying the database name and the current database version. In this class you need to override the onCreate() and onUpgrade() methods. 

  1. onCreate(SQLiteDatabase db): invoked when the database is created, this is where we can create tables and columns to them, create views or triggers.
  2. onUpgrade(SQLiteDatabse db, int oldVersion, int newVersion): invoked when we make a modification to the database such as altering, dropping , creating new tables.This method allows you to update the database schema. 
Both methods receive an SQLiteDatabase object as parameter which represents the database. SQLiteOpenHelper provides the methods getReadableDataBase() and getWritableDatabase() to get access to an SQLiteDatabase object; either in read or write mode. The database tables should use the identifier _id for the primary key of the table.

3. SQLiteDatabase: SQLitedatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database. More specifically SQLiteDatabase provides the insert(), update() and delete() methods. In addition it provides the execSQL() method, which allows to execute SQL directly. The object ContentValues allows to define key/values. The "key" represents the table column identifier and the "value" represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries. Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class .

rawQuery() directly accepts an SQL statement as input.
query() provides a structured interface for specifying the SQL query.
SQLiteQueryBuilder is a convenience class that helps to build SQL queries.


4. rawQuery() Example
The following gives an example of a rawQuery() call. the rawQuery method has two parameters:
  1. String query: the select statement.
  2. String[] selection args: the arguments if a WHERE clause is included in the select statement.

      Cursor cursor = getReadableDatabase().
       rawQuery("select * from todo where _id = ?", new String[] { id });

5. query() Example: The following gives an example of a query() call.
return database.query(DATABASE_TABLE,new String[] { KEY_ROWID, KEY_CATEGORY, KEY_SUMMARY, KEY_DESCRIPTION }, null, null, null, null, null); 


The method query() has the following parameters.
Parameters of the query() method
Parameter
Comment
String dbName
The table name to compile the query against.
int[] columnNames
A list of which table columns to return. 
Passing "null" will return all columns.
String whereClause
Where-clause, i.e. filter for the selection 
of data, null will select all data.
String[] selectionArgs
You may include ?s in the "whereClause"".
 These placeholders will get replaced by the 
values from the selectionArgs array.
String[] groupBy
A filter declaring how to group rows, 
null will cause the rows to not be grouped.
String[] having
Filter for the groups, null means no filter.
String[] orderBy
Table columns which will be used to 
order the data, null means no ordering.
If a condition is not required you can pass null, e.g. for the group by clause.
The "whereClause" is specified without the word "where", for example a "where" statement might look like: "_id=19 and summary=?". If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs parameter to the query.

6. Cursor : A query returns a Cursor object . A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory. To get the number of elements of the resulting query use the getCount() method. To move between individual data rows, you can use the moveToFirst() and moveToNext() methods. The isAfterLast() method allows to check if the end of the query result has been reached.

Cursor provides typed get*() methods, e.g. getLong(columnIndex), getString(columnIndex) to access the column data for the current position of the result. The "columnIndex" is the number of the column you are accessing.

Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table. there are some common methdos that you will use with cursors:
  1. boolean moveToNext(): moves the cursor by one record in the result set, returns false if moved past the last row in the result set.
  2. boolean moveToFirst(): moves the cursor to the first row in the result set, returns false if the result set is empty.
  3. boolean moveToPosition(int position): moves the cursor to a certain row index within the boolean result set, returns false if the position is un-reachable
  4. boolean moveToPrevious():moves the cursor to the preevious row in the result set, returns false if the cursor is past the first row.
  5. boolean moveToLast():moves the cursor to the lase row in the result set, returns false if the result set is empty.
there are also some useful methods to check the position of a cursor: boolean isAfterLast(), isBeforeFirst, isFirst,isLast and isNull(columnIndex).

Monday, 20 February 2012

LayOuts in Android

Layout In Android: The layout of an activity can be constructed by a XML file. These files are considered resources as they reside in res/layout folder. Each xml file consists of the declarations of widgets and their containers. The xml file is constructed in a hierarchical way, there is a tag that defines the layout of the widgets, inside this tag there are nested xml tags that define widgets, each widget tag has attributes that define the widget’s properties.  We can divide the layout in 2 ways.

1.  Android provides widgets and layouts class that are used to create the layout.
2. Second way ,You can instantiate layout elements at runtime that means programmatically in java coding.

You could declare your application's default layouts in XML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.  You can change or modify your source code and recompile.


Attributes :-There are many type attributes in XML. View object have some type attributes eg. textSize attribute but every attributes is inherited by any View objects.id attributeed is the the root View class.

1. ID :- ID attributes uniquely identify the View within the tree. This is an XML attribute common to all View objects and you will use it very often. The

                                                  android:id="@+id/my_button"

2. Layout Parameters :-XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides. 


You can specify width and height with exact measurements, though you probably won't want to do this often. More often, you will use one of these constants to set the width or height:
  • wrap_content tells your view to size itself to the dimensions required by its content
  • fill_parent (renamed match_parent in API Level 8) tells your view to become as big as its parent view group will allow.
Common Layout Objects:
The common Layout are:
  1. Linear layout: manages controls in horizontal or vertical way. 
  2. Table layout: manages the controls in a group of columns and rows.
  3. Relative layout: manages the controls relative to one another or to the parent.
  4. Absolute layout: manages the controls in absolute position by coordinates.
  5. Frame layout: manages the controls in a dynamic way.
  6. Scroll layout: manages the controls in a scrollable layout.
1.Frame Layout: its the simplest type of  layout object. It's basically a blank space on your screen that you can later fill with a single object — for example, a picture that you'll swap in and out. All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot specify a different location for a child view. Subsequent child views will simply be drawn over previous ones, partially or totally obscuring them (unless the newer object is transparent). Frame layout is used to display a single view at a time. The view can contain many widgets but only one will appear at a time.

2.Linear Layout: LinearLayout puts all its child elements into a single column or row depending on the android:orientation attribute. Possible values for this attribute are horizontal and vertical. horizontal is the default value. LinearLayout can be nested to achieve more complex layouts.When dealing with Linear layout there are five properties that we can deal with:

  1. Oientation.
  2. Fill model.
  3. Weight
  4. Gravity.
  5. padding.
Orientaition: Orientation property determines whether the controls would be put in a horizontal way like in a row or in a vertical way like a column. The layout orientation is set by the property android:orientation
Fill Model:
The widgets inside linear layout have width and height properties. These properties can have three values:

  1. A numeric value in pixels or inches that gives the width or height properties an absolute value. 
  2. They can have the value wrap_content meaning the widget should occupy it’s natural size unless there is no space then android can use word wrap to make the widget fit.
  3. They can have the value fill_parent meaning the widget should occupy all the available space of the closing container.
To set the fill model programmitaclly use this code:
1Button b=(Button)findViewById(R.id.btn);
2b.setWidth(LayoutParams.WRAP_CONTENT);
3b.setHeight(LayoutParams.FILL_PARENT);
Weight:
The weight property determines the ratio by which controls share free space. For example if we have two buttons and the weight of both is set to 1 (this is the default value) then the free space will be divided equally between them. But if the value of the weight of one of them is 2 and the other is one, then the first button will occupy space half as that occupied by the second and so on. 

Example code:

<linearlayout android:id="@+id/mainlayout" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Linear Layout">
<button
android:layout_height="fill_parent"
android:layout_weight="1" 
android:layout_width="fill_parent" 
android:text="weight set to 2"
/>
<button
android:id="@+id/btn"
android:layout_height="fill_parent" 
android:layout_weight="1" 
android:layout_width="fill_parent" 
android:text="weight set to 1"
/>
</textview></linearlayout>


3.Table Layout: positions its children into rows and columns. TableLayout containers do not display border lines for their rows, columns, or cells. The table will have as many columns as the row with the most cells. A table can leave cells empty, but cells cannot span columns, as they can in HTML.
 TableRow objects are the child views of a TableLayout.

4.Relative Layout: it allow to position the widget relative to each other. This allows for complex layouts. A simple usage for RelativeLayout is if you want to center a single component.You can place a widget in a position relative to another widget’s position or relative to the container.
As we said in relative layout widgets can be placed
  1. Relative to the container.
  2. Relative to other widgets
Relative to the container :
The widgets are placed in position relative to their container like by setting the following properties:
  • android:layout_alignParentTop|Bottom|Right|Left to true. This aligns the Top|Bottom|Right|Left side of the widget with the Top|Bottom|Right|Left side of the container.
  • android:layout_centerVertical: the widget should be positioned vertically in the center of the container.
  • android:layout_centerHorizontal: the widget should be positioned horizontally in the center of the container.
  • android:layout_centerInParent: the widget should be positioned both vertically and horizontally in the middle of the container.
Position Relative to other widgets’ positions:
  • There are four properties that determine the position of the widget in relation to other widgets:
    • android:layout_above: the widget should be placed above the referenced widget. 
    • android:layout_below: the widget should be placed below the referenced widget.
    • android:layout_toRightOf: the widget should be placed to the right of the referenced widget.
    • android:layout_toLeftOf: the widget should be placed above the referenced widget.
Notes:
  • When you reference a widget in a relative layout property, you must assure that this widget has been already defined in the layout.
  • When you use the value fill_parent to assign athe height of a widget in a relative container, it could occupy all the available space so that any further controls defined in the xml file would not appear.
  • When referencing another control in relative layout property, we use the notation “@id/widgetID”.
5.Grid Layout : It was introduced with Android 4.0. This layout allows you to organize a view into a Grid. GridLayout separates its drawing area into: rows, columns, and cells. You can specify how many columns you want for define for each View in which row and column it should be placed and how many columns and rows it should use. If not specified GridLayout uses defaults, e.g. one column, one row and the position of a View depends on the order of the declaration of the View.


6.Absolute Layout: Absolute layout lays widgets by specifying their exact X and Y positions. In android the origin (0,0) coordinate is located at the top left of the screen. Absolute layout is defiend in XML as <AbsoluteLayout>. By default, if you define any control in absolute layout without defining it’s x,y coordinates, it will be placed in the origin point at (x,y)=(0,0), if you define x,y values that are too large, the widget will not appear on the screen.

User Interface in Android


User Interface in Android :-


 View and ViewGroup objects is used for user interface in andriod. View class is basic unit. Widgets class which offer fully implemented UI objects in android like button and text field etc which is the sub class of View class. Layouts class provides different kinds of layout architecture, like linear, tabular and relative which is the sub class of ViewGroup class.View is also a point of interaction for the user and the receiver of the interaction events. setContentView() method is used to  pass a reference to the root node object that is called by the Activity.
XML is used to store and transfer the data and provides layout that is readable by the human much like HTML.. View objects are leaves in the tree, ViewGroup objects are branches in the tree .



You can also draw View and ViewGroups objects in Java code, using the addView(View) methods to dynamically insert new View and ViewGroup objects.
Widgets :-  Android provides a set of fully implemented widgets, like buttons, checkboxes, and text-entry fields. It is a View object that serves as an interface for interaction with the user. date picker, a clock, and zoom controls are some other  widget. android.widget package provides several method and class for this purpose.



Layout:-Layout  is the process of planning and arranging in detail something that is human readable form.<LinearLayout> element is used to creates a Linear Layout view group and TextView  element creates a TextView. When you load a layout resource, the Android system initializes these run-time objects, corresponding to the elements in your layout.


Menus:-  Menus offers a reliable interface that reveals application functions and settings.Android will automatically create the necessary View hierarchy for the menu and draw each of your menu items in it. You do not define this structure yourself onCreateOptionsMenu() or onCreateContextMenu()  methods for your Activity and declare the items that you want to include in your menu.

Adapters:-
Adapters is used to bind your view to an external source of data. AdapterView is used for this purpose.