SlideShare a Scribd company logo
5/21/2013
Android Development Basic | Er Pragati Singh
CMC LTD ANDROID TUTORIALS
toandroiddeveloper@gmail.com
Page 1
1. What is Android?
1.1. Android Operation System
Android is an operating system based on Linux with a Java programming interface.
The Android Software Development Kit (Android SDK) provides all necessary tools to develop Android
applications. This includes a compiler, debugger and a device emulator, as well as its own virtual machine to run
Android programs.
Android is currently primarily developed by Google.
Android allows background processing, provides a rich user interface library, supports 2-D and 3-D graphics using
the OpenGL libraries, access to the file system and provides an embedded SQLite database.
Android applications consist of different components and can re-use components of other applications, if these
applications declare their components as available. This leads to the concept of a task in Android; an application can
re-use other Android components to archive a task.
For example you can write an application which integrates a map component and a camera component to archive a
certain task.
1.2. Google Play
Google offers the "Google Play" service. Google hosts Android applications and the Google Play application allows
to install new Android application on an Android device. Google Play used to be called "Android Market".
1.3. Security and permissions
During deployment on an Android device, the Android system will create a unique user and group ID for every
Android application. Each application file is private to this generated user, e.g. other applications cannot access
these files.
In addition each Android application will be started in its own process.
Therefore by means of the underlying Linux operating system, every Android application is isolated from other
running applications. A misbehaving application cannot easily harm other Android applications.
If data should be shared, the application must do this explicitly, e.g. via a Service or a ContentProvider.
Android also contains a permission system. Android predefines permissions for certain tasks but every application
can also define its own permissions.
toandroiddeveloper@gmail.com
Page 2
An application must declare in its configuration file (AndroidManifest.xml) that it requires certain permissions.
Depending on the details of the required permission, the Android system will either automatically grant the
permission, reject it or ask the user if he grants this permission to the application during installation.
If for example the application declares that it requires Internet access, the user needs to confirm the usage of this
permission during installation.
This is called "user driven security". The user decides to grant a permission or to deny it. If the user denies a
permission required by the application, this application cannot be installed. The check of the permission is only
performed during installation, permissions cannot be denied or granted after the installation.
Typically not all users check the permissions in detail but some users do. If there is seems to be something strange in
connection with them, they will write bad reviews on Google Play.
2. Android components
The following gives a short overview of the most important Android components.
2.1. Activity
Activity represents the presentation layer of an Android application. A simplified (and slightly incorrect) description
is that an Activity is a screen. This is slightly incorrect as Activities can be displayed as Dialogs or can be
transparent. An Android application can have several Activities.
2.2. Views and ViewGroups
Views are user interface widgets, e.g. buttons or text fields. The base class for
all Views is android.view.View.Views often have attributes which can be used to change their appearance and
behavior.
A ViewGroup is responsible for arranging other Views e.g. a ViewGroup is a layout manager. The base class for a
layout manager is android.view.ViewGroups. ViewGroup also extends View. ViewGroups can be nestled to create
complex layouts. You should not nestle ViewGroups too deeply as this has a negative impact on the performance.
2.3. Intents
Intents are asynchronous messages which allow the application to request functionality from other components of
the Android system, e.g. from Services or Activities. An application can call a component directly (explicitIntent )
or ask the Android system to evaluate registered components for a certain Intent (implicit Intents ). For example the
application could implement sharing of data via an Intent and all components which allow sharing of data would be
available for the user to select. Applications register themselves to an Intent via anIntentFilter.
toandroiddeveloper@gmail.com
Page 3
Intents allow to combine loosely coupled components to perform certain tasks.
2.4. Services
Services perform background tasks without providing a user interface. They can notify the user via the notification
framework in Android.
2.5. ContentProvider
ContentProvider provides a structured interface to application data. Via a ContentProvider your application can
share data with other applications. Android contains an SQLite database which is frequently used in conjunction
with a ContentProvider to persist the data of the ContentProvider.
2.6. BroadcastReceiver
BroadcastReceiver can be registered to receive system messages and Intents. A BroadcastReceiver will get notified
by the Android system, if the specified situation happens. For example a BroadcastReceiver could get called once
the Android system completed the boot process or if a phone call is received.
2.7. (HomeScreen) Widgets
Widgets are interactive components which are primarily used on the Android homescreen. They typically display
some kind of data and allow the user to perform actions via them. For example a Widget could display a short
summary of new emails and if the user selects an email, it could start the email application with the selected email.
2.8. Other
Android provide many more components but the list above describes the most important ones. Other Android
components are "Live Folders" and "Live Wallpapers". Live Folders display data on the homescreen without
launching the corresponding application.
3. Android Development Tools
3.1. What are the Android Development Tools?
Google provides the Android Development Tools (ADT) to develop Android applications with Eclipse. ADT is a set
of components (plug-ins) which extend the Eclipse IDE with Android development capabilities.
ADT contains all required functionalities to create, compile, debug and deploy Android applications from the
Eclipse IDE and from the command line. Other IDE's, e.g. IntellJ, are also reusing components of ADT.
toandroiddeveloper@gmail.com
Page 4
ADT also provides an Android device emulator, so that Android applications can be tested without a real Android
phone.
3.2. Dalvik Virtual Machine
The Android system uses a special virtual machine, i.e. the Dalvik Virtual Machine to run Java based applications.
Dalvik uses an own bytecode format which is different from Java bytecode.
Therefore you cannot directly run Java class files on Android, they need to get converted in the Dalvik bytecode
format.
3.3. How to develop Android Applications
Android applications are primarily written in the Java programming language. The Java source files are converted to
Java class files by the Java compiler.
Android provides a tool called "dx"" which converts Java class files into a dex (Dalvik Executable) file. All class
files of one application are placed in one compressed .dex file. During this conversion process redundant
information in the class files are optimized in the .dex file. For example if the same String is found in different class
files, the .dex file contains only once reference of this String.
These dex files are therefore much smaller in size than the corresponding class files.
The .dex file and the resources of an Android project, e.g. the images and XML files, are packed into
an .apk (Android Package) file. The program aapt (Android Asset Packaging Tool) performs this packaging.
The resulting .apk file contains all necessary data to run the Android application and can be deployed to an Android
device via the "adb" tool.
The Android Development Tools (ADT) allows that all these steps are performed transparently to the user; either
within Eclipse or via the command line.
If you use the ADT tooling you press a button or run a script and the whole Android application (.apk file) will be
created and deployed.
4. Android Application Architecture
4.1. AndroidManifest.xml
The components and settings of an Android application are described in the file AndroidManifest.xml. For example
all Activities and Services of the application must be declared in this file.
toandroiddeveloper@gmail.com
Page 5
It must also contain the required permissions for the application. For example if the application requires network
access it must be specified here.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.temperature"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Convert"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="9" />
</manifest>
The package attribute defines the base package for the Java objects referred to in this file. If a Java object lies within
a different package, it must be declared with the full qualified package name.
Google Play requires that every Android application uses its own unique package. Therefore it is a good habit to use
your reverse domain name as package name. This will avoid collisions with other Android applications.
toandroiddeveloper@gmail.com
Page 6
android:versionName and android:versionCode specify the version of your application. versionNameis what the user
sees and can be any String.
versionCode must be an integer. The Android Market determine based on the versionCode, if it should perform an
update of the applications for the existing installations. You typically start with "1" and increase this value by one, if
you roll-out a new version of your application.
The tag <activity> defines an Activity, in this example pointing to the Convert class in
thede.vogella.android.temperature package. An intent filter is registered for this class which defines that
thisActivity is started once the application starts (action android:name="android.intent.action.MAIN"). The category
definition category android:name="android.intent.category.LAUNCHER" defines that this application is added to
the application directory on the Android device.
The @string/app_name value refers to resource files which contain the actual value of the application name. The
usage of resource file makes it easy to provide different resources, e.g. strings, colors, icons, for different devices
and makes it easy to translate applications.
The "uses-sdk" part of the "AndroidManifest.xml" file defines the minimal SDK version for which your application
is valid. This will prevent your application being installed on devices with older SDK versions.
4.2. R.java and Resources
The " gen " directory in an Android project contains generated values. R.java is a generated class which contains
references to certain resources of the project.
These resources must be defined in the "res" directory and can be XML files, icons or pictures. You can for example
define values, menus, layouts or animations via XML files.
If you create a new resource, the corresponding reference is automatically created in R.java via the Eclipse ADT
tools. These references are static int values and define ID's for the resources.
The Android system provides methods to access the corresponding resource via these ID's.
For example to access a String with the R.string.yourString ID, you would use
thegetString(R.string.yourString)) method.
R.java is automatically created by the Eclipse development environment, manual changes are not necessary and will
be overridden by the tooling.
4.3. Assets
toandroiddeveloper@gmail.com
Page 7
While the res directory contains structured values which are known to the Android platform, the assets directory can
be used to store any kind of data. In Java you access this data via the AssetsManager and the getAssets()method .
4.4. Activities and Layouts
The user interface for Activities is defined via layouts. The layout defines the included Views (widgets) and their
properties.
A layout can be defined via Java code or via XML. In most cases the layout is defined as an XML file.
XML based layouts are defined via a resource file in the /res/layout folder. This file specifies
the ViewGroups,Views, their relationship and their attributes for this specific layout.
If a View needs to be accessed via Java code, you have to give the View a unique ID via the android:id attribute. To
assign a new ID to a View use @+id/yourvalue. The following shows an example in which a Button gets the
"button1" ID assigned.
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Preferences" >
</Button>
By conversion this will create and assign a new yourvalue ID to the corresponding View. In your Java code you can
later access a View via the method findViewById(R.id.yourvalue).
Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout
definition. It also allows the definition of different layouts for different devices. You can also mix both approaches.
4.5. Reference to resources in XML files
In your XML files, for example your layout files, you can refer to other resources via the @ sign.
For example, if you want to refer to a color which is defined in a XML resource, you can refer to it
via@color/your_id. Or if you defined a "hello" string in an XML resource, you could access it via @string/hello.
toandroiddeveloper@gmail.com
Page 8
4.6. Activities and Lifecycle
The Android system controls the lifecycle of your application. At any time the Android system may stop or destroy
your application, e.g. because of an incoming call. The Android system defines a lifecycle for Activities via
predefined methods. The most important methods are:
• onSaveInstanceState() - called if the Activity is stopped. Used to save data so that the Activitycan restore
its states if re-started
• onPause() - always called if the Activity ends, can be used to release resource or save data
• onResume() - called if the Activity is re-started, can be used to initialize fields
4.7. Configuration Change
An Activity will also be restarted, if a so called "configuration change" happens. A configuration change happens if
an event is triggered which may be relevant for the application. For example if the user changes the orientation of
the device (vertically or horizontally). Android assumes that an Activity might want to use different resources for
these orientations and restarts the Activity.
In the emulator you can simulate the change of the orientation via CNTR+F11.
You can avoid a restart of your application for certain configuration changes via the configChanges attribute on
your Activity definition in your AndroidManifest.xml. The following Activity will not be restarted in case of
orientation changes or position of the physical keyboard (hidden / visible).
<activity android:name=".ProgressTestActivity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden|keyboard">
</activity>
4.8. Context
The class android.content.Context provides the connections to the Android system. It is the interface to global
information about the application environment. Context also provides access to Android Services, e.g. the Location
Service. Activities and Services extend the Context class and can therefore be used asContext.
toandroiddeveloper@gmail.com
Page 9
1. SQLite and Android
1.1. What is SQLite
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. 250 KByte).
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 saving them
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.
More information about SQLite can be found on the SQLite website: http://www.sqlite.org.
1.2. SQLite in Android
SQLite is available on every Android device. Using an SQLite database in Android does not require any database
setup or administration.
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
directoryDATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which
theEnvironment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the
name you specify in your application code for the database.
2. Prerequisites for this tutorial
The following assumes that you have already basic knowledge in Android development. Please check the Android
development tutorial to learn the basics.
3. SQLite Architecture
3.1. Packages
toandroiddeveloper@gmail.com
Page 10
The package android.database contains all general classes for working with
databases.android.database.sqlite contains the SQLite specific classes.
3.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.
onCreate() is called by the framework, if the database does not exists.
onUpgrade() is called, if the database version is increased in your application code. 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 getWriteableDatabase() 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. Several Android functions rely on
this standard.
It is best practice to create a separate class per table. This class defines static onCreate() and onUpdate()methods.
These methods are called in the corresponding methods of SQLiteOpenHelper. This way your implementation
of SQLiteOpenHelper will stay readable, even if you have several tables.
3.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 .
toandroiddeveloper@gmail.com
Page 11
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.
3.4. rawQuery() Example
The following gives an example of a rawQuery() call.
Cursor cursor = getReadableDatabase().
rawQuery("select * from todo where _id = ?", new String[] { id });
3.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.
Table 1. 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.
toandroiddeveloper@gmail.com
Page 12
Parameter Comment
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.
3.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.
TheisAfterLast() 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.
toandroiddeveloper@gmail.com
Page 13
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a
column name of the table.
3.7. ListViews, ListActivities and SimpleCursorAdapter
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. TheSimpleCursorAdapter 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.
This tutorial will use ListActivities but not look into the details of them.
6. Android virtual device - Emulator
6.1. What is the Android Emulator?
The Android Development Tools (ADT) includes an emulator to run an Android system. The emulator behaves like
a real Android device (in most cases) and allows you to test your application without having a real device.
You can configure the version of the Android system you would like to run, the size of the SD card, the screen
resolution and other relevant settings. You can define several of them with different configurations.
These devices are called "Android Virtual Device" (AVD) and you can start several in parallel. Starting a new
emulator is very slow, because the file system of the new AVD needs to get prepared.
The ADT allows to deploy and run your Android program on the AVD.
6.2. Google vs. Android AVD
During the creation of an AVD you decide if you want an Android device or a Google device.
An AVD created for Android will contain the programs from the Android Open Source Project. An AVD created for
the Google API's will also contain several Google applications, most notable the Google Maps application.
toandroiddeveloper@gmail.com
Page 14
If you want to use functionality which is only provided via the Google API's, e.g. Cloud2DeviceMessaging or
Google Maps you must run this application on an AVD with Google API's.
6.3. Emulator Shortcuts
The following shortcuts are useful for working with the emulator.
Alt+Enter Maximizes the emulator. Nice for demos.
Ctrl+F11 changes the orientation of the emulator.
F8 Turns network on / off.
6.4. Performance
The graphics of the emulator are rendered in software, which is very slow. To have a responsive emulator use a
small resolution for your emulator, as for example HVGA.
Also if you have sufficient memory on your computer, add at least 1 GB of memory to your emulator. This is the
value "Device ram size" during the creation of the AVD.
8. Error handling and typical problems
Things are not always working as they should. This section gives an overview over typical problems and how to
solve them.
8.1. Clean Project
Several users report that get the following errors:
1. Project ... is missing required source folder: 'gen'
2. The project could not be built until build path errors are resolved.
3. Unable to open class file R.java.
To solve any of these errors, go to the project menu and select Project → Clean.
8.2. Problems with Android Debug Bridge (adb)
The communication with the emulator or your Android device might have problems. This communication is handled
by the Android Debug Bridge (adb).
toandroiddeveloper@gmail.com
Page 15
Eclipse allows to reset the adb in case this causes problems. Select therefore the DDMS perspective
via Window →Open Perspective → Other → DDMS
To restart the adb, select the "Reset adb" in the Device View.
8.3. LogCat
The "LogCat" View shows you the log messages of your Android device and help you analyze problems. For
example Java exceptions in your program would be shown here. To open this view, select Window → Show
View → Other →Android → LogCat.
8.4. Emulator does not start
If your emulator does not start, make sure that the android-sdk version is in a path without any spaces in the path
name.
8.5. Timeout during deployment
If you face timeout issues during deployment you can increase the default timeout in the Eclipse preferences.
SelectWindow → Preferences → Android → DDMS and increase the "ADB connection timeout (in ms)" value.
8.6. Install failed due to insufficient storage
Sometimes the emulator will refuse to install an application with the error message:
INSTALL_FAILED_INSUFFICIENT_STORAGE.
An Android virtual device provides per default only 64M for the storaging Android applications. You can clean your
installed application by re-starting the emulator and selecting the "Wipe user data" flag.
toandroiddeveloper@gmail.com
Page 16
Alternative you can set the the data partition size, if you press edit on the AVD you can set the "Ideal size of data
partition" property via the "New" button.
8.7. Debug Certificate expired
If you get the error message "Debug Certificate expired" switch to the folder which contains the Android AVD, e.g.
".android" under Linux and delete the "debug.keystore" file. This file is only valid for a year and if not present
Eclipse will regenerate the password.
toandroiddeveloper@gmail.com
Page 17
8.8. Error message for @override
The @override annotation was introduced in Java 1.6. If you receive an error message for @override, change the
Java compiler level to Java 1.6. To do this right-click on the project, select Properties → Java Compiler → Compiler
compliance level and select "1.6" in the drop-down box.
8.9. Missing Imports
Java requires that classes which are not part of the standard Java Language be either fully qualified or declared via
imports.
If you see error message with "XX cannot be resolved to a variable", right-click in your Editor and
select Source →Organize Imports to important required packages.
8.10. Eclipse Tips
To work more efficiently with Eclipse, select Window → Preferences → Java → Editor → Save Actions and select
that the source code should be formatted and that the imports should be organized at every save.
9. Conventions for the tutorials
9.1. API version, package and application name
The tutorials of this document have been developed and tested with Android 4.0.3, API Level 15. Please use this
version for all tutorials in this book. Higher version usually should also work. Lower version of the Android API
might also work, but if you face issues, try the recommended version.
The base package for the projects is always the same as the project name, e.g. if you are asked to create a project
"de.vogella.android.example.test" then the corresponding package name is "de.vogella.android.example.test".
The Application name, which must be entered on the Android project generation wizard, will not be predefined.
Choose a name you like.
9.2. Warnings Messages for Strings
The Android development tools are show warnings if you use hard-coded strings, for example in layout files. While
for real application its best practice to use string resource files we use use Strings directly to simplify the creation of
the examples.

More Related Content

PDF
Lecture 2(b) Android Internals A Quick Overview
PPTX
Android application-component
PPT
Android development tutorial
PDF
Android dev o_auth
PPTX
Android Development Training
PPTX
Aptech Apps
PPTX
Android basic principles
PPTX
Lecture 2(b) Android Internals A Quick Overview
Android application-component
Android development tutorial
Android dev o_auth
Android Development Training
Aptech Apps
Android basic principles

What's hot (20)

PPTX
Android Workshop: Day 1 Part 3
PDF
Android Development: Build Android App from Scratch
PPTX
Day 15: Working in Background
PDF
Lecture 1 Session 1 Before Getting Started
PDF
Android interview questions and answers
PPTX
Basic of Android App Development
PPTX
Android Services
PDF
Android developer interview questions with answers pdf
PPTX
.Net presentation
PPTX
Android
PPTX
Android Basic
PDF
Synopsis on android nougat
PPT
Android Applications Development
PDF
Android Development
PPT
Day 6: Android BroadcastReceiver Component
PPSX
ANDROID
PPTX
Introduction to Android Development: Before Getting Started
PPT
android-tutorial-for-beginner
PDF
Android Development
PPT
Android In A Nutshell
Android Workshop: Day 1 Part 3
Android Development: Build Android App from Scratch
Day 15: Working in Background
Lecture 1 Session 1 Before Getting Started
Android interview questions and answers
Basic of Android App Development
Android Services
Android developer interview questions with answers pdf
.Net presentation
Android
Android Basic
Synopsis on android nougat
Android Applications Development
Android Development
Day 6: Android BroadcastReceiver Component
ANDROID
Introduction to Android Development: Before Getting Started
android-tutorial-for-beginner
Android Development
Android In A Nutshell
Ad

