Pages

Showing posts with label introduction. Show all posts
Showing posts with label introduction. Show all posts

Monday, March 21, 2016

Introduction to Android

Android is a platform for developing mobile application that supports most of the java standard edition (J2SE) except for Abstract Windows Toolkit (AWT) and Swing so if you are a java developer you won’t feel strange when developing for android.

In this post we’re going to demonstrate some of the features of the Android platform so that any developer from any background can have a look on what Android really is .
  1. Java code is interpreted not compiled (see this link to know the difference) and it need the Java Virtual Machine JVM to do so. Android provides its own virtual machine called the Dalvik Virtual machine
  2. The dalvik VM takes the generated java class files and combine them in to Dalvik executable (.dex) files that saves storage space (uncompressed) by half compared to similar JAR file.
  3. Google did not use a Just In Time (JIT) debugger because of the fact that many of android’s core libraries and APIs are written in C and C++ such as the graphics API.
  4. The final executable code of Android is not java byte code it is .dex files.
The Android Software Stack


This picture describes the Android software stack that can be described briefly as a Linux Kernel and C/C++ libraries exposed through an application framework that provides services for and management of runtime and applications.

The elements of the Android software stack are:
 
  1.  Linux Kernel: version 2.6, provides abstraction between the hardware and the rest of the stack, responsible for device drivers (Camera , Wi Fi, etc…), resources management , power management, security and net working
  2.  C/C++ Libraries: such as SQL lite, Graphics libraries such as OpenGL, media library for Audio and Vide playback
  3. The Android Runtime: includes Core libraries and the Dalvik VM.
    The Core libraries provide most of java libraries + additional Android libraries.
    The Dalvik VM is optimized to run multiple instances of VMs. As Java applications access the core libraries each application has it’s own VM
  4.  The Android Application Framework: Provides classes required to develop an Android application and abstraction between hardware access. the Android Java API’s main library include telephony, content providers (data), resources, locations and UI.
  5. Application Layer: all Android applications(native or third party) are built on the application layer using the same API.
The Android Application structure:


Android architecture encourages component reuse allowing you to publish and share activities, services and data between applications with security restrictions defined by you. This enables developers to present new UI for out of the box components such as the phone dialer or contact manager, or adding new functionalities to them.

The basis of the Android applications are:
  • Activity Manager: which controls the life cycle of the activities, activities can be compared to the windows or web forms they carry the controls (views) that construct the interface, an activity represents a single screen.
  • Views: the UI components that construct the interface. They can be compared to the swing or windows forms controls
  • Notification Manger: provides a consistent mechanism to notify or alert users.
  • Content Providers: lets applications to share data between them.
  • Resources Manager: much like the ASP.NET resources concept. Enables the developer to store resources such as strings or images
Read More..

Tuesday, March 15, 2016

Using Themes and Styles in Android

In web design we have the concept of Styles and Themes. Styles like Cascading Style Sheets (CSS) define the values of the web controls attributes such as width, heigth, font color, background and so on. A style can be applied on several controls in several web pages.

Themes are used to group a set of styles to be applied on the whole web application. Themes (or sometimes skins) define the look of all control within the application.

Android introduces similar concepts by using Styles and Themes. A Style can be applied to views individually while a Theme is applied to a whole activity.

Styles:

Styles are defined as xml resources files in res/values directory of your project.

consider this definition of a TextView:
<TextView android_layout_width="fill_parent" 
android_layout_height="wrap_content"
android_textColor="#FFF"
android_typeface="monospace"
android_text="First Text View"
android_background="#00F"
/>


this defines a text view with width and height equal to wrap_content, white font color, font type "monospace" and blue back ground.

if we want to have the same results using a style: we first create a xml file (call it styles.xml) in res/values directory and it would be like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="BlueLabel">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:typeface">monospace</item>
<item name="android:background">#00F</item>
<item name="android:textColor">#FFF</item>
</style>
</resources>

then redefine the TextView like this:
<TextView android_text="First Text View"
style="@style/BlueLabel" / >


and you will receive the same results.
the attributes in the <item>tag can be any layout property.

Inheriting Styles:
Styles in Android has an interesting feature which is the ability to inherit styles in a fashion similar to that in CSS. consider this example:

we have a style for a button like this:
<style name="ButtonStyle">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">15px</item>
<item name="android:typeface">serif</item>
</style>


the button will appear like this:

we can make this style inherit from BlueLabel defined previously by adding the parent attribute to the <style*gt; tag:
<style name="ButtonStyle" parent="BlueLabel">
then the button will be like this:
the button inherited the background color from the parent style.
another interesting feature in styles inheritance is the ability to inherit from the platform built-in styles defined in the android.R.style namespace. to know more about the platform styles check this link

or you can type in your editor (Eclipse) android.R.style and let the intelli-sense list you the complete list of platform styles, if you want to use them in your xml just replace the undrscores with a period like this:
Widget_Button becomes @android:style/Widget.Button.

In the previous button style example we will set the parent of the style to be @android:style/Widget.Button.Small
and the button will be like this:

Note: if you apply a style to a ViewGroup widget, its child widgets will not inherit that style.

Using Themes

you can apply styles as themes on an activity level or application level.

if you apply a theme on an activity level then all widgets within that activity will inherit from that theme.
to do so, open the AndroidManifest.xml and go the <activity> tag and add the android:theme attribute:
<activity android_name=".StylesDemo"
android_label="@string/app_name" android_theme="@style/BlueLabel">


to apply a theme on the application level so that the style will be applied to all activities within your application, open the AndroidManifest.xml and go the <application> tag and add the android:theme attribute:
<application android_icon="@drawable/icon" android_label="@string/app_name" android_theme="@style/BlueLabel">

to set the theme of an activity programmatically call this line in the onCreate method
this.setTheme(R.style.BlueLabel);
Read More..

Thursday, March 10, 2016

Introduction to UI in Android

Layouts in android is constructed from two objects: View and ViewGroup.


The View class is the base class for many widgets sub classes such as TextView and Button classes.

The ViewGroup is a view that conatains other views. The Viewgroup class is the base class for many layouts in android.

The UI Hierarchy is described in this picture from the android online sdk documentation



As you can see the root node is a view group which can be any layout that contains child views or even other viewgroups.


The root node appears on the activity by calling setcontentview ( method). Which in turn draws its child nodes and each child node draws its child nodes

In the following posts we are going to explore the categories of android widgets which are:
 
1. Text Controls


2. Button controls

3. List controls

4. Grid controls

5. Date and time controls

6. Menus

7. Dialogs

8. Adapters
Read More..

Monday, February 29, 2016

Android Content Providers

Remember when we created a sqlite database android application. We saw that the database file is stored in the file system directories of that application meaning that the database cannot be accessed from another application. You can apply the same thing on any resources within your application (Files, images, videos, …).
But there is a method to expose your data across multiple applications: Content Providers.
Content Providers expose an application’s data across all other applications, you can use content providers to store or retrieve data of one application from any other application.
In this post we’re going to see how to deal with the existing default content providers by retrieving and manipulating data through them.
Android default content providers:
There are many built-in content providers supplied by OS. They are defined in the android.provider package, they include:
·         Browser.
·         Calllog.
·         Live Folders.
·         Contacts Contract.
·         Media Store.
·         Settings

content providers basics:

the concept of content providers is pretty similar to the concept of ASP.NET Web Services they provide data encapsulation through exposing data by URis. Any content provider is invoked by a URi in the form of content://provider_name . for example the URi of the Contacts content provider that retrieves all contacts is in the following form content://contacts/people. If you want to retrieve a particular contact (by its ID) then it would be in this form: content://contacts/people/5.

You do not need to write the URis of the content providers manually as they are stored as constant values in their respective content provider classes.

The Uri of the Contacts phones content provider is defined in
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
(content://com.android.contacts/data/phones)

The Uri of the browser Bookmarks content provider is defined in
Browser.BOOKMARKS_URI
(content://browser/bookmarks)

The Media store (Video) stored in external device (SD Card) is defined in
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
(content://media/external/video/media) and so on.

content providers allow you to perform basic CRUD operations: Create,Read, Update and Delete on data.

Making Queries

to retrieve data from a content provider we run a sql-like query using ManagedQuery object. The ManagedQuery object returns a cursor holding the result set.

To retrieve a list of all contacts and display them in a ListView
We first define our activity xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android_orientation="vertical"
android_layout_width="fill_parent"
android_layout_height="fill_parent"
>
<TextView
android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_id="@+id/txt"
/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/list"
/>
</LinearLayout>

And define the layout of each row in the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

android_layout_width="wrap_content"
android_layout_height="wrap_content"
android_orientation="horizontal"
>
<TextView
android_layout_width="100px"
android_layout_height="wrap_content"
android_id="@+id/txtName"
android_layout_weight="1"
/>
<TextView
android_layout_width="100px"
android_layout_height="wrap_content"
android_id="@+id/txtNumber"
android_layout_weight="1"
/>
</LinearLayout>

Remember to add the following permission to the manifest.xml file
<uses-permission android_name="android.permission.READ_CONTACTS"></uses-permission>

To retrieve the contacts and bind them to the listView:
String [] projection=new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone._ID};
txt.setText(ContactsContract.PhoneLookup.CONTENT_FILTER_URI.toString());
Uri contacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

Cursor managedCursor = managedQuery(contacts,projection,null,null,null);
//Cursor managedCursor =cr.query(contacts, projection, null, null, null);
ListAdapter sca=new SimpleCursorAdapter(this,R.layout.listrow,managedCursor,projection,to);
list.setAdapter(sca);


the above code retrieves all the contacts in the following steps:
  1. We first define the projection of our query, we define the columns we want to retrieve in the result set.We define a String array containing the names of the columns we want to retreieve.The contacts column names are defined in ContactsContract.CommonDataKinds.Phone class.Note that we need to retrieve the _ID column as the cursor that retrieves the data expects such a column to be there.
  2. We specify the Uri of the content provider ContactsContract.CommonDataKinds.Phone.CONTENT_URI
  3. We retrieve the data by a cursor
    Cursor managedCursor = managedQuery(contacts,projection,null,null,null);The cursor is retrieved by executing a managedQuery which has the following parameters:
    1. The Uri of the content provider.
    2. A String Array of the columns to be retrieved (projection)
    3. Where clause.
    4. String array containing selection arguments values.
    5. String representing the order by clause, we can use it but here it will be null. If we want to sort the contacts by name it would be ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +“ asc”
  4. Then we create a list adapeter using the cursor and bind the ListView to it.

The previous example retrieves all the contacts but what if we want to retrieve a certain contact by name:
There are two ways:
  1. Using the same code above but adding a where clause and selection arguments to the managed wuery so it becomes like this:
    Cursor managedCursor = managedQuery(contacts,projection,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+"=?",new String[]{"Jack"},null);
    This retrieves contact info of a person named Jack.

  2. The other method is to inject the query in the Uri, instead of using Uri
    contacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    we use
    Uri contacts=Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,Uri.encode("Jack"));
    This is equivalent to the following Uri content://com.android.contacts/data/phones/Jack

Inserting,updating and deleting:

to insert data using a content provider there are two methods

First:
Using the Insert() method of your activity’s content resolver object. Like this example t insert a new bookmark to the browser:
ContentValues cv=new ContentValues();
cv.put(Browser.BookmarkColumns.TITLE, "End Gadget");
cv.put(Browser.BookmarkColumns.URL, "http://www.engadget.com/");
cv.put(Browser.BookmarkColumns.BOOKMARK,1);
Uri u= getContentResolver().insert(Browser.BOOKMARKS_URI, cv);

We create a ContentValues object and add to it all the required fields, then we call getContentResolver().insert method which returns the Uri of the newly inserted item.
It would be in this example content://browser/bookmarks/17
We can use the generated Uri to update or delete the item later.

Second:
We can replace the getcontentresolver().insert() method with bulkInsert method if we want to insert multiple items at a time.
The bulkInsert(Uri url,ContentValues[] values) method returns the number of new items created.

Updating info using Content Providers:

To update data using content providers, we use getContnetResolver.Update() method:
This code updates the title of an existing browser bookmark:
ContentValues cv=new ContentValues();
cv.put(Browser.BookmarkColumns.TITLE, "End Gadget mod");
//uriBook= getContentResolver().insert(Browser.BOOKMARKS_URI, cv);
getContentResolver().update(Browser.BOOKMARKS_URI, cv, BookmarkColumns.TITLE+"=?", new String[]{"End Gadget"});

the Update method has the following parameters:
  • Content Providers Uri
  • ContentValues object having the new values
  • Where clause
  • String array of the where clause arguments values

Deleting info using Content Providers:

To delete info we use getContentResolver.Delete() method
To delete a bookmark:
getContentResolver().delete(Browser.BOOKMARKS_URI,BookmarkColumns.TITLE+"=?", new String[]{"End Gadget"});

the delete function has the following parameters:
  • Content Providers Uri
  • Where clause
  • String array of the where clause arguments values

Remember to add the following permissions to the manifest.xml to add and read browser bookmarks:
<uses-permission android_name="android.permission.WRITE_CONTACTS"></uses-permission>
<uses-permission android_name="com.android.browser.permission.WRITE_HISTORY_BOOKMARKS"></uses-permission>

Read More..