SlideShare a Scribd company logo
Topics:
1. Android Project Structure in Eclipse:
Source
Standard Comments
Naming Conventions
Variable Scope
GEN
ANDROID <version number>
Referencing a library project
Add jar files into Android Project
ASSETS
BIN
RES
Drawable
Layout
Various Layouts in Android
Values
Menu
AndroidManifest.xml file
Topics:
AndroidManifest.xml file
Support different screen size in android
Android Exceptions
Upload apk into Android Market
2.Effective Eclipse
3.Best Code Review Tools for Eclipse
Android Project Structure in Eclipse:
When we start a new Android project in Eclipse, it will
automatically creates a lot of files and folders for us.
We will look at the meaning and functions of each of these folders
in the Android project structure one by one.
After you create a new project in eclipse, you will see the
following top-level folders in your package explorer.
Structure of the Android Project:
Here is the brief description of important files/folders in the Android
project structure:
/src: The src folder contains the Java source code files of your
application organized into packages.
You can have more than one package in your Android application.
Its always a good practice to break the source code of your application
into different packages based on its core functionality.
All the source files of your Activities, Services etc. Goes into this folder.
In the above screen, you can see the source file of the Activity that we
created for our project.
We have to follow few standards while coding in java Classes.
© Changepond Technologies 2010-11. All rights reserved.
Standard Comments:
Every file should have a copyright statement at the top.
Then a package statement and import statements should follow, each
block separated by a blank line.
Then there is the class or interface declaration. In the Javadoc
comments, describe what the class or interface does.
Every class and nontrivial public method you write must contain a
Javadoc comment with at least one sentence describing what the class
or method does. This sentence should start with a 3rd person
descriptive verb.
© Changepond Technologies 2010-11. All rights reserved.
Use TODO Comments:
Use TODO comments for code that is temporary, a short-term
solution, or good-enough but not perfect
TODOs should include the string TODO in all caps, followed by a
colon:
// TODO: Remove this code after the UrlTable2 has been checked in.
If your TODO is of the form "At a future date do something" make
sure that you either include a very specific date ("Fix by November
2005") or a very specific event ("Remove this code after all
production mixers understand protocol V7.").
© Changepond Technologies 2010-11. All rights reserved.
Order Import Statements:
The ordering of import statements is:
1. Android imports
2. Imports from third parties (com, junit, net, org)
3. java and javax
Note: import com.InternetGMBH.Sample.Utilities.*;
The wildcard character (*) is used to specify that all classes with that
package are available to your program.
So, it occupies the more memory in our application. So, import only
required classes of the packages like:
import com.InternetGMBH.Sample.Utilities.URLComposer;
© Changepond Technologies 2010-11. All rights reserved.
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.android.internal.foo;
import android.os.Blah;
import com.InternetGMBH.Sample.R;
import java.sql.ResultSet;
/**
* Does X and Y and provides an abstraction for Z.
*/
public class Foo {
...
/** Returns the correctly rounded positive square root of a double value. */
static double sqrt(double a) {
...
}
}
Syntax:
© Changepond Technologies 2010-11. All rights reserved.
Naming Conventions:
What is Naming Convention?
Why use Naming Conventions?
Picking Name for your Identifier
Standard Java Naming Conventions
© Changepond Technologies 2010-11. All rights reserved.
What is Naming Convention?
A naming convention is a rule to follow as you decide what to name
your identifiers (e.g. class, package, variable, method, etc..).
Why use Naming Conventions?
By using standard Java naming conventions they make their code
easier to read for themselves and for other programmers.
Readability of Java code is important because it means less time is
spent trying to figure out what the code does, leaving more time to fix
or modify it.
© Changepond Technologies 2010-11. All rights reserved.
Picking Name for your Identifier
When choosing a name for an identifier make sure it's meaningful.
For instance, if your program deals with customer accounts then
choose names that make sense to dealing with customers and their
accounts (EX: customerName, accountDetails). Don't worry about the
length of the name.
© Changepond Technologies 2010-11. All rights reserved.
Standard Java Naming Conventions
Packages:
Names should be in lowercase and the packages might be imported
into other classes, the names will normally be subdivided. Typically
this will start with the company domain before being split into layers
or features:
Example:
package com.mycompany.utilities
package org.bobscompany.application.userinterface
© Changepond Technologies 2010-11. All rights reserved.
Classes:
Names should be in CamelCase. Try to use nouns because a class is
normally representing something in the real world:
Ex: class Customer
class Account
Interfaces:
Names should be in CamelCase. They tend to have a name that
describes an operation that a class can do:
Ex: interface Comparable
interface Enumerable
© Changepond Technologies 2010-11. All rights reserved.
Methods:
Names should be in mixed case. Use verbs to describe what the
method does:
Ex: void calculateTax()
string getSurname()
Constants:
Names should be in uppercase.
Ex: static final int DEFAULT_WIDTH
static final int MAX_HEIGHT
© Changepond Technologies 2010-11. All rights reserved.
Variables:
Names should be in mixed case. The names should represent what the
value of the variable represents:
string firstName
int orderNumber
Only use very short names when the variables are short lived, such as
in for loops:
for (int i=0; i<20;i++)
{
//i only lives in here
}
© Changepond Technologies 2010-11. All rights reserved.
The scope of local variables should be kept to a minimum. By doing
so, you increase the readability and maintainability of your code and
reduce the likelihood of error.
Types of Scopes in Java:
1.Class Level Scope
2.Method Scope
3.Loop Scope
Variable Scope:
© Changepond Technologies 2010-11. All rights reserved.
Class Level Scope:
The scope of these variables will need to be at the class level, and
there is only one way to create variables at that level – just inside the
class but outside of any methods. Let's take a look at an example:
Ex: public Class User{
private String username;
}
Method Scope:
Some variables you might want to make temporary and
preferably they are used for only one method. This would be an
example of method scope.
Ex:public static void main(Strings[] args){
int x = 5;
}
© Changepond Technologies 2010-11. All rights reserved.
Loop Scope:
Any variables created inside of a loop are LOCAL TO THE
LOOP. This means that once you exit the loop, the variable can no
longer be accessed!
In the first example, x can ONLY be used inside of the for loop.
In the second example, you are free to use x inside of the loop as well
as outside of the loop because it was declared outside of the loop (it
has been declared at method scope).
© Changepond Technologies 2010-11. All rights reserved.
/GEN: The files in the gen folder are automatically generated by the
ADT. Here the R.java file contains reference/index to all the resources
in the res we use in our program. Each time we add a new resource to
the project, ADT will automatically regenerate the R.java file
containing reference to the newly added resource. You should not edit
the contents of R.java file manually or otherwise your application may
not compile.
/ANDROID <version number> : This folder is also called Android
target library in Android project structure. The version number will be
same as the build target version that we choose while creating a new
project. The android.jar file contains all the essential libraries required
for our program.
Let see, how to add library projects and jar file to our project.
© Changepond Technologies 2010-11. All rights reserved.
If you are developing an application and want to include the shared
code or resources from a library project, you can do so easily by
adding a reference to the library project in the application project's
Properties.
To add a reference to a library project, follow these steps:
1. In the Package Explorer, right-click the dependent project and select
Properties.
2. In the Properties window, select the "Android" properties group at
left and locate the Library properties at right.
3. Click Add to open the Project Selection dialog.
4. From the list of available library projects, select a project and click
OK.
5. When the dialog closes, click Apply in the Properties window.
6. Click OK to close the Properties window.
Referencing a library project:
© Changepond Technologies 2010-11. All rights reserved.
As soon as the Properties dialog closes, Eclipse rebuilds the project,
including the contents of the library project. Below figure shows the
Properties dialog that lets you add library references and move them
up and down in priority.
© Changepond Technologies 2010-11. All rights reserved.
Add Jar - to include jar files in you build path which are already present
in your project.
Add External jar - used to include jar files which are 'outside' your
eclipse project workspace folder.
To add to your Android Project, follow these steps:
1. In the Package Explorer, right-click the dependent project and select
Properties.
2. .In the Properties window, select the Java Build Path and then click
on Libraries Tab .
3. Here click on Add Jar's or Add External Jar's button and then browse
your jar file and select ok.
Add jar files into Android Project:
© Changepond Technologies 2010-11. All rights reserved.
Screen Shot:
© Changepond Technologies 2010-11. All rights reserved.
/ASSETS: The assets folder is used to store raw asset files. You can keep
any raw data in the assets folder and there’s an asset manager in
Android to read the data stored in the folder.
The raw data can be anything such as audio, video, images etc. On
important point about assets folder is that the data stored in this folder
can’t be referenced by an ID. To access a data in this folder, we have
to work with bits and bytes.
/BIN: /bin folder is where our compiled application files go. When we
successfully compile an application, this folder will contain java class
files, dex files which are executable under Dalvik virtual machine, apk
archives etc.
/ASSETS: The assets folder is used to store raw asset files. You can keep
any raw data in the assets folder and there’s an asset manager in
Android to read the data stored in the folder.
The raw data can be anything such as audio, video, images etc. On
important point about assets folder is that the data stored in this folder
can’t be referenced by an ID. To access a data in this folder, we have
to work with bits and bytes.
/BIN: /bin folder is where our compiled application files go. When we
successfully compile an application, this folder will contain java class
files, dex files which are executable under Dalvik virtual machine, apk
archives etc.
/ASSETS: The assets folder is used to store raw asset files. You can keep
any raw data in the assets folder and there’s an asset manager in
Android to read the data stored in the folder.
The raw data can be anything such as audio, video, images etc. On
important point about assets folder is that the data stored in this folder
can’t be referenced by an ID. To access a data in this folder, we have
to work with bits and bytes.
/BIN: /bin folder is where our compiled application files go. When we
successfully compile an application, this folder will contain java class
files, dex files which are executable under Dalvik virtual machine, apk
archives etc.
© Changepond Technologies 2010-11. All rights reserved.
/RES:Res folder is where we store all our external resources for our
applications such as images, layout XML files, strings, animations,
audio files etc.
Sub folders:
/res/drawable: This folder contains the bitmap file to be used in the
program. There are three different folders to store drawables.
They are drawable-ldpi, drawable-mdpi, drawable-hdpi. The folders
are to provide alternative image resources to specific screen
configurations. Ldpi, mdpi & hdpi stands for low density, medium
density & high density screens respectively.
The resources for each screen resolutions are stored in respective
folders and the android system will choose it according to the pixel
density of the device.
/res/layout: XML files that defines the User Interface goes in this folder.
We have different Layouts in android, Those are:
© Changepond Technologies 2010-11. All rights reserved.
1.LinearLayout : LinearLayout is used when we need to arrange the
widgets/views in a horizontal or vertical manner. The direction of
arrangement can be set to horizontal or vertical, by default it is being
horizontal.
2.TableLayout : If the Layout's widgets/views need to be arranged in
the form of rows and columns, we use this layout object. This is
similar to html tables. The cells can span columns.
TheTableLayout do not display its border. We can be made to shrink
and stretch by setting the respective properties of the columns
"TableRow" is another helper widget which should be used in
conjunction with the TableLayout.
Various Layouts in Android:
© Changepond Technologies 2010-11. All rights reserved.
3.RelativeLayout : Here the position of each of the widgets/view is in
relative/dependent to each other. For example, when a layout is
needed such that it has a text view just to the left of an Edit Textbox,
and a button just below the EditText. The relation between the views
are taken care in one iteration, hence if view B’s position is dependent
on view A’s position, view A must come first in the layout.
4.FrameLayout : This is a very simply layout which is used to hold a
section of the screen blank, for displaying an item or group of items at
runtime.
5.AbsoluteLayout : When there is a need is to specify exact x and y
co-ordinate position of the view, then AbsoluteLayout need to be used.
This layout is difficult to maintain.
© Changepond Technologies 2010-11. All rights reserved.
/res/values:This folder again contains XML files, which contain key
values pairs that will be referenced in the application.
These XML files declare Arrays, colors, dimensions, strings etc. The
main idea of having these values in a separate XML file is that the
values can be used based on the locale without actually changing the
source code.
/res/menu: XML files that define menus in your application goes in
this folder
© Changepond Technologies 2010-11. All rights reserved.
AndroidManifest.xml file:
AndroidManifest.xml is one of the most important file in the Android
project structure. It contains all the information about your
application.
When an application is launched, the first file the system seeks is
the AndroidManifest file. It actually works as a road map of your
application, for the system.
The Android Manifest file contains information about:
Components of your application such as Activities, services etc.

User permissions required

Minimum level of Android API required
The structure of the Manifest file is:
© Changepond Technologies 2010-11. All rights reserved.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="package of your application"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".Starting Activity Class Name"
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>
© Changepond Technologies 2010-11. All rights reserved.
Brief into Manifest File:

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.

android:versionName and android:versionCode specify the version of
your application.
versionName is 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.
© Changepond Technologies 2010-11. All rights reserved.

The <activity> tag defines an Activity, i.e Starting Activity Class
Name. An intent filter is registered for this class which defines that
this Activity 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 unsupported devices.
© Changepond Technologies 2010-11. All rights reserved.
For Different screen size, The following is a list of resource directories
in an application that provides different layout designs for different
screen sizes and different bitmap drawables for small, medium, high,
and extra high density screens. And few changes in Manifest file.
The following code in the Manifest supports all dpis.
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true" />
support different screen size in android :
© Changepond Technologies 2010-11. All rights reserved.
Add below shown drawable and layout folders in resource folder:
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-small/my_layout.xml // layout for small screen size
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape
orientation
res/drawable-mdpi/my_icon.png // bitmap for medium density
res/drawable-hdpi/my_icon.png // bitmap for high density
res/drawable-xhdpi/my_icon.png // bitmap for extra high density
Reference Link:
http://developer.android.com/training/multiscreen/screendensities.html
© Changepond Technologies 2010-11. All rights reserved.
Handle the error gracefully and substitute an appropriate value in the
catch {} block.
/** Set port. If value is not a valid number, 80 is substituted. */
void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
serverPort = 80; // default port for server
}
}
Handle the Exception:
© Changepond Technologies 2010-11. All rights reserved.
IllegalAccessException: Thrown when a program attempts to access a
field or method which is not accessible from the location where the
reference is made.
NullPointerException: Thrown when a program tries to access a field or
method of an object or an element of an array when there is no
instance or array to use, that is if the object or array points to null. It
also occurs in some other, less obvious circumstances, like a throw e
statement where the Throwable reference is null.
IllegalArgumentException: Thrown when a method is invoked with an
argument which it can not reasonably deal with. This can happen if the
user either dismisses the view (Ex: a dialog that can be backed out of)
or if the user switches to a different activity while your task is
running.
ClassNotFoundException: Thrown when a class loader is unable to find
a class.
Solution: compare the error to your Android Manifest very closely.
Few Exception in Android:
© Changepond Technologies 2010-11. All rights reserved.
Upload apk into Android Market:
Steps for Create a certificate for Android Market apk:
1. If you are using Eclipse for Development just right click on your
project and click export.
2. Now choose Android and then Export Android Application. In
the next step confirm the project that you want to export.
3. Then click next and now you should be able to select create new
keystore.
4. Now fill in the required fields and your should be able to sign
your app.
5. Be sure to make a backup of the keystore file and remember your
password. Losing this will make it impossible to update your
application.
Refer the Link:
http://ofps.oreilly.com/titles/9781449383268/ch08_id35815995.html
© Changepond Technologies 2010-11. All rights reserved.
Publishing Updates on Android Market :
1. At any time after publishing an application on Android Market,
you can upload and publish an update to the same application
package.
2. When you publish an update to an application, users who have
already installed the application may receive a notification that an
update is available for the application. They can then choose to update
the application to the latest version.
3. Before uploading the updated application, be sure that you have
incremented the android:versionCode and android:versionName
attributes in the element of the manifest file. Also, the package name
must be the same as the existing version and the .apk file must be
signed with the same private key.
© Changepond Technologies 2010-11. All rights reserved.
Go to manifestfile and set the version code like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name"
android:versionCode="2"
android:versionName="2.0" >
Here , old versioncode: 1 and new version code:2
4. If the package name and signing certificate do not match those of
the existing version, Market will consider it a new application, publish
it as such, and will not offer it to existing users as an update.
5. You have to have the same keystore file which you have used to
upload the 1st version of application on android market. If you have
lost this keystore file then you can't provide update to this application.
Note: Dont forgot to keep a backup of your keystore file.
Refer the Link:
http://developer.android.com/distribute/googleplay/publish/preparing.html
© Changepond Technologies 2010-11. All rights reserved.
Shortcut keys for using eclipse in effective way:
Ctrl+Shift+L which displays a list of all the keyboard shortcut
combinations (just in case you forget any of those listed here) .
Site For Eclipse Shortcut keys:
http://eclipse.dzone.com/news/effective-eclipse-shortcut-key
Effective Eclipse:
© Changepond Technologies 2010-11. All rights reserved.
FindBugs:
http://www.vogella.com/articles/Findbugs/article.html
PMD Tool:
http://about-android.blogspot.in/2010/03/android-codereview-tool-setup-pmd.html
Best Code Review Tools for Eclipse:

More Related Content

PDF
PDF
Add on packages
PPT
Understanding Annotations in Java
DOCX
The Seven Pillars Of Asp.Net
PPTX
Type Annotations in Java 8
PDF
Aspect-Oriented Programming and Depedency Injection
PDF
Java chapter 1
PPT
C Course Material0209
Add on packages
Understanding Annotations in Java
The Seven Pillars Of Asp.Net
Type Annotations in Java 8
Aspect-Oriented Programming and Depedency Injection
Java chapter 1
C Course Material0209

What's hot (20)

PPSX
Java annotations
DOCX
Notes of java first unit
PDF
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
PPTX
Java Annotations
PDF
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
PPTX
Application package
PDF
Java chapter 5
PPT
Annotations
PPT
Java Annotation
PDF
Creation of a Test Bed Environment for Core Java Applications using White Box...
PDF
Web Programming UNIT VIII notes
DOCX
C# Unit 2 notes
PDF
Multi-dimensional exploration of API usage - ICPC13 - 21-05-13
PDF
Aspect Oriented Programming Through C#.NET
PDF
Bt0074 oops with java
PDF
Understanding And Using Reflection
PDF
Opal Hermes - towards representative benchmarks
PPTX
Namespaces in C#
PPT
Java tutorial PPT
PDF
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Java annotations
Notes of java first unit
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
Java Annotations
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Application package
Java chapter 5
Annotations
Java Annotation
Creation of a Test Bed Environment for Core Java Applications using White Box...
Web Programming UNIT VIII notes
C# Unit 2 notes
Multi-dimensional exploration of API usage - ICPC13 - 21-05-13
Aspect Oriented Programming Through C#.NET
Bt0074 oops with java
Understanding And Using Reflection
Opal Hermes - towards representative benchmarks
Namespaces in C#
Java tutorial PPT
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Ad

Viewers also liked (20)

PPTX
Apply google coding rule to android studio
PDF
Mobile is still Fresh
PPTX
Best Coding Practices For Android Application Development
PPTX
As 9 musas da mitologia grega
PDF
서버성능개선 류우림
PPT
DLL Hijacking
PPT
Lecture 19 dynamic web - java - part 1
PPTX
Google drive training - Overview
PPTX
2 Slides Conditionals Iterators Blocks Hashes Arrays
PPS
Jdbc session01
PPTX
20080215 jbpm Business Process Simulation with Jboss jBPM
PDF
Desenvolvimento de Games para Nokia Asha
PDF
JUnit Tutorial for Beginners - Learn Java Unit Testing
PPTX
L21 io streams
PPT
Client Side Programming with Applet
PPTX
Webapplication development with HTML5 and GWT
PPT
Beasley ch9 v2
PPS
Comp tia a+_session_11
PDF
Rapid and Reliable Developing with HTML5 & GWT
PPT
01 intro+
Apply google coding rule to android studio
Mobile is still Fresh
Best Coding Practices For Android Application Development
As 9 musas da mitologia grega
서버성능개선 류우림
DLL Hijacking
Lecture 19 dynamic web - java - part 1
Google drive training - Overview
2 Slides Conditionals Iterators Blocks Hashes Arrays
Jdbc session01
20080215 jbpm Business Process Simulation with Jboss jBPM
Desenvolvimento de Games para Nokia Asha
JUnit Tutorial for Beginners - Learn Java Unit Testing
L21 io streams
Client Side Programming with Applet
Webapplication development with HTML5 and GWT
Beasley ch9 v2
Comp tia a+_session_11
Rapid and Reliable Developing with HTML5 & GWT
01 intro+
Ad

