Week 1 Android Programming What Is Android?
Week 1 Android Programming What Is Android?
INTRODUCTION
ANDROID PROGRAMMING
What is Android?
Android is an open source (free to use) and Linux-based Operating System for mobile devices such as
tablets and smartphones. It was developed by the Open Handset Alliance, led by Google, and other
companies.
The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007,
whereas the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly
Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in
terms of functionality and performance.
Some great features of Android
1. Beautiful UI - Android OS’s screen has beautiful and intuitive user interface
2. Connectivity – Wi-fi, Bluetooth, WiMAX, LTE, GSM/EDGE, Etc.
3. Storage – SQLite, a built-in lightweight relational database that is used for data storage
purposes. SQLite’s syntax is the almost same as SQL databases.
4. Media Support – Audio file like: Ogg, Vorbis, Wav and MP3. Image file like: PNG, GIF, JPEG,
and BMP
5. Messaging – SMS and MMS
6. Web Browser – Based on the open-source WebKit layout engine, coupled with Chrome’s V8
JavaScript engine supporting HTML5 and CSS3.
7. Multi-touch – Native support for multi-touch.
8. Multi-tasking – User can jump from one task to another and same time various application
can run simultaneously.
Android Apps
Android applications are usually developed in the Java language using the Android Software
Development Kit.
Once developed, Android applications can be packaged easily and sold out either through a store such
as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more
than 190 countries around the world. It's the largest installed base of any mobile platform and is
growing fast. Every day more than 1 million new Android devices are activated worldwide
Environment Setup
Android application development can start with:
1. Microsoft Windows XP or later version
2. Mac OS X 10.5.8 or later version with Intel chip
3. Linux including GNU C Library 2.7 or later
4. Minimum of 2GB of RAM (4GB is preferred)
5. 1.5GB of available disk space
Tools for developing Android app:
1. Java JDK5 or JDK6
2. Android SDK
3. Eclipse IDE for Java Developers
4. Android Development Tools (ADT) Eclipse Plugin
6. Finish
5. Package Explorer – where all resources including source code, XML file, AndroidManifest, and
other related file is located. Package explorer serves as navigation for coding, changing design
and adding resources in your application.
6. The graphical layout of the App
NOTE: Android applications can only be ran in an android device. Thus, for our app to run on computer,
we need to have an Emulator. Android eclipse supports default emulator: Android Virtual Device (AVD)
A. Project components
Included libraries
Resources
Manifest file
- Shouldn’t usually have to edit it directly, Eclipse can do that for you
- Separates the description of the layout from any actual code that controls it
- Can easily take a UI from one platform to another
C. R Class
In res/values
- strings.xml
E. Manifest File
When have more than one Activity in app, NEED to specify it in manifest file
Also important to define permissions and external libraries, like Google Maps API
WEEK 2
Activity, Activity Life Cycle, UI Layouts, UI Controls
Activity
- Different events in their life happen either via the user touching buttons or
programmatically
Activity Life Cycle
UI Layouts
- The basic building block for user interface is a View object which is created from the View class and
occupies a rectangular area on the screen and is responsible for drawing and event handling. View
is the base class for widgets, which are used to create interactive UI components like buttons, text
fields, etc.
- The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.
- Once your layout is defined, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.
# Layout Description
1. Linear Layout LinearLayout is a view group that aligns all children in a single
direction, vertically or horizontally.
2. Relative Layout RelativeLayout is a view group that displays child views in relative
positions.
3. Table Layout TableLayout is a view that groups views into rows and columns.
4. Absolute Layout AbsoluteLayout enables you to specify the exact location of its
children.
5. Frame Layout The FrameLayout is a placeholder on screen that you can use to
display a single view.
6. List View ListView is a view group that displays a list of scrollable items.
7. Grid View View GridView is a ViewGroup that displays items in a two-
dimensional, scrollable grid.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and there are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
Layout Attribute Description
android:id This is the ID which uniquely identifies the view.
android:layout_marginTop This is the extra space on the top side of the layout.
android:layout_marginBottom This is the extra space on the bottom side of the layout.
android:layout_marginLeft This is the extra space on the left side of the layout.
android:layout_marginRight This is the extra space on the right side of the layout.
android:layout_gravity This specifies how much of the extra space in the layout should be
allocated to the View.
android:layout_weight This specifies how child Views are positioned.
Here width and height are the dimension of the layout/view which can be specified in terms of dp
(Density-independent Pixels), sp (Scale-independent Pixels), pt (Points which is 1/72 of an inch), px
(Pixels), mm (Millimeters) and finally in (inches).
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within the tree.
The syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"
- The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and
expand the rest of the ID string and identify it as an ID resource.
- The plus-symbol (+) means that this is a new resource name that must be created and added to our
resources. To create an instance of the view object and capture it from the layout, use the
following:
Button myButton = (Button) findViewById(R.id.my_button);
Android UI Controls
There are number of UI controls provided by Android that allows you to build the graphical user
interface for your app.
# UI Control Description
1. TextView This control is used to display text to the user.
7. CheckBox An on/off switch that can be toggled by the user. You should use
checkboxes when presenting users with a group of selectable
options that are not mutually exclusive.
8. ToggleButton An on/off button with a light indicator.
13. TimePicker The TimePicker view enable users to select a time of the day, in
either 24-hour mode or AM/PM mode.
14. DatePicker The DatePicker view enable users to select a date of the day.
Create UI Controls
<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_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the following:
Data types
- Java has four (4) looping keywords that are used for iterating statements. They are:
o While loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
Syntax:
while(<condition>){ <Statements> }
o Do-while loop
Like while statement, except that it tests the condition at the end of the loop body.
Syntax:
do{ <statements> } while(<condition>);
o For loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop.
Syntax:
for(<initialization> ; <condition> ; <inc/dec>) { <Statements>}
o Enhanced for loop
This for loop can traverse a collection of elements such as arrays.
Syntax:
for(<element holder declaration>: <array/collection>){ <Statements> }
Functions in Java
- A function is a block of code that has a name and property that is reusable. It can be executed from
as many different points in program as required.
- In Java, functions are defined inside classes.
Examples:
WEEK 4
Event Handling
Events in Android
- Events are a useful way to collect data about a user's interaction with interactive components of
your app, like button presses or screen touch etc.
Event Listeners
- The View class is mainly involved in building up an Android GUI, same View class provides a number
of Event Listeners. The Event Listener is the object that receives notification when an event occurs.
- Event Registration is the process by which an Event Handler gets registered with an Event Listener
so that the handler is called when the Event Listener fires the event.
Event handler
- When an event happens and we have registered an event listener for the event, the event listener
calls the Event Handlers, which is the method that actually handles the event.
Examples
onKey() OnKeyListener
This is called when the user is focused on the item and presses or
releases a hardware key on the device. You will use onKey() event
handler to handle such event.
onTouch OnTouchListener
This is called when the user presses the key, releases the key, or
any movement gesture on the screen. You will use onTouch()
event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener
This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc., which may be needed for your application.
Steps on creating Event in Android:
Step 1:
Create a new project name it EventListerProject. Just leave all default settings of your project.
Step 2:
In your activity_main.xml, place a two textboxes and a button. Make sure to change the default layout
(RelativeLayout) to LinearLayout.
Graphical Layout:
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">EventListenerProject</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="add">Add Numbers</string>
</resources>
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:id="@+id/etNum1"
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/etNum2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/add" />
</LinearLayout>
Step 3:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
Button btnAdd;
EditText etNum1, etNum2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewByIds(); // USER DEFINED FUNCTION
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int num1 =
Integer.parseInt(etNum1.getText().toString());
int num2 =
Integer.parseInt(etNum2.getText().toString());
int sum = getSum(num1, num2); // USER-DEFINED
FUNCTIONs
Toast.makeText(MainActivity.this, "The sum is: "+sum,
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Step 4:
Run your Android Application Project. Make sure you have your default emulator.
Conclusion: The app will accept two numbers using EditTexts, and add the input when the button was
clicked. The sum will be displayed in a Toast notification.
WEEK 5
Threads and Splash Screen
Starting a new Activity
- If you want to open multiple xml Layout within your app, you have to create new Class and XML
files that will handle your layouts.
Steps on starting a new Activity.
Step 1:
Create a new android application project, name it StartingNewActivity. Just leave all the default settings
for your project.
Step 2:
Aside from activity_main.xml, create a new xml file name it activity_two. Then paste the following code.
1. activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:text="@string/next" />
</LinearLayout>
2. activity_two.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="@string/second"
/>
</LinearLayout>
Step 3:
Add new class to your package, name it NextActivity. Paste the following code on your classes.
MainActivity:
package com.example.startingnewactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
Button btnNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener((OnClickListener) this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
NextActivity.java:
package com.example.startingnewactivity;
import android.app.Activity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
}
Step 4:
We have to declare our NextActivity class to our AndroidManifest file for it to be recognized as a valid
Class. If we do not do this, NextActivity will not display any layout, hence, a force close.
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity <!-- here's for MainActivity -->
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Step 5:
Conclusion: The application will be directed to another layout/view when the button was clicked.
Splash Screen
- Splash screens are typically used by particularly large applications to notify the user that the
program is in the process of loading. They provide feedback that a lengthy process is underway.
- The following are sample splash screen of popular android apps.
Threads
- A thread is an independent path of execution within a program. Many threads can run concurrently
within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A
Java program can have many threads, and these threads can run concurrently, either
asynchronously or synchronously.
- Multithreading has several advantages over Multiprocessing such as:
o Threads are lightweight compared to processes.
o Threads share the same address space and therefore can share both data and code.
o Context switching between threads is usually less expensive than between processes.
o Cost of thread intercommunication is relatively low that that of process
intercommunication.
o Threads allow different tasks to be performed concurrently.
You can use Threads in Java to make a splash screen of your application. The following is an example of
a splash screen program in Android:
Step 1:
Create a new android application project, name it SplashActivity. Just leave all the default settings for
your project. Just leave all default settings for your project.
Step 2:
In your res folder, create a new folder and name it raw.
Step 3:
Drag and drop any image to raw folder except PNG file and select copy files.
Splash image should appear in raw folder. The image should also be named Splash.jpeg
Step 4:
Make an ImageView to have a splash screen image. Paste the FF. code to your activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@raw/Splash" />
</LinearLayout>
Layout:
Step 5:
Inside your MainActivity, you must create a thread that handles how long the splash screen will stay.
Paste the following code in MainActivity class.
package com.example.splashactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent();
i.setClass(MainActivity.this, NextActivity.class);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You’ll notice that NextActivity class is not yet created. So, you need to create it first.
Step 6:
Create NextActivity, just leave default settings but make sure to extend the NextActivity with Activity
class and implement onCreate Method. Code is as follows.
package com.example.splashactivity;
import android.app.Activity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
}
You’ll notice that the layout activity_app is not yet created. So you should create one.
Step 7:
Go to your layout folder, and create activity_app.xml. Paste the following code.
package com.example.splashactivity;
import android.app.Activity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
}
}
Conclusion: You have created a simple splash screen for your application.
Source: http://www.wideskills.com/java-tutorial/java-threads-tutorial
WEEK 7
Session Handling
Session
- Session helps you when want to store user data outside your application, so that when the next
time user use your application, you can easily get back his details and perform accordingly. This can
be done in many ways. But the most easiest and nicest way of doing this is through Shared
Preferences.
SharedPreferences
- allows you to save and retrieve data in the form of key value pair. In order to use shared
preferences
- You have to call the method getSharedPreferences() that returns a SharedPreference instance
pointing to the file that contains the values of preferences.
Sample Program:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
android:text="@string/sesion_handling" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
>
<EditText
android:id="@+id/etData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/save"
/>
</LinearLayout>
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SharePreferencesDemo</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="sesion_handling">Working with Session Handling</string>
<string name="save">Save Data</string>
</resources>
MainActivity.java
package com.pdm.sharepreferencesdemo;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
@Override
protected void onResume()
{
if(sharedPrefs.contains(keyData)){
String data = sharedPrefs.getString(keyData, ""); // param1
is the key and param2 is the default value if key has no value
etData.setText(data);
}
}
Conclusion:
we created an app that saves the entered data of the user.
WEEK 8-9
SQLite Database in Android