Laboratory Manual: Sdl-Ii Mobile Application Development (Android)
Laboratory Manual: Sdl-Ii Mobile Application Development (Android)
Laboratory Manual: Sdl-Ii Mobile Application Development (Android)
SDL-II
Mobile Application Development
(Android)
For
As a student, many of you may be wondering with some of the questions in your
mind regarding the subject and exactly what has been tried is to answer through
this manual.
As you may be aware that MGM has already been awarded with ISO 9001:2000
certification and it is our endure to technically equip our students taking the
advantage of the procedural aspects of ISO 9001:2000 Certification.
Faculty members are also advised that covering these aspects in initial stage
itself, will greatly relieve them in future as much of the load will be taken care
by the enthusiasm energies of the students once they are conceptually clear.
LABORATORY MANUAL CONTENTS
This manual is intended for the third year students of Computer Science and
Engineering in the subject of SDL-II Mobile Application Development (Android).
This manual typically contains practical/lab sessions related Android
implemented in java-eclipse covering various aspects related the subject to
enhanced understanding.
Students are advised to thoroughly go through this manual rather than only
topics mentioned in the syllabus as practical aspects are the key to
understanding and conceptual visualization of theoretical aspects covered in the
books.
II. Preparing graduates for higher education and research in computer science and engineering
enabling them to develop systems for society development.
3. Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team,
to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
LAB INDEX
1. Make entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from their left to
right.
3. All the students are supposed to enter the terminal number in the log book.
Basic honesty in the evaluation and marking system is absolutely essential and
in the process impartial nature of the evaluator is required in the examination system to
become popular amongst the students. It is a wrong approach or concept to award the
students by way of easy marking to get cheap popularity among the students to which
they do not deserve. It is a primary responsibility of the teacher that right students
who are really putting up lot of hard work with right kind of intelligence are correctly
awarded.
The marking patterns should be justifiable to the students without any ambiguity and
teacher should see that `students are faced with unjust circumstances.
Android Architecture
Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches.
This provides basic system functionality like process management, memory
management, device management like camera, keypad, display etc. Also, the
kernel handles all the things that Linux is really good at such as networking and
a vast array of device drivers, which take the pain out of interfacing to peripheral
hardware.
Libraries
On top of Linux kernel there is a set of libraries including open -source Web
browser engine WebKit, well known library libc, SQLite database which is a
useful repository for storage and sharing of application data, libraries to play and
record audio and video, SSL libraries responsible for Internet security etc.
Android Runtime
This is the third section of the architecture and available on the second layer
from the bottom. This section provides a key component called Dalvik Virtual
Machine which is a kind of Java Virtual Machine specially designed and
optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and
multi-threading, which is intrinsic in the Java language. The Dalvik VM enables
every Android application to run in its own process, with its own instance of the
Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android
application developers to write Android applications using standard Java
programming language.
Application Framework
Applications
You will find all the Android application at the top layer. You will write your
application to be installed on this layer only. Examples of such applications are
Contacts Books, Browser, Games etc.
Android UI
An Android application user interface is everything that the user can see and
interact with. You have learned about the various layouts that you can use to
position your views in an activity. This chapter will give you detail on various
views.
A View is an object that draws something on the screen that the user can interact
with and a ViewGroupis an object that holds other View (and ViewGroup) objects
in order to define the layout of the user interface.
You define your layout in an XML file which offers a human-readable structure
for the layout, similar to HTML. For example, a simple vertical layout with a text
view and a button looks like this:
<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"
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Android UI Controls
There are number of UI controls provided by Android that allow you to build the
graphical user interface for your app.
TextView
1
This control is used to display text to the user.
EditText
2 EditText is a predefined subclass of TextView that includes rich
editing capabilities.
AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText,
3
except that it shows a list of completion suggestions
automatically while the user is typing.
Button
4 A push-button that can be pressed, or clicked, by the user to
perform an action.
ImageButton
5 AbsoluteLayout enables you to specify the exact location of its
children.
CheckBox
An on/off switch that can be toggled by the user. You should
6
use checkboxes when presenting users with a group of
selectable options that are not mutually exclusive.
ToggleButton
7
An on/off button with a light indicator.
RadioButton
8
The RadioButton has two states: either checked or unchecked.
RadioGroup
9 A RadioGroup is used to group together one or more
RadioButtons.
ProgressBar
The ProgressBar view provides visual feedback about some
10
ongoing tasks, such as when you are performing a task in the
background.
Spinner
11
A drop-down list that allows users to select one value from a set.
TimePicker
12 The TimePicker view enables users to select a time of the day, in
either 24-hour mode or AM/PM mode.
DatePicker
13
The DatePicker view enables users to select a date of the day.
Create UI Controls
android:id="@+id/text_id"
<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:
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. The Android
framework maintains an event queue into which events are placed as they occur
and then each event is removed from the queue on a first-in, first-out (FIFO)
basis. You can capture these events in your program and take appropriate action
as per requirements.
• Event Listeners: The View class is mainly involved in building up a Android GUI,
same View class provides a number of Event Listeners. The Event Listener is the
object that receives notification when an event happes.
• Event Listeners Registration: 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 Handlers: When an event happens and we have registered and event
listener fo the event, the event listener calls the Event Handlers, which is the
method that actually handles the event.
Event Listeners & Event Handlers
OnClickListener()
This is called when the user either clicks or
onClick() touches or focuses upon any widget like button,
text, image etc. You will use onClick() event
handler to handle such event.
OnLongClickListener()
This is called when the user either clicks or
touches or focuses upon any widget like button,
onLongClick()
text, image etc. for one or more seconds. You will
use onLongClick() event handler to handle such
event.
OnFocusChangeListener()
This is called when the widget looses its focus ie.
onFocusChange() user goes away from the view item. You will use
onFocusChange() event handler to handle such
event.
OnFocusChangeListener()
onKey() 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.
OnTouchListener()
This is called when the user presses the key,
onTouch() releases the key, or any movement gesture on the
screen. You will use onTouch() event handler to
handle such event.
OnMenuItemClickListener()
This is called when the user selects a menu item.
onMenuItemClick()
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.
So I recommend to refer official documentation for Android application
development in case you are going to develop a sophisticated apps.
Exercise:
Key points to study: History, Versions, Architecture, IDE (Eclipse), SDK of
android.
Assignment 2
Aim: Study of UI in Android
The first step is to create a simple Android Application using Eclipse IDE. Follow
the option
File → New → Project and finally select →Android New Application wizard from
the wizard list. Now name your application as HelloWorld using the wizard
window as follows:
Next, follow the instructions provided and keep all other entries as default till
the final step. Once your project is created successfully, you will have following
project screen:
Anatomy of Android Application
Before you run your app, you should be aware of a few directories and files in
the Android project:
S.N. Folder, File & Description
src
1
This contains the .java source files for your project. By default, it
includes an MainActivity.java source file having an activity class
that runs when your app is launched using the app icon.
gen
This contains the .R file, a compiler-generated file that references
2
all the resources found in your project. You should not modify
this file.
bin
This folder contains the Android package files .apk built by the
3
ADT during the build process and everything else needed to run
an Android application.
res/drawable-hdpi
4 This is a directory for drawable objects that are designed for high-
density screens.
res/layout
5
This is a directory for files that define your app's user interface.
res/values
6 This is a directory for other various XML files that contain a
collection of resources, such as strings and colors definitions.
AndroidManifest.xml
7 This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
Following section will give a brief overview few of the important application files.
The main activity code is a Java file MainActivity.java. This is the actual
application file which ultimately gets converted to a Dalvik executable and runs
your application. Following is the default code generated by the application
wizard for Hello World! application:
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the
res/layout folder. TheonCreate() method is one of many methods that are fi red
when an activity is loaded.
Whatever component you develop as a part of your application, you must declare
all its components in a manifest file called AndroidManifest.xml which ressides
at the root of the application project directory. This file works as an interface
between Android OS and your application, so if you do not declare your
component in this file, then it will not be considered by the OS. For example, a
default manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Here <application>...</application> tags enclosed the components related to the
application. Attributeandroid:icon will point to the application icon available
under res/drawable-hdpi. The application uses the image named
ic_launcher.png located in the drawable folders
Following is the list of tags which you will use in your manifest file to specify
different Android application components:
The strings.xml file is located in the res/values folder and it contains all the text
that your application uses. For example, the names of buttons, labels, default
text, and similar types of strings go into this file. This file is responsible for their
textual content. For example, a default strings file will look like as following file:
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
The R File
package com.example.helloworld;
<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate
chapter. The TextView is an Android control used to build the GUI and it have
various attribuites like android:layout_width,android:layout_height etc which are
being used to set its width and height etc. The @string refers to the strings.xml
file located in the res/values folder. Hence, @string/hello_world refers to the
hello string defined in the strings.xml fi le, which is "Hello World!".
Let's try to run our Hello World! application we just created. I assume you had
created your AVD while doing environment setup. To run the app from Eclipse,
open one of your project's activity files and click Run icon from the toolbar.
Eclipse installs the app on your AVD and starts it and if everything is fine with
your setup and application, it will display following Emulator window:
Exercise:
Key points to study: Package explorer (Description about folders e.g. src, gen,res,
etc.), Description about XML file, Layouts.
States of an activity
State Description
The Android system defines a life-cycle for activities via predefined life-cycle
methods. The most important methods are:
Method Purpose
onCreate() Called then the activity is created. Used to initialize the activity, for
example create the user interface.
onResume() Called if the activity get visible again and the user starts interacting
with the activity again. Used to initialize fields, register listeners, bind
to services, etc.
onPause() Called once another activity gets into the foreground. Always called
before the activity is not visible anymore. Used to release resources
or save application data. For example you unregister listeners, intent
receivers, unbind from services or remove system service listeners.
onStop() Called once the activity is no longer visible. Time or CPU intensive
shut-down operations, such as writing information to a database
should be down in the onStop() method. This method is guaranteed
to be called as of API 11.
The life cycle of an activity with its most important methods is displayed in the
following diagram.
Android has more life cycle methods but not all of these methods are guaranteed
to be called. The onDestroy() method is not guaranteed to be called, hence you
typically do not use it.
Instance state of an activity which is required to restore the activity to the state
in which the user left it. This is non-persistent application data that needs to
be passed between activities restarts during a configuration change to restore
user selections. The application is responsible for restoring its instance state.
Assume for example the user scrolled through a ListView with thousands of
items and the activity is recreated. Loosing the position in the list is annoying
for the user, hence the position should be restored.
The persisted Bundle data is passed at restart of the activity to the onCreate()
method and onRestoreInstanceState() as parameter.
Exercise:
Objective: Student should know what is intent in android and whatare the
types of it.
Outcome: Student will develop a good application using the intents and its
properties efficiently
Intents are objects of the android.content.Intent type. Your code can send them
to the Android system defining the components you are targeting. For example,
via the startActivity() method you can define that the intent should be used to
start an activity. An intent can contain data via a Bundle. This data can be used
by the receiving component. Starting activities. To start an activity, use the
method startActivity(intent). This method is defined on the Context object which
activity extends.
The following code demonstrates how you can start another activity via an
intent.
Sub-activities
Activities which are started by other Android activities are called sub-activities.
This wording makes it easier to describe which activity is meant.
Starting services
You can also start services via intents. Use the startService(Intent) method call
for that.
Different types of intents
Android supports explicit and implicit intents. An application can define the
target component directly in the intent (explicit intent) or ask the Android system
to evaluate registered components based on the intent data (implicit intents).
Explicit Intents
Explicit intents explicitly define the component which should be called by the
Android system, by using the Java class as identifier.
The following shows how to create an explicit intent and send it to the Android
system. If the class specified in the intent represents an activity, the Android
system starts it.
Implicit Intents
Implicit intents specify the action which should be performed and optionally
data which provides content for the action.
For example, the following tells the Android system to view a webpage. All
installed web browsers should be registered to the corresponding intent data
via an intent filter.
If an implicit intent is sent to the Android system, it searches for all components
which are registered for the specific action and the fitting data type.
Data transfer to the target component: An intent contains certain header data,
e.g., the desired action, the type, etc. Optionally an intent can also contain
additional data based on an instance of the Bundle class which can be retrieved
from the intent via the getExtras() method.
You can also add data directly to the Bundle via the overloaded putExtra()
methods of the Intent objects. Extras are key/value pairs. The key is always of
type String. As value you can use the primitive data types (int, float, ...) plus
objects of type String, Bundle, Parceable and Serializable.
The receiving component can access this information via the getAction() and
getData() methods on the Intent object. ThisIntent object can be retrieved via the
getIntent() method.
The component which receives the intent can use the getIntent().getExtras()
method call to get the extra data. That is demonstrated in the following code
snippet.
Lots of Android applications allow you to share some data with other people,
e.g., the Facebook, G+, Gmail and Twitter application. You can send data to
one of these components. The following code snippet demonstrates the usage
of such an intent within your application.
An activity can be closed via the back button on the phone. In this case the
finish() method is performed. If the activity was started with the
startActivity(Intent) method call, the caller requires no result or feedback from
the activity which now is closed.
If you start the activity with the startActivityForResult() method call, you expect
feedback from the sub-activity. Once the sub-activity ends, the
onActivityResult() method on the sub-activity is called and you can perform
actions based on the result.
In the startActivityForResult() method call you can specify a result code to
determine which activity you started. This result code is returned to you. The
started activity can also set a result code which the caller can use to determine
if the activity was canceled or not.
T he sub-activity uses the finish() method to create a new intent and to put data
into it. It also sets a result via the setResult()method call.
The following example code demonstrates how to trigger an intent with the
startActivityForResult() method.
public void onClick(View view) {
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
// set the request code to any code you like,
// you can identif y the callback via this code
startActivityForResult(i, REQUEST_CODE);
}
If you use the startActivityForResult() method, then the started activity is called
a sub-activity.
If the sub-activity is finished, it can send data back to its caller via an Intent.
This is done in the finish() method.
@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
// Activity f inished ok, return the data
setResult(RESULT_OK, data);
super.finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
if (data.hasExtra("returnKey1")) {
Toast.makeText(this, data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
}
}
Intent filter
Intents are used to signal to the Android system that a certain event has
occurred. Intents often describe the action which should be performed and
provide data upon which such an action should be done. For example, your
application can start a browser component for a certain URL via an intent. This
is demonstrated by the following example.
But how does the Android system identify the components which can react to
a certain intent?
A component can register itself via an intent f ilter for a specific action and
specific data. An intent filter specifies the types of intents to which an activity,
service, or broadcast receiver can respond to by declaring the capabilities of a
component.
Android components register intent filters either statically in the
AndroidManifest.xml or in case of a broadcast receiver also dynamically via code.
An intent filter is defined by its category, action and data filters. It can also
contain additional meta-data.
If an intent is sent to the Android system, the Android platform runs a receiver
determination. It uses the data included in the intent. If several components
have registered for the same intent filter, the user can decide which component
should be started.
You can register your Android components via intent filters for certain events.
If a component does not define one, it can only be called by explicit intents.
This chapter gives an example for registering a component for an intent. The
key for this registration is that your component registers for the correct action,
mime-type and specifies the correct meta-data.
If you send such an intent to your system, the Android system determines all
registered Android components for this intent. If several components have
registered for this intent, the user can select which one should be used.
Exercise:
Objective: Student should use the adapters and list views in their applications
efficiently.
Outcome: Student will demonstrate the efficient use of List views and adapters
through the application.
Typically the user interacts with the list via the action bar, for example, via a
refresh button. Individual list items can be selected. This selection can update
the action bar or can trigger a detailed screen for the selection. The following
graphic sketches that. On the selection of a list item another activity is started.
The input to the list (items in the list) can be arbitrary Java objects. The adapter
extracts the correct data from the data object and assigns this data to the views
in the row of the ListView.
These items are typically called the data model of the list. An adapter can
receive data as input.
Adapters
A n adapter manages the data model and adapts it to the individual entries in
the widget. An adapter extends the BaseAdapterclass.
Every line in the widget displaying the data consists of a layout which can be
as complex as you want. A typical line in a list has an image on the left side
and two text lines in the middle as depicted in the following graphic.
A layout file for a such a line might look like the following.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="@id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
<TextView
android:id="@+id/firstLine"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="@id/icon"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp" />
</RelativeLayout>
T he adapter would inflate the layout for each row in its getView() method and
assign the data to the individual views in the row.
The adapter is assigned to the ListView via the setAdapter method on the
ListView object.
Filtering and sorting of the data is handled by the adapter. You need to
implement the logic in your custom adapter implementation.
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
Default adapter
Using ArrayAdapter
The ArrayAdapter class can handle a list or array of Java objects as input. Every
Java object is mapped to one row. By default, it maps the toString() method of
the object to a view in the row layout.
You can define the ID of the view in the constructor of the ArrayAdapter
otherwise the android.R.id.text1 ID is used as default.
The ArrayAdapter class allows to remove all elements in its underlying data
structure with the clear() method call. You can then add new elements via the
add() method or a Collection via the addAll() method.
You can also directly modify the underlying data structure and call the
notifyDataSetChanged() method on the adapter to notify it about the changes
in data.
Warning
If you want to change the data in your adapter, the underlying data structure
must support this operation. This is, for example, the case for the ArrayList class,
but not for arrays.
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
The following example shows the usage of the ListView view in an activity. It
uses a default layout from the Android platform for the row layout. It also
demonstrates the removal of list items and uses animations for the removal.
package com.exerciseneme.android.listview.withanimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listviewexampleactivity);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
@Override
public void run() {
list.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Exercise:
Key points to study: Description of List View and Types of adapters
Objective: Student should understand the concept of dialogs and alert dialogs
in android.
Android Dialogs
Y ou can open dialogs from your activity via the showDialog(int) method. Dialogs
which are created via an activity are bound to this activity. A dialog gets the
focus until the user closes it.
The Dialog class is the base class for dialogs. Typically you use one of its
subclasses, e.g., AlertDialog, ProgressDialog,DatePickerDialog or
TimePickerDialog.
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This will end the activity");
builder.setCancelable(true);
builder.setPositiveButton("I agree", new OkOnClickListener());
builder.setNegativeButton("No, no", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
onCreateDialog(int) is only called the first time if you want to later influence the
dialog to use the optionalonPrepareDialog(int, Dialog) method.
ProgressDialog
Custom dialogs
If you want to create your custom dialogs, you create a layout file for the dialog.
This layout file is assigned to the dialog via thesetContentView() method.
You would then use the dialog.findViewById() to find the elements in your
layout and assign values to it.
The title of the dialog can be set via the setTitle() method.
Exercise:
Ensure that the layout file of your activity contains a button with the
android:onClick pointing to a method called onClick.
// existing code.....
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This ends the activity");
builder.setCancelable(true);
builder.setPositiveButton("I agree", new OkOnClickListener());
builder.setNegativeButton("No, no", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
If you run your application and click the corresponding button, your dialog is
displayed.
Assignment 7
Aim: Developing application for TextToSpeech Converter
TextToSpeech Converter
Android allows you convert your text into voice. Not only you can convert it but
it also allows you to speak text in variety of different languages.
Android provides TextToSpeech class for this purpose. In order to use this class,
you need to instantiate an object of this class and also specify the initListnere.
Its syntax is given below:
@Override
);
In this listener , you have to specify the properties for TextToSpeech object , such
as its language ,pitch e.t.c. Language can be set by calling setLanguage() method.
Its syntax is given below:
ttobj.setLanguage(Locale.UK);
The method setLanguage takes an Locale object as parameter. The list of some
of the locales availaible are given below:
Sr.No Locale
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA
Once you have set the language, you can call speak method of the class to speak
the text. Its syntax is given below:
Apart from the speak method, there are some other methods availaible in the
TextToSpeech class. They are listed below:
getLanguage()
2 This method returns a Locale instance describing the
language.
isSpeaking()
3 This method checks whether the TextToSpeech engine is busy
speaking.
setPitch(float pitch)
4 This method sets the speech pitch for the TextToSpeech
engine.
setSpeechRate(float speechRate)
5
This method sets the speech rate.
shutdown()
6 This method releases the resources used by the TextToSpeech
engine.
stop()
7
This method stop the speak.
Example
The below example demonstrates the use of TextToSpeech class. It crates a basic
application that allows you to set write text and speak it.
To experiment with this example , you need to run this on an actual device.
Steps Description
package com.example.texttospeech;
import java.util.Locale;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
TextToSpeech ttobj;
private EditText write;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
write = (EditText)findViewById(R.id.editText1);
ttobj=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
ttobj.setLanguage(Locale.UK);
}
}
});
}
@Override
public void onPause(){
if(ttobj !=null){
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
@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;
}
public void speakText(View view){
String toSpeak = write.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
}
Here is the content of 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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="188dp"
android:layout_marginRight="67dp"
android:onClick="speakText"
android:text="@string/text1" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="81dp"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="@string/write"
android:textAppearance="?android:attr/textAppe aranceLarge" />
</RelativeLayout>
Here is the content of Strings.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TextToSpeech</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="text1">Text to Speech</string>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.texttospeech"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.texttospeech.MainActivity"
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>
</manifest>
Let's try to run your TextToSpeech application. I assume you have connected
your actual Android Mobile device with your computer. To run the app from
Eclipse, open one of your project's activity files and click Run icon from the
toolbar. Before starting your application, Eclipse will display following window to
select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which
will display following screen.
Now just type some text in the field and click on the text to speech button below.
A notification would appear and text will be spoken. It is shown in the image
below:
Now type something else and repeat the step again with different locale. You will
again hear sound. This is shown below:
Assignment 8
Aim: To Study the Telephony (SmsManager) in android.
Objective: Student should know how to use the telephony package in android.
SmsManager
There are following two ways to send SMS using Android device:
The SmsManager manages SMS operations such as sending data to the given
mobile device. You can create this object by calling the static method
SmsManager.getDefault() as follows:
Once you have SmsManager object, you can use sendDataMessage() method to
send SMS at the specified mobile number as below:
Apart from the above method, there are few other important functions available
in SmsManager class. These methods are listed below:
Example
Following example shows you in practical how to use SmsManager object to send
an SMS to the given mobile number.
To experiment with this example, you will need actual Mobile device equipped
with latest Android OS, otherwise you will have to struggle with emulator which
may not work.
Step Description
Exercise:
What is SQLite?
SQLite supports the data types TEXT (similar to String in Java), INTEGER
(similar to long in Java) and REAL (similar to double in Java).
All other types must be converted into one of these fields before getting saved in
the database. SQLite itself does not validate if the types written to the columns
are actually of the defined type, e.g. you can write an integer into a string column
and vice versa.
SQLite in Android
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 a SQLite database involves accessing the file system. This can be slow.
Therefore it is recommended to perform database operations asynchronously.
SQLite architecture
Packages
The android.database package contains all necessary classes for working with
databases. The android.database.sqlitepackage contains the SQLite specific
classes.
In this class you need to override the following methods to create and update
your database.
onCreate() - is called by the framework, if the database is accessed but not yet
created.
The database tables should use the identifier _id for the primary key of the table.
Several Android functions rely on this standard.
Note:
It is good practice to create a separate class per table. This class defines static
onCreate() andonUpgrade() methods. These methods are called in the
corresponding methods of SQLiteOpenHelper. This way your implementation of
SQLiteOpenHelper stays readable, even if you have several tables.
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.
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() Example
query() Example
The following gives an example of a query() call.
Parameter Comment
String Where-clause, i.e. filter for the selection of data, null will
whereClause select all data.
String[] groupBy A filter declaring how to group rows, null will cause the
rows to not be grouped.
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.
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.
ListViews are Views which allow to display a list of elements. ListActivities are
specialized activities which make the usage of ListViews easier. To work with
databases and ListViews you can use the SimpleCursorAdapter. The
SimpleCursorAdapter allows to set a layout for each row of the ListViews.
You also define an array which contains the column names and another array
which contains the IDs of Views which should be filled with the data.
The SimpleCursorAdapter class will map the columns to the Views based on the
Cursor passed to it. To obtain the Cursor you should use the Loader class.
Exercise:
Objective: Student should able to develop and deploy the android application.
Assignment: Student should come with their ideas and discuss with faculty and
develop application on android. Application with web service and database has
more weightage and with all necessary database operations.
Student should use maximum UI components to make UI better and user-
friendly.