Saturday, May 25, 2013

Ten Tips for Android Application Development

Beginner tips

1: Learn SQL

Android has an excellent persistence system; use it to make your applications more robust in case of failure or shutdown, and to make suspending and resuming more efficient. Android's SQLite-based storage system is thoroughly integrated with Android's user interface classes.

Android supports the observer pattern in Cursor, Adapter, and View classes, enabling the user interface to connect directly to the results of database queries. Using these capabilities means less work when Android wants to stop your application because you have little or no data that needs to be to be explicitly saved, and more reliability in running on mobile devices that can be out of battery at any time.

The database classes in the Android framework manage caching and are more efficient than reading a whole data model into objects in memory. But, in oder to take maximum advantage of the Android way of designing data models, you will need to know some SQL.

2: Learn XML

You don't have to know much about XML to use the visual editing tools for defining layouts and other resources. You are, in theory, hardly ever required to edit XML "by hand." But these tools are imperfect. The more you know about how Android uses XML, and about the Android XML schema, the easier it is to fix problems that occur in XML in Android applications, and the more comfortable you will be using XML to maximum effect in developing Android applications. A general XML book, like XML in a Nutshell (O'Reilly), or Learning XML (O'Reilly) can be useful.

3: Learn Eclipse IDE

Java can be a verbose language, and without code completion, Javadoc pop-ups, and advanced refactoring, it can be a drag compared to dynamic languages. In other words, Java without Eclispe's productivity features would be no fun at all.

Eclipse, however, can have a steep learning curve for beginners. Getting comfortable with this big, powerful, and sometimes perplexing IDE is a big part of being productive in Android application development. Steve Holzner's book Eclipse (O'Reilly) is an excellent introduction and will get you up to speed.

Within the Eclipse documentation pages, you can get a good start by reading the pages covering Eclipse concepts. Get to know these concepts early on, otherwise the Eclipse menus and documentation will seem full of jargon. Then go on to thebasic tutorial in the Java development section.

4: Use automated testing

Use the Monkey to stress test your application. It generates a stream of events, simulating random inputs, and reports application crashes or lack of response. Use the Instrumentation Framework and JUnit to write unit tests that can be run from Eclipse using adb and the InstrumentationTestRunner.

Learn and use the application and service lifecycles effectively. Enable your application to be efficiently stopped and restarted by the Android system. Unlike many runtime environments with almost trivial application lifecycles, Android's runtime environment frequently stops or terminates processes to keep application resource consumption low, being prepared to restart them if the user navigates back to an application.

Android expects applications to override and respond to a set of application lifecycle methods and cooperate with the way Android manages applications as they become visible on the screen or are obscured by other applications. Get this code into your application early on in its development, so that you do not end up retro-fitting these method overrides. Use the debugger to set breakpoints in the application lifecycle methods so that you get a feel for how the Android application lifecycle works.

Advanced tips

5: Use static analyzers

Java lends itself well to meaningful compiler warnings, and to warnings and "advice" based on static analysis. Every potential bug you kill before your application leaves development brings you closer to a 4-star user rating instead of a 2-star one. Use the compiler warnings, FindBugs, and try other static analyzers, like PMD available as Eclipse plug-ins to find the tools that find the most problems and the fewest false positives.

6: Use and be used

Use Intent objects and StartActivity (and related methods) to "borrow" functionality from other applications, and write your application to respond to Intent filter matches and provide functionality to other applications. Appications can also share data through the ContentProvider system and through remote method interfaces.

7: Divide large applications

If you are writing a large application, consider dividing it into a suite of applications and services. Smaller applications load faster and use fewer resources. Making a suite of applications, content providers, and services makes your code more open to incorporation into other applications as described the "Use and be used" tip.

8: Design for low power consumption

Things that are benign on a personal computer, like polling a server every 10 minutes, can cut a handset's battery life in half or worse. Code your application to do as little as possible until the user brings it to the foreground or some external information arrives that requires action. Use the "Battery use" in the "About phone" menu in "Settings" to find the applications and other system functions using the battery.

9: Use the NDK to access library functions

The Android NDK is an optional companion to the Android SDK that enables use of native compiled code. Use the NDK to incorporate existing C and C++ libraries where they provide useful functionality. Code CPU-intensive computations, if they must be done on the handset, in C or C++. Use the NDK's tools to call that code from Java using the Java Native Interface (JNI).

10: Avoid hierarchy

Don't design your application around a central location, "home" screen, or fixed starting place. Mobile device users want instant access to functionality. They won't tolerate moving up and down menu hierarchies. Furthermore, you want to provide stand-alone activities that are easy for other applications to invoke through the Intent interface. Allow each activity to be used independently, and include a menu in it that allows access to every other activity. In short, embed your application into a seamless Android user experience.

Some tips to start programming applications for Android Platform



1: Learn Java

If you don’t know the basics of programming, now is the time to start learning Java.  There are myriad books, classes and online tutorials teaching Java.

2: Install Eclipse and the Android add-ons.

If you know the basics of programming, this is for you.  Android programming is done almost exclusively in Java using the Eclipse IDE.  Your first step is to install Eclipse, along with the ADT plugin and the Android SDK (Software Development Kit).

3: Get a basic program up and running

You can compile one of the template apps, and either run it on a real mobile phone using a wired or wireless connection from your PC to the phone, or if you don’t have access to an Android phone, there is a virtual Android phone provided with the SDK.

4: Fiddle around with the WYSIWIG tools in the Eclipse editor

Most of the widgets and thingimajigs in an Android app can be dragged and dropped into place using the Eclipse editor.  This is a lot easier than typing in the code manually, and generally works just as well.

5: Understand how the various view styles work

ListView and so on work in similar ways to one another.  Learn what the gravity does – hint:  It tells you where the objects in the view appear.

6: Use the official tutorial until you are already fairly advanced

The tutorial provided by Android’s own website is very good. You can freely use that tutorials until you are become familiar with Android. If you're a new Android app developer, you should complete each of that tutorials in order.

7: You should know the differences between different versions of Android

You might be a bit confused of terms such as “Ice Cream Sandwich”, “Gingerbread” and “Jelly Bean”.  These are terms for Android versions 4.0, 2.3 and 4.1 respectively, with 4.1 being the most recent.  If your app uses all of the features of a higher-numbered version of Android, it might not work on older versions.  If in doubt, use 2.3 – this caters for most older phones, but has most of the important features.  You can check which version your own phone has in your phone’s Settings/About Phone menu option.

Lesson 8. Android Life Cycle

Android Life Cycle


Android Activity Lifecycle Example Code Description
Here we will learn complete details about an Android Activity Lifecycle Example with details Code Description. Here we will learn details about all real time scenarios and different states of an Android Activity. Once you download the sample code example from here, then you can find line by line code description for an Android Activity. If you are new to Android Activity, then you might like to read my article Android Fundamentals and Components. Anyway lets have a quick reminder on Android Activity Lifecycle. Below image will give us a overall idea about an Activity’s complete LifeCycle, then we will implement all details in our example.




Android Activity states

onCreate()

onCreat Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by onStart().

onRestart()

onRestart Called after your activity has been stopped, prior to it being started again.
Always followed by onStart()

onStart()

Called when the activity is becoming visible to the user.
Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

onResume()

Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.

Always followed by onPause().

onPause()

onPause Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.
Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

onStop()

onStop Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.

Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

onDestroy()

The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with theisFinishing() method.

ActivityLifeCycle Example code :-


package com.learnsimply.activitylifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class ActivityLifeCycle extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(this,"onCreate", Toast.LENGTH_SHORT).show();
}

public void onStart() {
super.onStart();
Toast.makeText(this,"onStart.", Toast.LENGTH_SHORT).show();
}

public void onRestart() {
super.onRestart();
Toast.makeText(this,"onRestart.", Toast.LENGTH_SHORT).show();
}

public void onResume() {
super.onResume();
Toast.makeText(this,"onResume.", Toast.LENGTH_SHORT).show();
}

public void onPause() {
super.onPause();
Toast.makeText(this,"onPause.", Toast.LENGTH_SHORT).show();
}

public void onStop() {
super.onStop();
Toast.makeText(this,"onStop.", Toast.LENGTH_SHORT).show();
}

public void onDestroy() {
super.onStop();
Toast.makeText(this,"onDestroy.", Toast.LENGTH_SHORT).show();
}

}

Lesson 7. Android Activity

What is Android Activity ?


What is Android Activity ?

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows
  • The basis of android applications
  • A single Activity defines a single viewable screen
  • Can have multiple per application
  • Each is a separate entity
  • They have a structured life cycle
  • Different events in their life happen either via the user touching buttons or programmatically

The user interface of an application is displayed on a device through an Activity, typically with one Activity created for each unique screen. Internally there is a stack of Activities, when moving from one screen to another, the next Activity to be visible is pushed onto the top of the stack – put another way, the Activity on the top of the stack is what is visible on the display. Activities are popped from the stack by pressing the back button, which resumes the previous Activity.

Activity Class

When you want to create a new Activity, you extend the Activity class. The code below shows a simple starting point:

package com.learnsimply.basicactivity;

import android.app.Activity;
import android.os.Bundle;

Notice the reference to main in the layou
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
}


Once created you’ll need to associate a layout of the UI for the Activity. The recommended approach is to use an XML-based layout. For example, the layout below shows how you might define a simple table.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">
    <TableRow>
        <TextView
            android:text="@string/row1a"/>
        <TextView
            android:text="@string/row1b"
            android:gravity="right"/>
    </TableRow>
    <TableRow>
        <TextView
            android:text="@string/row2a"/>
        <TextView
            android:text="@string/row2b"
            android:gravity="right"/>
    </TableRow>
</TableLayout>



Let’s assume the layout about was created/saved in a file main.xml. Behind the scenes, the Eclipse plugin will update the R.java file and make a reference to the layout resources defined in main.xml. As an example:


package com.learnsimply.basicactivity;
 
public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040004;
        public static final int row1a=0x7f040000;
        public static final int row1b=0x7f040001;
        public static final int row2a=0x7f040002;
        public static final int row2b=0x7f040003;
    }
}

Notice the reference to main in the layout class. 
We can now update the BasicTable class defined above, 
which extended the Activity class, to tie the layout (table) to the Activity we defined.  we do this be calling the setContentView() method inside onCreate():
package com.learnsimply.basicactivity;
 
import android.app.Activity;
import android.os.Bundle;
 
public class BasicActivity extends Activity 
{
  WebView webView;
 
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
 
    // Associate table layout to this Activity
    setContentView(R.layout.main);
}
}
Android Manifest
For each Activity, there needs to be an entry in the AndroidManifest.xml file,where you can define a theme,label,permissions, etc.
Here is a sample manifest with one Activity:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.tabletest.table"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TableActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>
</manifest>

Lesson 6. Android Wrap_content And Match_parent

Android Wrap_content And Match_parent

Android Wrap_content And Match_parent

In Android, while designing layout you always put either "wrap_content" or "match_parenton component’s attribute on "layout_width" and "layout_height",  did any one know what’s the different?

  1. wrap_content – The component just want to display big enough to enclose its content only.
  2. fill_parent – The component want to display as big as its parent, and fill in the remaining spaces. (renamed match_parent in API Level 8)

1. wrap_content

A button component, set "wrap_content" on both width and height attribute. It tell Android to display the button big enough to enclose it’s content “Button Hello World” only.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>





2. match_parent – width

Change the "layout_width" to "match_parent", now, the button’s width will fill in the remaining spaces, just as big as it’s parent "Linearlayout", but button’s height is still big enough to enclose it’s content only.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>





3. match_parent – height

Change the "layout_height" to "match_parent", now, the button’s height will fill in the remaining spaces, just as big as it’s parent "Linearlayout", but button’s width is still big enough to enclose it’s content only.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent" >

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>




4. match_parent – width, height

Change the both "layout_widthand "layout_height" to "match_parent", the button will display as big as the whole device screen, it just fill in the entire screen space.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</LinearLayout>

Lesson 5. Execution Flow of Android Application

Execution Flow of Android Application

As a Beginner You need to know the execution flow of your android application. to understand the basic execution flow of android  we are  considering the hello world example.

When you create the android project in eclipse lots of folder are created such as "src" ,"gen" , "Android 1.5"  , "assets" and "res" folder.

To understand android flow we are starting with the "res" folder. In "res" folder there is a file called "AndroidManifest.xml".

These below is the content of AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="3" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HelloWorldDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
      
    </application>
</manifest>


In the Above Xml code we have an activity called "HelloWordDemo" listed in activity tag this activity will be launched first. if you have multiple activity in your android application you must have to register all your activity in AndroidManifest.xml file.

you can specify your child activity by just <activity android:name=".xyz"></activity> adding as many tag as many activity you have in your android application. Make sure you specify "." (dot) before each activity.


Activity name ".HelloWorldDemo" will call HelloWorldDemo.java file.

package com.example;
import android.app.Activity;
import android.os.Bundle;

public class HelloWorldDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

When HelloWorldDemo Activity is created by default onCreate method will be executed. inside onCreate Method we have an setContentView which execute the android application design file whose name is main.xml  because we have R.layout.main as an argument.


In Brief  AndroidManifest.xml file execute the Launcher Activity class and from the launcher activity onCreate method will execute the Design View file by usingsetContentView method.

Lesson 4. Directory Structure of Android Application

Directory Structure of Android Application


When you create new android project from eclipse editor you found that there are lots of directories created for android application lets us understand all these directory.

Let us start from the top directory the top most directory is src directory.

SRC Directory

The src Directory contains the java files inside package.

gen Directory

The gen directory contains folder that are generated for us by the toolset. one of the best thing you will find in gen directory is R.java file. R.java file update automatically by the system whenever you add or remove the design object or anything. in straight forward way whatever you add or remove from your project will be update in R.java file.

Android 1.5 or X.X

This folder is associate with the  SDK version  this is the thing that we have to configure when we create new project of android application.

assets

the assets folder provides repository for your resource which are using by your android application. for eg if your android application has sound effect then you can put those sound files in this folder but you can't put image files in this folder because we have another folder for images like stuff.

bin

Every program gets compiled and generate binary files same way android program also gets compiled and generate binary files. android bin folder contains the compiled binary files.

res

the res folder doesn't contain any files but it is one of the most important directory in android application. let us see what kind of directory res folder has.

res/drawable

Drawable folder contains images. there are three kind of screen density. you can specify same three images for different screen density. for eg res/drawable-hdpi contains all your image resources for high-resolution devices.   you don't need to specify which density images to pick when but operating system will choose it at run time.

res/layout 

the layout folder is where you put your main.xml fileall design resources are stored in this folder.

res/values

values folder contains string resource. mostly its in key value pair. some common file isstrings.xml

AndroidManifest.xml: 

The manifest file is responsible for providing essential information to the operating system about a   particular application. for e.g. used to specify the default activity to launch.