Similar to Android coding guide lines (20)

ODT
Android Open source coading guidel ine
PPT
2) java development
PPT
Synapseindia android apps introduction hello world
PDF
Perfomatix - Android Coding Standards
PDF
API design
PDF
ApiDesign
PDF
Android Application Development - Level 2
PPTX
java interface and packages
PDF
Api design
PPTX
Android Studio development model and.pptx
PPTX
API workshop: Deep dive into Java
PDF
Android session 1
PPTX
Android styles and themes
PPTX
Learning core java
PPTX
PPTX
Android Basic
PPTX
Android
PPTX
oop unit1.pptx
PPTX
PPT
Chapter 2 - Getting Started with Java
Android Open source coading guidel ine
2) java development
Synapseindia android apps introduction hello world
Perfomatix - Android Coding Standards
API design
ApiDesign
Android Application Development - Level 2
java interface and packages
Api design
Android Studio development model and.pptx
API workshop: Deep dive into Java
Android session 1
Android styles and themes
Learning core java
Android Basic
Android
oop unit1.pptx
Chapter 2 - Getting Started with Java

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Electronic commerce courselecture one. Pdf
PDF
KodekX | Application Modernization Development
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
Teaching material agriculture food technology
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Electronic commerce courselecture one. Pdf
KodekX | Application Modernization Development
Diabetes mellitus diagnosis method based random forest with bat algorithm
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Monthly Chronicles - July 2025
MYSQL Presentation for SQL database connectivity
Mobile App Security Testing_ A Comprehensive Guide.pdf
Teaching material agriculture food technology
madgavkar20181017ppt McKinsey Presentation.pdf
20250228 LYD VKU AI Blended-Learning.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Chapter 3 Spatial Domain Image Processing.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Android coding guide lines

  • 1. Topics: 1. Android Project Structure in Eclipse: Source Standard Comments Naming Conventions Variable Scope GEN ANDROID <version number> Referencing a library project Add jar files into Android Project ASSETS BIN RES Drawable Layout Various Layouts in Android Values Menu AndroidManifest.xml file
  • 2. Topics: AndroidManifest.xml file Support different screen size in android Android Exceptions Upload apk into Android Market 2.Effective Eclipse 3.Best Code Review Tools for Eclipse
  • 3. Android Project Structure in Eclipse: When we start a new Android project in Eclipse, it will automatically creates a lot of files and folders for us. We will look at the meaning and functions of each of these folders in the Android project structure one by one. After you create a new project in eclipse, you will see the following top-level folders in your package explorer.
  • 4. Structure of the Android Project:
  • 5. Here is the brief description of important files/folders in the Android project structure: /src: The src folder contains the Java source code files of your application organized into packages. You can have more than one package in your Android application. Its always a good practice to break the source code of your application into different packages based on its core functionality. All the source files of your Activities, Services etc. Goes into this folder. In the above screen, you can see the source file of the Activity that we created for our project. We have to follow few standards while coding in java Classes.
  • 6. © Changepond Technologies 2010-11. All rights reserved. Standard Comments: Every file should have a copyright statement at the top. Then a package statement and import statements should follow, each block separated by a blank line. Then there is the class or interface declaration. In the Javadoc comments, describe what the class or interface does. Every class and nontrivial public method you write must contain a Javadoc comment with at least one sentence describing what the class or method does. This sentence should start with a 3rd person descriptive verb.
  • 7. © Changepond Technologies 2010-11. All rights reserved. Use TODO Comments: Use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect TODOs should include the string TODO in all caps, followed by a colon: // TODO: Remove this code after the UrlTable2 has been checked in. If your TODO is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2005") or a very specific event ("Remove this code after all production mixers understand protocol V7.").
  • 8. © Changepond Technologies 2010-11. All rights reserved. Order Import Statements: The ordering of import statements is: 1. Android imports 2. Imports from third parties (com, junit, net, org) 3. java and javax Note: import com.InternetGMBH.Sample.Utilities.*; The wildcard character (*) is used to specify that all classes with that package are available to your program. So, it occupies the more memory in our application. So, import only required classes of the packages like: import com.InternetGMBH.Sample.Utilities.URLComposer;
  • 9. © Changepond Technologies 2010-11. All rights reserved. /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * http://www.apache.org/licenses/LICENSE-2.0 */ package com.android.internal.foo; import android.os.Blah; import com.InternetGMBH.Sample.R; import java.sql.ResultSet; /** * Does X and Y and provides an abstraction for Z. */ public class Foo { ... /** Returns the correctly rounded positive square root of a double value. */ static double sqrt(double a) { ... } } Syntax:
  • 10. © Changepond Technologies 2010-11. All rights reserved. Naming Conventions: What is Naming Convention? Why use Naming Conventions? Picking Name for your Identifier Standard Java Naming Conventions
  • 11. © Changepond Technologies 2010-11. All rights reserved. What is Naming Convention? A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..). Why use Naming Conventions? By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.
  • 12. © Changepond Technologies 2010-11. All rights reserved. Picking Name for your Identifier When choosing a name for an identifier make sure it's meaningful. For instance, if your program deals with customer accounts then choose names that make sense to dealing with customers and their accounts (EX: customerName, accountDetails). Don't worry about the length of the name.
  • 13. © Changepond Technologies 2010-11. All rights reserved. Standard Java Naming Conventions Packages: Names should be in lowercase and the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features: Example: package com.mycompany.utilities package org.bobscompany.application.userinterface
  • 14. © Changepond Technologies 2010-11. All rights reserved. Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world: Ex: class Customer class Account Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do: Ex: interface Comparable interface Enumerable
  • 15. © Changepond Technologies 2010-11. All rights reserved. Methods: Names should be in mixed case. Use verbs to describe what the method does: Ex: void calculateTax() string getSurname() Constants: Names should be in uppercase. Ex: static final int DEFAULT_WIDTH static final int MAX_HEIGHT
  • 16. © Changepond Technologies 2010-11. All rights reserved. Variables: Names should be in mixed case. The names should represent what the value of the variable represents: string firstName int orderNumber Only use very short names when the variables are short lived, such as in for loops: for (int i=0; i<20;i++) { //i only lives in here }
  • 17. © Changepond Technologies 2010-11. All rights reserved. The scope of local variables should be kept to a minimum. By doing so, you increase the readability and maintainability of your code and reduce the likelihood of error. Types of Scopes in Java: 1.Class Level Scope 2.Method Scope 3.Loop Scope Variable Scope:
  • 18. © Changepond Technologies 2010-11. All rights reserved. Class Level Scope: The scope of these variables will need to be at the class level, and there is only one way to create variables at that level – just inside the class but outside of any methods. Let's take a look at an example: Ex: public Class User{ private String username; } Method Scope: Some variables you might want to make temporary and preferably they are used for only one method. This would be an example of method scope. Ex:public static void main(Strings[] args){ int x = 5; }
  • 19. © Changepond Technologies 2010-11. All rights reserved. Loop Scope: Any variables created inside of a loop are LOCAL TO THE LOOP. This means that once you exit the loop, the variable can no longer be accessed! In the first example, x can ONLY be used inside of the for loop. In the second example, you are free to use x inside of the loop as well as outside of the loop because it was declared outside of the loop (it has been declared at method scope).
  • 20. © Changepond Technologies 2010-11. All rights reserved. /GEN: The files in the gen folder are automatically generated by the ADT. Here the R.java file contains reference/index to all the resources in the res we use in our program. Each time we add a new resource to the project, ADT will automatically regenerate the R.java file containing reference to the newly added resource. You should not edit the contents of R.java file manually or otherwise your application may not compile. /ANDROID <version number> : This folder is also called Android target library in Android project structure. The version number will be same as the build target version that we choose while creating a new project. The android.jar file contains all the essential libraries required for our program. Let see, how to add library projects and jar file to our project.
  • 21. © Changepond Technologies 2010-11. All rights reserved. If you are developing an application and want to include the shared code or resources from a library project, you can do so easily by adding a reference to the library project in the application project's Properties. To add a reference to a library project, follow these steps: 1. In the Package Explorer, right-click the dependent project and select Properties. 2. In the Properties window, select the "Android" properties group at left and locate the Library properties at right. 3. Click Add to open the Project Selection dialog. 4. From the list of available library projects, select a project and click OK. 5. When the dialog closes, click Apply in the Properties window. 6. Click OK to close the Properties window. Referencing a library project:
  • 22. © Changepond Technologies 2010-11. All rights reserved. As soon as the Properties dialog closes, Eclipse rebuilds the project, including the contents of the library project. Below figure shows the Properties dialog that lets you add library references and move them up and down in priority.
  • 23. © Changepond Technologies 2010-11. All rights reserved. Add Jar - to include jar files in you build path which are already present in your project. Add External jar - used to include jar files which are 'outside' your eclipse project workspace folder. To add to your Android Project, follow these steps: 1. In the Package Explorer, right-click the dependent project and select Properties. 2. .In the Properties window, select the Java Build Path and then click on Libraries Tab . 3. Here click on Add Jar's or Add External Jar's button and then browse your jar file and select ok. Add jar files into Android Project:
  • 24. © Changepond Technologies 2010-11. All rights reserved. Screen Shot:
  • 25. © Changepond Technologies 2010-11. All rights reserved. /ASSETS: The assets folder is used to store raw asset files. You can keep any raw data in the assets folder and there’s an asset manager in Android to read the data stored in the folder. The raw data can be anything such as audio, video, images etc. On important point about assets folder is that the data stored in this folder can’t be referenced by an ID. To access a data in this folder, we have to work with bits and bytes. /BIN: /bin folder is where our compiled application files go. When we successfully compile an application, this folder will contain java class files, dex files which are executable under Dalvik virtual machine, apk archives etc. /ASSETS: The assets folder is used to store raw asset files. You can keep any raw data in the assets folder and there’s an asset manager in Android to read the data stored in the folder. The raw data can be anything such as audio, video, images etc. On important point about assets folder is that the data stored in this folder can’t be referenced by an ID. To access a data in this folder, we have to work with bits and bytes. /BIN: /bin folder is where our compiled application files go. When we successfully compile an application, this folder will contain java class files, dex files which are executable under Dalvik virtual machine, apk archives etc. /ASSETS: The assets folder is used to store raw asset files. You can keep any raw data in the assets folder and there’s an asset manager in Android to read the data stored in the folder. The raw data can be anything such as audio, video, images etc. On important point about assets folder is that the data stored in this folder can’t be referenced by an ID. To access a data in this folder, we have to work with bits and bytes. /BIN: /bin folder is where our compiled application files go. When we successfully compile an application, this folder will contain java class files, dex files which are executable under Dalvik virtual machine, apk archives etc.
  • 26. © Changepond Technologies 2010-11. All rights reserved. /RES:Res folder is where we store all our external resources for our applications such as images, layout XML files, strings, animations, audio files etc. Sub folders: /res/drawable: This folder contains the bitmap file to be used in the program. There are three different folders to store drawables. They are drawable-ldpi, drawable-mdpi, drawable-hdpi. The folders are to provide alternative image resources to specific screen configurations. Ldpi, mdpi & hdpi stands for low density, medium density & high density screens respectively. The resources for each screen resolutions are stored in respective folders and the android system will choose it according to the pixel density of the device. /res/layout: XML files that defines the User Interface goes in this folder. We have different Layouts in android, Those are:
  • 27. © Changepond Technologies 2010-11. All rights reserved. 1.LinearLayout : LinearLayout is used when we need to arrange the widgets/views in a horizontal or vertical manner. The direction of arrangement can be set to horizontal or vertical, by default it is being horizontal. 2.TableLayout : If the Layout's widgets/views need to be arranged in the form of rows and columns, we use this layout object. This is similar to html tables. The cells can span columns. TheTableLayout do not display its border. We can be made to shrink and stretch by setting the respective properties of the columns "TableRow" is another helper widget which should be used in conjunction with the TableLayout. Various Layouts in Android:
  • 28. © Changepond Technologies 2010-11. All rights reserved. 3.RelativeLayout : Here the position of each of the widgets/view is in relative/dependent to each other. For example, when a layout is needed such that it has a text view just to the left of an Edit Textbox, and a button just below the EditText. The relation between the views are taken care in one iteration, hence if view B’s position is dependent on view A’s position, view A must come first in the layout. 4.FrameLayout : This is a very simply layout which is used to hold a section of the screen blank, for displaying an item or group of items at runtime. 5.AbsoluteLayout : When there is a need is to specify exact x and y co-ordinate position of the view, then AbsoluteLayout need to be used. This layout is difficult to maintain.
  • 29. © Changepond Technologies 2010-11. All rights reserved. /res/values:This folder again contains XML files, which contain key values pairs that will be referenced in the application. These XML files declare Arrays, colors, dimensions, strings etc. The main idea of having these values in a separate XML file is that the values can be used based on the locale without actually changing the source code. /res/menu: XML files that define menus in your application goes in this folder
  • 30. © Changepond Technologies 2010-11. All rights reserved. AndroidManifest.xml file: AndroidManifest.xml is one of the most important file in the Android project structure. It contains all the information about your application. When an application is launched, the first file the system seeks is the AndroidManifest file. It actually works as a road map of your application, for the system. The Android Manifest file contains information about: Components of your application such as Activities, services etc.  User permissions required  Minimum level of Android API required The structure of the Manifest file is:
  • 31. © Changepond Technologies 2010-11. All rights reserved. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="package of your application" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Starting Activity Class Name" 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>
  • 32. © Changepond Technologies 2010-11. All rights reserved. Brief into Manifest File:  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.  android:versionName and android:versionCode specify the version of your application. versionName is 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.
  • 33. © Changepond Technologies 2010-11. All rights reserved.  The <activity> tag defines an Activity, i.e Starting Activity Class Name. An intent filter is registered for this class which defines that this Activity 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 unsupported devices.
  • 34. © Changepond Technologies 2010-11. All rights reserved. For Different screen size, The following is a list of resource directories in an application that provides different layout designs for different screen sizes and different bitmap drawables for small, medium, high, and extra high density screens. And few changes in Manifest file. The following code in the Manifest supports all dpis. <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" /> support different screen size in android :
  • 35. © Changepond Technologies 2010-11. All rights reserved. Add below shown drawable and layout folders in resource folder: res/layout/my_layout.xml // layout for normal screen size ("default") res/layout-small/my_layout.xml // layout for small screen size res/layout-large/my_layout.xml // layout for large screen size res/layout-xlarge/my_layout.xml // layout for extra large screen size res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation res/drawable-mdpi/my_icon.png // bitmap for medium density res/drawable-hdpi/my_icon.png // bitmap for high density res/drawable-xhdpi/my_icon.png // bitmap for extra high density Reference Link: http://developer.android.com/training/multiscreen/screendensities.html
  • 36. © Changepond Technologies 2010-11. All rights reserved. Handle the error gracefully and substitute an appropriate value in the catch {} block. /** Set port. If value is not a valid number, 80 is substituted. */ void setServerPort(String value) { try { serverPort = Integer.parseInt(value); } catch (NumberFormatException e) { serverPort = 80; // default port for server } } Handle the Exception:
  • 37. © Changepond Technologies 2010-11. All rights reserved. IllegalAccessException: Thrown when a program attempts to access a field or method which is not accessible from the location where the reference is made. NullPointerException: Thrown when a program tries to access a field or method of an object or an element of an array when there is no instance or array to use, that is if the object or array points to null. It also occurs in some other, less obvious circumstances, like a throw e statement where the Throwable reference is null. IllegalArgumentException: Thrown when a method is invoked with an argument which it can not reasonably deal with. This can happen if the user either dismisses the view (Ex: a dialog that can be backed out of) or if the user switches to a different activity while your task is running. ClassNotFoundException: Thrown when a class loader is unable to find a class. Solution: compare the error to your Android Manifest very closely. Few Exception in Android:
  • 38. © Changepond Technologies 2010-11. All rights reserved. Upload apk into Android Market: Steps for Create a certificate for Android Market apk: 1. If you are using Eclipse for Development just right click on your project and click export. 2. Now choose Android and then Export Android Application. In the next step confirm the project that you want to export. 3. Then click next and now you should be able to select create new keystore. 4. Now fill in the required fields and your should be able to sign your app. 5. Be sure to make a backup of the keystore file and remember your password. Losing this will make it impossible to update your application. Refer the Link: http://ofps.oreilly.com/titles/9781449383268/ch08_id35815995.html
  • 39. © Changepond Technologies 2010-11. All rights reserved. Publishing Updates on Android Market : 1. At any time after publishing an application on Android Market, you can upload and publish an update to the same application package. 2. When you publish an update to an application, users who have already installed the application may receive a notification that an update is available for the application. They can then choose to update the application to the latest version. 3. Before uploading the updated application, be sure that you have incremented the android:versionCode and android:versionName attributes in the element of the manifest file. Also, the package name must be the same as the existing version and the .apk file must be signed with the same private key.
  • 40. © Changepond Technologies 2010-11. All rights reserved. Go to manifestfile and set the version code like this: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name" android:versionCode="2" android:versionName="2.0" > Here , old versioncode: 1 and new version code:2 4. If the package name and signing certificate do not match those of the existing version, Market will consider it a new application, publish it as such, and will not offer it to existing users as an update. 5. You have to have the same keystore file which you have used to upload the 1st version of application on android market. If you have lost this keystore file then you can't provide update to this application. Note: Dont forgot to keep a backup of your keystore file. Refer the Link: http://developer.android.com/distribute/googleplay/publish/preparing.html
  • 41. © Changepond Technologies 2010-11. All rights reserved. Shortcut keys for using eclipse in effective way: Ctrl+Shift+L which displays a list of all the keyboard shortcut combinations (just in case you forget any of those listed here) . Site For Eclipse Shortcut keys: http://eclipse.dzone.com/news/effective-eclipse-shortcut-key Effective Eclipse:
  • 42. © Changepond Technologies 2010-11. All rights reserved. FindBugs: http://www.vogella.com/articles/Findbugs/article.html PMD Tool: http://about-android.blogspot.in/2010/03/android-codereview-tool-setup-pmd.html Best Code Review Tools for Eclipse: