Your SlideShare is downloading. ×
0
Topics:1. Android Project Structure in Eclipse:SourceStandard CommentsNaming ConventionsVariable ScopeGENANDROID <version ...
Topics:AndroidManifest.xml fileSupport different screen size in androidAndroid ExceptionsUpload apk into Android Market2.E...
Android Project Structure in Eclipse:When we start a new Android project in Eclipse, it willautomatically creates a lot of...
Structure of the Android Project:
Here is the brief description of important files/folders in the Androidproject structure:/src: The src folder contains the...
© Changepond Technologies 2010-11. All rights reserved.Standard Comments:Every file should have a copyright statement at t...
© Changepond Technologies 2010-11. All rights reserved.Use TODO Comments:Use TODO comments for code that is temporary, a s...
© Changepond Technologies 2010-11. All rights reserved.Order Import Statements:The ordering of import statements is:1. And...
© Changepond Technologies 2010-11. All rights reserved./** Copyright (C) 2010 The Android Open Source Project** Licensed u...
© Changepond Technologies 2010-11. All rights reserved.Naming Conventions:What is Naming Convention?Why use Naming Convent...
© Changepond Technologies 2010-11. All rights reserved.What is Naming Convention?A naming convention is a rule to follow a...
© Changepond Technologies 2010-11. All rights reserved.Picking Name for your IdentifierWhen choosing a name for an identif...
© Changepond Technologies 2010-11. All rights reserved.Standard Java Naming ConventionsPackages:Names should be in lowerca...
© Changepond Technologies 2010-11. All rights reserved.Classes:Names should be in CamelCase. Try to use nouns because a cl...
© Changepond Technologies 2010-11. All rights reserved.Methods:Names should be in mixed case. Use verbs to describe what t...
© Changepond Technologies 2010-11. All rights reserved.Variables:Names should be in mixed case. The names should represent...
© Changepond Technologies 2010-11. All rights reserved.The scope of local variables should be kept to a minimum. By doings...
© Changepond Technologies 2010-11. All rights reserved.Class Level Scope:The scope of these variables will need to be at t...
© Changepond Technologies 2010-11. All rights reserved.Loop Scope:Any variables created inside of a loop are LOCAL TO THEL...
© Changepond Technologies 2010-11. All rights reserved./GEN: The files in the gen folder are automatically generated by th...
© Changepond Technologies 2010-11. All rights reserved.If you are developing an application and want to include the shared...
© Changepond Technologies 2010-11. All rights reserved.As soon as the Properties dialog closes, Eclipse rebuilds the proje...
© Changepond Technologies 2010-11. All rights reserved.Add Jar - to include jar files in you build path which are already ...
© 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 ca...
© Changepond Technologies 2010-11. All rights reserved./RES:Res folder is where we store all our external resources for ou...
© Changepond Technologies 2010-11. All rights reserved.1.LinearLayout : LinearLayout is used when we need to arrange thewi...
© Changepond Technologies 2010-11. All rights reserved.3.RelativeLayout : Here the position of each of the widgets/view is...
© Changepond Technologies 2010-11. All rights reserved./res/values:This folder again contains XML files, which contain key...
© Changepond Technologies 2010-11. All rights reserved.AndroidManifest.xml file:AndroidManifest.xml is one of the most imp...
© Changepond Technologies 2010-11. All rights reserved.<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http...
© Changepond Technologies 2010-11. All rights reserved.Brief into Manifest File:The package attribute defines the base pa...
© Changepond Technologies 2010-11. All rights reserved.The <activity> tag defines an Activity, i.e Starting Activity Clas...
© Changepond Technologies 2010-11. All rights reserved.For Different screen size, The following is a list of resource dire...
© Changepond Technologies 2010-11. All rights reserved.Add below shown drawable and layout folders in resource folder:res/...
© Changepond Technologies 2010-11. All rights reserved.Handle the error gracefully and substitute an appropriate value in ...
© Changepond Technologies 2010-11. All rights reserved.IllegalAccessException: Thrown when a program attempts to access af...
© Changepond Technologies 2010-11. All rights reserved.Upload apk into Android Market:Steps for Create a certificate for A...
© Changepond Technologies 2010-11. All rights reserved.Publishing Updates on Android Market :1. At any time after publishi...
© Changepond Technologies 2010-11. All rights reserved.Go to manifestfile and set the version code like this:<manifest xml...
© Changepond Technologies 2010-11. All rights reserved.Shortcut keys for using eclipse in effective way:Ctrl+Shift+L which...
© Changepond Technologies 2010-11. All rights reserved.FindBugs:http://www.vogella.com/articles/Findbugs/article.htmlPMD T...
Upcoming SlideShare
Loading in...5
×

Android coding guide lines

329

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
329
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
18
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Android coding guide lines"

  1. 1. Topics:1. Android Project Structure in Eclipse:SourceStandard CommentsNaming ConventionsVariable ScopeGENANDROID <version number>Referencing a library projectAdd jar files into Android ProjectASSETSBINRESDrawableLayoutVarious Layouts in AndroidValuesMenuAndroidManifest.xml file
  2. 2. Topics:AndroidManifest.xml fileSupport different screen size in androidAndroid ExceptionsUpload apk into Android Market2.Effective Eclipse3.Best Code Review Tools for Eclipse
  3. 3. Android Project Structure in Eclipse:When we start a new Android project in Eclipse, it willautomatically creates a lot of files and folders for us.We will look at the meaning and functions of each of these foldersin the Android project structure one by one.After you create a new project in eclipse, you will see thefollowing top-level folders in your package explorer.
  4. 4. Structure of the Android Project:
  5. 5. Here is the brief description of important files/folders in the Androidproject structure:/src: The src folder contains the Java source code files of yourapplication 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 applicationinto 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 wecreated for our project.We have to follow few standards while coding in java Classes.
  6. 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, eachblock separated by a blank line.Then there is the class or interface declaration. In the Javadoccomments, describe what the class or interface does.Every class and nontrivial public method you write must contain aJavadoc comment with at least one sentence describing what the classor method does. This sentence should start with a 3rd persondescriptive verb.
  7. 7. © Changepond Technologies 2010-11. All rights reserved.Use TODO Comments:Use TODO comments for code that is temporary, a short-termsolution, or good-enough but not perfectTODOs should include the string TODO in all caps, followed by acolon:// TODO: Remove this code after the UrlTable2 has been checked in.If your TODO is of the form "At a future date do something" makesure that you either include a very specific date ("Fix by November2005") or a very specific event ("Remove this code after allproduction mixers understand protocol V7.").
  8. 8. © Changepond Technologies 2010-11. All rights reserved.Order Import Statements:The ordering of import statements is:1. Android imports2. Imports from third parties (com, junit, net, org)3. java and javaxNote: import com.InternetGMBH.Sample.Utilities.*;The wildcard character (*) is used to specify that all classes with thatpackage are available to your program.So, it occupies the more memory in our application. So, import onlyrequired classes of the packages like:import com.InternetGMBH.Sample.Utilities.URLComposer;
  9. 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. 10. © Changepond Technologies 2010-11. All rights reserved.Naming Conventions:What is Naming Convention?Why use Naming Conventions?Picking Name for your IdentifierStandard Java Naming Conventions
  11. 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 nameyour identifiers (e.g. class, package, variable, method, etc..).Why use Naming Conventions?By using standard Java naming conventions they make their codeeasier to read for themselves and for other programmers.Readability of Java code is important because it means less time isspent trying to figure out what the code does, leaving more time to fixor modify it.
  12. 12. © Changepond Technologies 2010-11. All rights reserved.Picking Name for your IdentifierWhen choosing a name for an identifier make sure its meaningful.For instance, if your program deals with customer accounts thenchoose names that make sense to dealing with customers and theiraccounts (EX: customerName, accountDetails). Dont worry about thelength of the name.
  13. 13. © Changepond Technologies 2010-11. All rights reserved.Standard Java Naming ConventionsPackages:Names should be in lowercase and the packages might be importedinto other classes, the names will normally be subdivided. Typicallythis will start with the company domain before being split into layersor features:Example:package com.mycompany.utilitiespackage org.bobscompany.application.userinterface
  14. 14. © Changepond Technologies 2010-11. All rights reserved.Classes:Names should be in CamelCase. Try to use nouns because a class isnormally representing something in the real world:Ex: class Customerclass AccountInterfaces:Names should be in CamelCase. They tend to have a name thatdescribes an operation that a class can do:Ex: interface Comparableinterface Enumerable
  15. 15. © Changepond Technologies 2010-11. All rights reserved.Methods:Names should be in mixed case. Use verbs to describe what themethod does:Ex: void calculateTax()string getSurname()Constants:Names should be in uppercase.Ex: static final int DEFAULT_WIDTHstatic final int MAX_HEIGHT
  16. 16. © Changepond Technologies 2010-11. All rights reserved.Variables:Names should be in mixed case. The names should represent what thevalue of the variable represents:string firstNameint orderNumberOnly use very short names when the variables are short lived, such asin for loops:for (int i=0; i<20;i++){//i only lives in here}
  17. 17. © Changepond Technologies 2010-11. All rights reserved.The scope of local variables should be kept to a minimum. By doingso, you increase the readability and maintainability of your code andreduce the likelihood of error.Types of Scopes in Java:1.Class Level Scope2.Method Scope3.Loop ScopeVariable Scope:
  18. 18. © Changepond Technologies 2010-11. All rights reserved.Class Level Scope:The scope of these variables will need to be at the class level, andthere is only one way to create variables at that level – just inside theclass but outside of any methods. Lets take a look at an example:Ex: public Class User{private String username;}Method Scope:Some variables you might want to make temporary andpreferably they are used for only one method. This would be anexample of method scope.Ex:public static void main(Strings[] args){int x = 5;}
  19. 19. © Changepond Technologies 2010-11. All rights reserved.Loop Scope:Any variables created inside of a loop are LOCAL TO THELOOP. This means that once you exit the loop, the variable can nolonger 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 wellas outside of the loop because it was declared outside of the loop (ithas been declared at method scope).
  20. 20. © Changepond Technologies 2010-11. All rights reserved./GEN: The files in the gen folder are automatically generated by theADT. Here the R.java file contains reference/index to all the resourcesin the res we use in our program. Each time we add a new resource tothe project, ADT will automatically regenerate the R.java filecontaining reference to the newly added resource. You should not editthe contents of R.java file manually or otherwise your application maynot compile./ANDROID <version number> : This folder is also called Androidtarget library in Android project structure. The version number will besame as the build target version that we choose while creating a newproject. The android.jar file contains all the essential libraries requiredfor our program.Let see, how to add library projects and jar file to our project.
  21. 21. © Changepond Technologies 2010-11. All rights reserved.If you are developing an application and want to include the sharedcode or resources from a library project, you can do so easily byadding a reference to the library project in the application projectsProperties.To add a reference to a library project, follow these steps:1. In the Package Explorer, right-click the dependent project and selectProperties.2. In the Properties window, select the "Android" properties group atleft 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 clickOK.5. When the dialog closes, click Apply in the Properties window.6. Click OK to close the Properties window.Referencing a library project:
  22. 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 theProperties dialog that lets you add library references and move themup and down in priority.
  23. 23. © Changepond Technologies 2010-11. All rights reserved.Add Jar - to include jar files in you build path which are already presentin your project.Add External jar - used to include jar files which are outside youreclipse project workspace folder.To add to your Android Project, follow these steps:1. In the Package Explorer, right-click the dependent project and selectProperties.2. .In the Properties window, select the Java Build Path and then clickon Libraries Tab .3. Here click on Add Jars or Add External Jars button and then browseyour jar file and select ok.Add jar files into Android Project:
  24. 24. © Changepond Technologies 2010-11. All rights reserved.Screen Shot:
  25. 25. © Changepond Technologies 2010-11. All rights reserved./ASSETS: The assets folder is used to store raw asset files. You can keepany raw data in the assets folder and there’s an asset manager inAndroid to read the data stored in the folder.The raw data can be anything such as audio, video, images etc. Onimportant point about assets folder is that the data stored in this foldercan’t be referenced by an ID. To access a data in this folder, we haveto work with bits and bytes./BIN: /bin folder is where our compiled application files go. When wesuccessfully compile an application, this folder will contain java classfiles, dex files which are executable under Dalvik virtual machine, apkarchives etc./ASSETS: The assets folder is used to store raw asset files. You can keepany raw data in the assets folder and there’s an asset manager inAndroid to read the data stored in the folder.The raw data can be anything such as audio, video, images etc. Onimportant point about assets folder is that the data stored in this foldercan’t be referenced by an ID. To access a data in this folder, we haveto work with bits and bytes./BIN: /bin folder is where our compiled application files go. When wesuccessfully compile an application, this folder will contain java classfiles, dex files which are executable under Dalvik virtual machine, apkarchives etc./ASSETS: The assets folder is used to store raw asset files. You can keepany raw data in the assets folder and there’s an asset manager inAndroid to read the data stored in the folder.The raw data can be anything such as audio, video, images etc. Onimportant point about assets folder is that the data stored in this foldercan’t be referenced by an ID. To access a data in this folder, we haveto work with bits and bytes./BIN: /bin folder is where our compiled application files go. When wesuccessfully compile an application, this folder will contain java classfiles, dex files which are executable under Dalvik virtual machine, apkarchives etc.
  26. 26. © Changepond Technologies 2010-11. All rights reserved./RES:Res folder is where we store all our external resources for ourapplications 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 theprogram. There are three different folders to store drawables.They are drawable-ldpi, drawable-mdpi, drawable-hdpi. The foldersare to provide alternative image resources to specific screenconfigurations. Ldpi, mdpi & hdpi stands for low density, mediumdensity & high density screens respectively.The resources for each screen resolutions are stored in respectivefolders and the android system will choose it according to the pixeldensity 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. 27. © Changepond Technologies 2010-11. All rights reserved.1.LinearLayout : LinearLayout is used when we need to arrange thewidgets/views in a horizontal or vertical manner. The direction ofarrangement can be set to horizontal or vertical, by default it is beinghorizontal.2.TableLayout : If the Layouts widgets/views need to be arranged inthe form of rows and columns, we use this layout object. This issimilar to html tables. The cells can span columns.TheTableLayout do not display its border. We can be made to shrinkand stretch by setting the respective properties of the columns"TableRow" is another helper widget which should be used inconjunction with the TableLayout.Various Layouts in Android:
  28. 28. © Changepond Technologies 2010-11. All rights reserved.3.RelativeLayout : Here the position of each of the widgets/view is inrelative/dependent to each other. For example, when a layout isneeded 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 viewsare taken care in one iteration, hence if view B’s position is dependenton 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 asection of the screen blank, for displaying an item or group of items atruntime.5.AbsoluteLayout : When there is a need is to specify exact x and yco-ordinate position of the view, then AbsoluteLayout need to be used.This layout is difficult to maintain.
  29. 29. © Changepond Technologies 2010-11. All rights reserved./res/values:This folder again contains XML files, which contain keyvalues pairs that will be referenced in the application.These XML files declare Arrays, colors, dimensions, strings etc. Themain idea of having these values in a separate XML file is that thevalues can be used based on the locale without actually changing thesource code./res/menu: XML files that define menus in your application goes inthis folder
  30. 30. © Changepond Technologies 2010-11. All rights reserved.AndroidManifest.xml file:AndroidManifest.xml is one of the most important file in the Androidproject structure. It contains all the information about yourapplication.When an application is launched, the first file the system seeks isthe AndroidManifest file. It actually works as a road map of yourapplication, 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 requiredThe structure of the Manifest file is:
  31. 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. 32. © Changepond Technologies 2010-11. All rights reserved.Brief into Manifest File:The package attribute defines the base package for the Java objectsreferred 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 ownunique package. Therefore it is a good habit to use your reversedomain name as package name. This will avoid collisions with otherAndroid applications.android:versionName and android:versionCode specify the version ofyour application.versionName is what the user sees and can be any String.versionCode must be an integer. The Android Market determine basedon the versionCode, if it should perform an update of the applicationsfor the existing installations. You typically start with "1" and increasethis value by one, if you roll-out a new version of your application.
  33. 33. © Changepond Technologies 2010-11. All rights reserved.The <activity> tag defines an Activity, i.e Starting Activity ClassName. An intent filter is registered for this class which defines thatthis Activity is started once the application starts (actionandroid:name="android.intent.action.MAIN" ). The categorydefinition categoryandroid:name="android.intent.category.LAUNCHER" defines thatthis application is added to the application directory on the Androiddevice.The @string/app_name value refers to resource files which contain theactual value of the application name. The usage of resource file makesit easy to provide different resources, e.g. strings, colors, icons, fordifferent devices and makes it easy to translate applications.The uses-sdk part of the AndroidManifest.xml file defines theminimal SDK version for which your application is valid. This willprevent your application being installed on unsupported devices.
  34. 34. © Changepond Technologies 2010-11. All rights reserved.For Different screen size, The following is a list of resource directoriesin an application that provides different layout designs for differentscreen 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. 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 sizeres/layout-large/my_layout.xml // layout for large screen sizeres/layout-xlarge/my_layout.xml // layout for extra large screen sizeres/layout-xlarge-land/my_layout.xml // layout for extra large in landscapeorientationres/drawable-mdpi/my_icon.png // bitmap for medium densityres/drawable-hdpi/my_icon.png // bitmap for high densityres/drawable-xhdpi/my_icon.png // bitmap for extra high densityReference Link:http://developer.android.com/training/multiscreen/screendensities.html
  36. 36. © Changepond Technologies 2010-11. All rights reserved.Handle the error gracefully and substitute an appropriate value in thecatch {} 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. 37. © Changepond Technologies 2010-11. All rights reserved.IllegalAccessException: Thrown when a program attempts to access afield or method which is not accessible from the location where thereference is made.NullPointerException: Thrown when a program tries to access a field ormethod of an object or an element of an array when there is noinstance or array to use, that is if the object or array points to null. Italso occurs in some other, less obvious circumstances, like a throw estatement where the Throwable reference is null.IllegalArgumentException: Thrown when a method is invoked with anargument which it can not reasonably deal with. This can happen if theuser 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 isrunning.ClassNotFoundException: Thrown when a class loader is unable to finda class.Solution: compare the error to your Android Manifest very closely.Few Exception in Android:
  38. 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 yourproject and click export.2. Now choose Android and then Export Android Application. Inthe next step confirm the project that you want to export.3. Then click next and now you should be able to select create newkeystore.4. Now fill in the required fields and your should be able to signyour app.5. Be sure to make a backup of the keystore file and remember yourpassword. Losing this will make it impossible to update yourapplication.Refer the Link:http://ofps.oreilly.com/titles/9781449383268/ch08_id35815995.html
  39. 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 applicationpackage.2. When you publish an update to an application, users who havealready installed the application may receive a notification that anupdate is available for the application. They can then choose to updatethe application to the latest version.3. Before uploading the updated application, be sure that you haveincremented the android:versionCode and android:versionNameattributes in the element of the manifest file. Also, the package namemust be the same as the existing version and the .apk file must besigned with the same private key.
  40. 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:24. If the package name and signing certificate do not match those ofthe existing version, Market will consider it a new application, publishit 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 toupload the 1st version of application on android market. If you havelost this keystore file then you cant 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. 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 shortcutcombinations (just in case you forget any of those listed here) .Site For Eclipse Shortcut keys:http://eclipse.dzone.com/news/effective-eclipse-shortcut-keyEffective Eclipse:
  42. 42. © Changepond Technologies 2010-11. All rights reserved.FindBugs:http://www.vogella.com/articles/Findbugs/article.htmlPMD Tool:http://about-android.blogspot.in/2010/03/android-codereview-tool-setup-pmd.htmlBest Code Review Tools for Eclipse:
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×