Viewers also liked (6)

PPT
Artificail Intelligent lec-1
PPTX
AI: Learning in AI 2
PPT
Artificial Intelligence: Expert Systems Components
PPT
Learning
PPTX
AI: Learning in AI
PPTX
AI: Planning and AI
Artificail Intelligent lec-1
AI: Learning in AI 2
Artificial Intelligence: Expert Systems Components
Learning
AI: Learning in AI
AI: Planning and AI
Ad

Similar to Android Basic- CMC (20)

PDF
Android development-tutorial
DOC
Google android white paper
PDF
Android fundamentals and tutorial for beginners
PPTX
How to create android applications
PDF
Android Introduction by Kajal
PDF
Android : Architecture & Components
PDF
Os eclipse-androidwidget-pdf
PDF
Android from A to Z
PDF
Android from A to Z
PPTX
3. Android Architecture.pptx
PPTX
Android 1-intro n architecture
PPTX
Android development-tutorial
PDF
Installing eclipse & sdk
ODP
Intro To Android App Development
PPTX
Android quick talk
PDF
Matteo Gazzurelli - Introduction to Android Development - Have a break edition
PDF
01 what is android
ODP
Java Meetup - 12-03-15 - Android Development Workshop
PPTX
Androidoverview 100405150711-phpapp01
PPT
Introduction to android sessions new
Android development-tutorial
Google android white paper
Android fundamentals and tutorial for beginners
How to create android applications
Android Introduction by Kajal
Android : Architecture & Components
Os eclipse-androidwidget-pdf
Android from A to Z
Android from A to Z
3. Android Architecture.pptx
Android 1-intro n architecture
Android development-tutorial
Installing eclipse & sdk
Intro To Android App Development
Android quick talk
Matteo Gazzurelli - Introduction to Android Development - Have a break edition
01 what is android
Java Meetup - 12-03-15 - Android Development Workshop
Androidoverview 100405150711-phpapp01
Introduction to android sessions new

More from Pragati Singh (20)

PDF
ISACA Membership-certificate-2034890 | ISACA
PDF
Leading AI driven Business Transformation.pdf
PDF
PMI Prompt Engineering | Gen AI Program Management
PDF
Shaping the Future of Project Management with AI.pdf
PDF
Nessus Scanner: Network Scanning from Beginner to Advanced!
PDF
Tenable Certified Sales Associate - CS.pdf
PDF
Analyzing risk (pmbok® guide sixth edition)
PDF
Pragati Singh | Sap Badge
PDF
Ios record of achievement
PDF
Ios2 confirmation ofparticipation
PDF
Certificate of completion android studio essential training 2016
PDF
Certificate of completion android development essential training create your ...
PDF
Certificate of completion android development essential training design a use...
PDF
Certificate of completion android development essential training support mult...
PDF
Certificate of completion android development essential training manage navig...
PDF
Certificate of completion android development essential training local data s...
PDF
Certificate of completion android development essential training distributing...
PDF
Certificate of completion android app development communicating with the user
PDF
Certificate of completion building flexible android apps with the fragments api
PDF
Certificate of completion android app development design patterns for mobile ...
ISACA Membership-certificate-2034890 | ISACA
Leading AI driven Business Transformation.pdf
PMI Prompt Engineering | Gen AI Program Management
Shaping the Future of Project Management with AI.pdf
Nessus Scanner: Network Scanning from Beginner to Advanced!
Tenable Certified Sales Associate - CS.pdf
Analyzing risk (pmbok® guide sixth edition)
Pragati Singh | Sap Badge
Ios record of achievement
Ios2 confirmation ofparticipation
Certificate of completion android studio essential training 2016
Certificate of completion android development essential training create your ...
Certificate of completion android development essential training design a use...
Certificate of completion android development essential training support mult...
Certificate of completion android development essential training manage navig...
Certificate of completion android development essential training local data s...
Certificate of completion android development essential training distributing...
Certificate of completion android app development communicating with the user
Certificate of completion building flexible android apps with the fragments api
Certificate of completion android app development design patterns for mobile ...

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
master seminar digital applications in india
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Institutional Correction lecture only . . .
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
01-Introduction-to-Information-Management.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Computing-Curriculum for Schools in Ghana
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Module 4: Burden of Disease Tutorial Slides S2 2025
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
master seminar digital applications in india
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
TR - Agricultural Crops Production NC III.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Institutional Correction lecture only . . .
Sports Quiz easy sports quiz sports quiz
Microbial diseases, their pathogenesis and prophylaxis
01-Introduction-to-Information-Management.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O7-L3 Supply Chain Operations - ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Computing-Curriculum for Schools in Ghana

Android Basic- CMC

  • 1. 5/21/2013 Android Development Basic | Er Pragati Singh CMC LTD ANDROID TUTORIALS
  • 2. toandroiddeveloper@gmail.com Page 1 1. What is Android? 1.1. Android Operation System Android is an operating system based on Linux with a Java programming interface. The Android Software Development Kit (Android SDK) provides all necessary tools to develop Android applications. This includes a compiler, debugger and a device emulator, as well as its own virtual machine to run Android programs. Android is currently primarily developed by Google. Android allows background processing, provides a rich user interface library, supports 2-D and 3-D graphics using the OpenGL libraries, access to the file system and provides an embedded SQLite database. Android applications consist of different components and can re-use components of other applications, if these applications declare their components as available. This leads to the concept of a task in Android; an application can re-use other Android components to archive a task. For example you can write an application which integrates a map component and a camera component to archive a certain task. 1.2. Google Play Google offers the "Google Play" service. Google hosts Android applications and the Google Play application allows to install new Android application on an Android device. Google Play used to be called "Android Market". 1.3. Security and permissions During deployment on an Android device, the Android system will create a unique user and group ID for every Android application. Each application file is private to this generated user, e.g. other applications cannot access these files. In addition each Android application will be started in its own process. Therefore by means of the underlying Linux operating system, every Android application is isolated from other running applications. A misbehaving application cannot easily harm other Android applications. If data should be shared, the application must do this explicitly, e.g. via a Service or a ContentProvider. Android also contains a permission system. Android predefines permissions for certain tasks but every application can also define its own permissions.
  • 3. toandroiddeveloper@gmail.com Page 2 An application must declare in its configuration file (AndroidManifest.xml) that it requires certain permissions. Depending on the details of the required permission, the Android system will either automatically grant the permission, reject it or ask the user if he grants this permission to the application during installation. If for example the application declares that it requires Internet access, the user needs to confirm the usage of this permission during installation. This is called "user driven security". The user decides to grant a permission or to deny it. If the user denies a permission required by the application, this application cannot be installed. The check of the permission is only performed during installation, permissions cannot be denied or granted after the installation. Typically not all users check the permissions in detail but some users do. If there is seems to be something strange in connection with them, they will write bad reviews on Google Play. 2. Android components The following gives a short overview of the most important Android components. 2.1. Activity Activity represents the presentation layer of an Android application. A simplified (and slightly incorrect) description is that an Activity is a screen. This is slightly incorrect as Activities can be displayed as Dialogs or can be transparent. An Android application can have several Activities. 2.2. Views and ViewGroups Views are user interface widgets, e.g. buttons or text fields. The base class for all Views is android.view.View.Views often have attributes which can be used to change their appearance and behavior. A ViewGroup is responsible for arranging other Views e.g. a ViewGroup is a layout manager. The base class for a layout manager is android.view.ViewGroups. ViewGroup also extends View. ViewGroups can be nestled to create complex layouts. You should not nestle ViewGroups too deeply as this has a negative impact on the performance. 2.3. Intents Intents are asynchronous messages which allow the application to request functionality from other components of the Android system, e.g. from Services or Activities. An application can call a component directly (explicitIntent ) or ask the Android system to evaluate registered components for a certain Intent (implicit Intents ). For example the application could implement sharing of data via an Intent and all components which allow sharing of data would be available for the user to select. Applications register themselves to an Intent via anIntentFilter.
  • 4. toandroiddeveloper@gmail.com Page 3 Intents allow to combine loosely coupled components to perform certain tasks. 2.4. Services Services perform background tasks without providing a user interface. They can notify the user via the notification framework in Android. 2.5. ContentProvider ContentProvider provides a structured interface to application data. Via a ContentProvider your application can share data with other applications. Android contains an SQLite database which is frequently used in conjunction with a ContentProvider to persist the data of the ContentProvider. 2.6. BroadcastReceiver BroadcastReceiver can be registered to receive system messages and Intents. A BroadcastReceiver will get notified by the Android system, if the specified situation happens. For example a BroadcastReceiver could get called once the Android system completed the boot process or if a phone call is received. 2.7. (HomeScreen) Widgets Widgets are interactive components which are primarily used on the Android homescreen. They typically display some kind of data and allow the user to perform actions via them. For example a Widget could display a short summary of new emails and if the user selects an email, it could start the email application with the selected email. 2.8. Other Android provide many more components but the list above describes the most important ones. Other Android components are "Live Folders" and "Live Wallpapers". Live Folders display data on the homescreen without launching the corresponding application. 3. Android Development Tools 3.1. What are the Android Development Tools? Google provides the Android Development Tools (ADT) to develop Android applications with Eclipse. ADT is a set of components (plug-ins) which extend the Eclipse IDE with Android development capabilities. ADT contains all required functionalities to create, compile, debug and deploy Android applications from the Eclipse IDE and from the command line. Other IDE's, e.g. IntellJ, are also reusing components of ADT.
  • 5. toandroiddeveloper@gmail.com Page 4 ADT also provides an Android device emulator, so that Android applications can be tested without a real Android phone. 3.2. Dalvik Virtual Machine The Android system uses a special virtual machine, i.e. the Dalvik Virtual Machine to run Java based applications. Dalvik uses an own bytecode format which is different from Java bytecode. Therefore you cannot directly run Java class files on Android, they need to get converted in the Dalvik bytecode format. 3.3. How to develop Android Applications Android applications are primarily written in the Java programming language. The Java source files are converted to Java class files by the Java compiler. Android provides a tool called "dx"" which converts Java class files into a dex (Dalvik Executable) file. All class files of one application are placed in one compressed .dex file. During this conversion process redundant information in the class files are optimized in the .dex file. For example if the same String is found in different class files, the .dex file contains only once reference of this String. These dex files are therefore much smaller in size than the corresponding class files. The .dex file and the resources of an Android project, e.g. the images and XML files, are packed into an .apk (Android Package) file. The program aapt (Android Asset Packaging Tool) performs this packaging. The resulting .apk file contains all necessary data to run the Android application and can be deployed to an Android device via the "adb" tool. The Android Development Tools (ADT) allows that all these steps are performed transparently to the user; either within Eclipse or via the command line. If you use the ADT tooling you press a button or run a script and the whole Android application (.apk file) will be created and deployed. 4. Android Application Architecture 4.1. AndroidManifest.xml The components and settings of an Android application are described in the file AndroidManifest.xml. For example all Activities and Services of the application must be declared in this file.
  • 6. toandroiddeveloper@gmail.com Page 5 It must also contain the required permissions for the application. For example if the application requires network access it must be specified here. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="de.vogella.android.temperature" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Convert" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="9" /> </manifest> The package attribute defines the base package for the Java objects referred to in this file. If a Java object lies within a different package, it must be declared with the full qualified package name. Google Play requires that every Android application uses its own unique package. Therefore it is a good habit to use your reverse domain name as package name. This will avoid collisions with other Android applications.
  • 7. toandroiddeveloper@gmail.com Page 6 android:versionName and android:versionCode specify the version of your application. versionNameis what the user sees and can be any String. versionCode must be an integer. The Android Market determine based on the versionCode, if it should perform an update of the applications for the existing installations. You typically start with "1" and increase this value by one, if you roll-out a new version of your application. The tag <activity> defines an Activity, in this example pointing to the Convert class in thede.vogella.android.temperature package. An intent filter is registered for this class which defines that thisActivity is started once the application starts (action android:name="android.intent.action.MAIN"). The category definition category android:name="android.intent.category.LAUNCHER" defines that this application is added to the application directory on the Android device. The @string/app_name value refers to resource files which contain the actual value of the application name. The usage of resource file makes it easy to provide different resources, e.g. strings, colors, icons, for different devices and makes it easy to translate applications. The "uses-sdk" part of the "AndroidManifest.xml" file defines the minimal SDK version for which your application is valid. This will prevent your application being installed on devices with older SDK versions. 4.2. R.java and Resources The " gen " directory in an Android project contains generated values. R.java is a generated class which contains references to certain resources of the project. These resources must be defined in the "res" directory and can be XML files, icons or pictures. You can for example define values, menus, layouts or animations via XML files. If you create a new resource, the corresponding reference is automatically created in R.java via the Eclipse ADT tools. These references are static int values and define ID's for the resources. The Android system provides methods to access the corresponding resource via these ID's. For example to access a String with the R.string.yourString ID, you would use thegetString(R.string.yourString)) method. R.java is automatically created by the Eclipse development environment, manual changes are not necessary and will be overridden by the tooling. 4.3. Assets
  • 8. toandroiddeveloper@gmail.com Page 7 While the res directory contains structured values which are known to the Android platform, the assets directory can be used to store any kind of data. In Java you access this data via the AssetsManager and the getAssets()method . 4.4. Activities and Layouts The user interface for Activities is defined via layouts. The layout defines the included Views (widgets) and their properties. A layout can be defined via Java code or via XML. In most cases the layout is defined as an XML file. XML based layouts are defined via a resource file in the /res/layout folder. This file specifies the ViewGroups,Views, their relationship and their attributes for this specific layout. If a View needs to be accessed via Java code, you have to give the View a unique ID via the android:id attribute. To assign a new ID to a View use @+id/yourvalue. The following shows an example in which a Button gets the "button1" ID assigned. <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Preferences" > </Button> By conversion this will create and assign a new yourvalue ID to the corresponding View. In your Java code you can later access a View via the method findViewById(R.id.yourvalue). Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout definition. It also allows the definition of different layouts for different devices. You can also mix both approaches. 4.5. Reference to resources in XML files In your XML files, for example your layout files, you can refer to other resources via the @ sign. For example, if you want to refer to a color which is defined in a XML resource, you can refer to it via@color/your_id. Or if you defined a "hello" string in an XML resource, you could access it via @string/hello.
  • 9. toandroiddeveloper@gmail.com Page 8 4.6. Activities and Lifecycle The Android system controls the lifecycle of your application. At any time the Android system may stop or destroy your application, e.g. because of an incoming call. The Android system defines a lifecycle for Activities via predefined methods. The most important methods are: • onSaveInstanceState() - called if the Activity is stopped. Used to save data so that the Activitycan restore its states if re-started • onPause() - always called if the Activity ends, can be used to release resource or save data • onResume() - called if the Activity is re-started, can be used to initialize fields 4.7. Configuration Change An Activity will also be restarted, if a so called "configuration change" happens. A configuration change happens if an event is triggered which may be relevant for the application. For example if the user changes the orientation of the device (vertically or horizontally). Android assumes that an Activity might want to use different resources for these orientations and restarts the Activity. In the emulator you can simulate the change of the orientation via CNTR+F11. You can avoid a restart of your application for certain configuration changes via the configChanges attribute on your Activity definition in your AndroidManifest.xml. The following Activity will not be restarted in case of orientation changes or position of the physical keyboard (hidden / visible). <activity android:name=".ProgressTestActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|keyboard"> </activity> 4.8. Context The class android.content.Context provides the connections to the Android system. It is the interface to global information about the application environment. Context also provides access to Android Services, e.g. the Location Service. Activities and Services extend the Context class and can therefore be used asContext.
  • 10. toandroiddeveloper@gmail.com Page 9 1. SQLite and Android 1.1. What is SQLite 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. 250 KByte). 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 saving them 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. More information about SQLite can be found on the SQLite website: http://www.sqlite.org. 1.2. SQLite in Android SQLite is available on every Android device. Using an SQLite database in Android does not require any database setup or administration. 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 directoryDATA/data/APP_NAME/databases/FILENAME. The parts of the above directory are constructed based on the following rules. DATA is the path which theEnvironment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the name you specify in your application code for the database. 2. Prerequisites for this tutorial The following assumes that you have already basic knowledge in Android development. Please check the Android development tutorial to learn the basics. 3. SQLite Architecture 3.1. Packages
  • 11. toandroiddeveloper@gmail.com Page 10 The package android.database contains all general classes for working with databases.android.database.sqlite contains the SQLite specific classes. 3.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. onCreate() is called by the framework, if the database does not exists. onUpgrade() is called, if the database version is increased in your application code. 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 getWriteableDatabase() 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. Several Android functions rely on this standard. It is best practice to create a separate class per table. This class defines static onCreate() and onUpdate()methods. These methods are called in the corresponding methods of SQLiteOpenHelper. This way your implementation of SQLiteOpenHelper will stay readable, even if you have several tables. 3.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 .
  • 12. toandroiddeveloper@gmail.com Page 11 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. 3.4. rawQuery() Example The following gives an example of a rawQuery() call. Cursor cursor = getReadableDatabase(). rawQuery("select * from todo where _id = ?", new String[] { id }); 3.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. Table 1. 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.
  • 13. toandroiddeveloper@gmail.com Page 12 Parameter Comment 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. 3.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. TheisAfterLast() 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.
  • 14. toandroiddeveloper@gmail.com Page 13 Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the column index for a column name of the table. 3.7. ListViews, ListActivities and SimpleCursorAdapter 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. TheSimpleCursorAdapter 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. This tutorial will use ListActivities but not look into the details of them. 6. Android virtual device - Emulator 6.1. What is the Android Emulator? The Android Development Tools (ADT) includes an emulator to run an Android system. The emulator behaves like a real Android device (in most cases) and allows you to test your application without having a real device. You can configure the version of the Android system you would like to run, the size of the SD card, the screen resolution and other relevant settings. You can define several of them with different configurations. These devices are called "Android Virtual Device" (AVD) and you can start several in parallel. Starting a new emulator is very slow, because the file system of the new AVD needs to get prepared. The ADT allows to deploy and run your Android program on the AVD. 6.2. Google vs. Android AVD During the creation of an AVD you decide if you want an Android device or a Google device. An AVD created for Android will contain the programs from the Android Open Source Project. An AVD created for the Google API's will also contain several Google applications, most notable the Google Maps application.
  • 15. toandroiddeveloper@gmail.com Page 14 If you want to use functionality which is only provided via the Google API's, e.g. Cloud2DeviceMessaging or Google Maps you must run this application on an AVD with Google API's. 6.3. Emulator Shortcuts The following shortcuts are useful for working with the emulator. Alt+Enter Maximizes the emulator. Nice for demos. Ctrl+F11 changes the orientation of the emulator. F8 Turns network on / off. 6.4. Performance The graphics of the emulator are rendered in software, which is very slow. To have a responsive emulator use a small resolution for your emulator, as for example HVGA. Also if you have sufficient memory on your computer, add at least 1 GB of memory to your emulator. This is the value "Device ram size" during the creation of the AVD. 8. Error handling and typical problems Things are not always working as they should. This section gives an overview over typical problems and how to solve them. 8.1. Clean Project Several users report that get the following errors: 1. Project ... is missing required source folder: 'gen' 2. The project could not be built until build path errors are resolved. 3. Unable to open class file R.java. To solve any of these errors, go to the project menu and select Project → Clean. 8.2. Problems with Android Debug Bridge (adb) The communication with the emulator or your Android device might have problems. This communication is handled by the Android Debug Bridge (adb).
  • 16. toandroiddeveloper@gmail.com Page 15 Eclipse allows to reset the adb in case this causes problems. Select therefore the DDMS perspective via Window →Open Perspective → Other → DDMS To restart the adb, select the "Reset adb" in the Device View. 8.3. LogCat The "LogCat" View shows you the log messages of your Android device and help you analyze problems. For example Java exceptions in your program would be shown here. To open this view, select Window → Show View → Other →Android → LogCat. 8.4. Emulator does not start If your emulator does not start, make sure that the android-sdk version is in a path without any spaces in the path name. 8.5. Timeout during deployment If you face timeout issues during deployment you can increase the default timeout in the Eclipse preferences. SelectWindow → Preferences → Android → DDMS and increase the "ADB connection timeout (in ms)" value. 8.6. Install failed due to insufficient storage Sometimes the emulator will refuse to install an application with the error message: INSTALL_FAILED_INSUFFICIENT_STORAGE. An Android virtual device provides per default only 64M for the storaging Android applications. You can clean your installed application by re-starting the emulator and selecting the "Wipe user data" flag.
  • 17. toandroiddeveloper@gmail.com Page 16 Alternative you can set the the data partition size, if you press edit on the AVD you can set the "Ideal size of data partition" property via the "New" button. 8.7. Debug Certificate expired If you get the error message "Debug Certificate expired" switch to the folder which contains the Android AVD, e.g. ".android" under Linux and delete the "debug.keystore" file. This file is only valid for a year and if not present Eclipse will regenerate the password.
  • 18. toandroiddeveloper@gmail.com Page 17 8.8. Error message for @override The @override annotation was introduced in Java 1.6. If you receive an error message for @override, change the Java compiler level to Java 1.6. To do this right-click on the project, select Properties → Java Compiler → Compiler compliance level and select "1.6" in the drop-down box. 8.9. Missing Imports Java requires that classes which are not part of the standard Java Language be either fully qualified or declared via imports. If you see error message with "XX cannot be resolved to a variable", right-click in your Editor and select Source →Organize Imports to important required packages. 8.10. Eclipse Tips To work more efficiently with Eclipse, select Window → Preferences → Java → Editor → Save Actions and select that the source code should be formatted and that the imports should be organized at every save. 9. Conventions for the tutorials 9.1. API version, package and application name The tutorials of this document have been developed and tested with Android 4.0.3, API Level 15. Please use this version for all tutorials in this book. Higher version usually should also work. Lower version of the Android API might also work, but if you face issues, try the recommended version. The base package for the projects is always the same as the project name, e.g. if you are asked to create a project "de.vogella.android.example.test" then the corresponding package name is "de.vogella.android.example.test". The Application name, which must be entered on the Android project generation wizard, will not be predefined. Choose a name you like. 9.2. Warnings Messages for Strings The Android development tools are show warnings if you use hard-coded strings, for example in layout files. While for real application its best practice to use string resource files we use use Strings directly to simplify the creation of the examples.