Android coding guide lines

42
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

Transcript of Android coding guide lines

Page 1: Android coding guide lines

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

Page 2: Android coding guide lines

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

Page 3: Android coding guide lines

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.

Page 4: Android coding guide lines

Structure of the Android Project:

Page 5: Android coding guide lines

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.

Page 6: Android coding guide lines

© 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.

Page 7: Android coding guide lines

© 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.").

Page 8: Android coding guide lines

© 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;

Page 9: Android coding guide lines

© 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:

Page 10: Android coding guide lines

© 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

Page 11: Android coding guide lines

© 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.

Page 12: Android coding guide lines

© 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.

Page 13: Android coding guide lines

© 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

Page 14: Android coding guide lines

© 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

Page 15: Android coding guide lines

© 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

Page 16: Android coding guide lines

© 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

}

Page 17: Android coding guide lines

© 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:

Page 18: Android coding guide lines

© 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;

}

Page 19: Android coding guide lines

© 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).

Page 20: Android coding guide lines

© 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.

Page 21: Android coding guide lines

© 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:

Page 22: Android coding guide lines

© 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.

Page 23: Android coding guide lines

© 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:

Page 24: Android coding guide lines

© Changepond Technologies 2010-11. All rights reserved.

Screen Shot:

Page 25: Android coding guide lines

© 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.

Page 26: Android coding guide lines

© 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:

Page 27: Android coding guide lines

© 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:

Page 28: Android coding guide lines

© 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.

Page 29: Android coding guide lines

© 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

Page 30: Android coding guide lines

© 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:

Page 31: Android coding guide lines

© 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>

Page 32: Android coding guide lines

© 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.

Page 33: Android coding guide lines

© 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.

Page 34: Android coding guide lines

© 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 :

Page 35: Android coding guide lines

© 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

Page 36: Android coding guide lines

© 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:

Page 37: Android coding guide lines

© 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:

Page 38: Android coding guide lines

© 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

Page 39: Android coding guide lines

© 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.

Page 40: Android coding guide lines

© 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

Page 41: Android coding guide lines

© 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:

Page 42: Android coding guide lines

© 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: