Archive for the ‘Mobile Application Development’ Category

24
Nov

Enterprise software is now going mobile. More and more work, which needed your presence in office/home, can be done on-the-go. With introduction of addictive UIs on smart phones, the market for Mobile based Software has grown into a new niche.

Smart phone applications can be categorized in to Native Applications and Web Applications. Native apps are downloaded on the device may or may not require internet connectivity. Most of the games and utilities like calculator, unit-converter fall in this category. Web Apps are applications that run on the device’s inbuilt browser. It does not need downloading, but requires continuous internet connectivity in most cases.

Both types of applications on Mobile can be developed by following these interdependent life cycle stages:

1. Design: A typical smart phone dimensions of 320×480 gives a very limited real estate to stuff-in the amazing functionalities they can support. Designers really need to master the art of small.

Native

The design needs to be in alignment with various UI standards and can closely follow Human Interface Guidelines(HIG) from Apple. Though they have defined it for iPhone, many of them in my opinion are pure common sense. Hence, HIG is applicable for all devices, specifically for the Native apps. The smart-phone vendors (RIM, Apple etc.) have gone a long way in providing standard and useful applications to their users via their own app-stores.

Web Based

In web based application development, for multiple devices for e.g. for iPhone and Blackberry Bold, design issues need to be taken care at the CSS level. For lower versions of Blackberry though UI has to be generated by a different code set.

2. Server side: APIs not only cater to web based mobile applications, native applications too need to shift the data intensive computation to server side. So there is not much difference between the server side programming for Web and Native apps. Bringing website functionality to mobile is not mere reuse of APIs. It involves optimization of existing APIs for performance. It may also involve revisiting the code for adding device specific checks, abstraction and exception handling etc.

3. Client side: iPhone, Blackberry, Android, Windows Mobile, Symbian have their own SDKs for development of Native Apps. While iPhone requires experience on Objective C and Mac OS, Blackberry and Android can be handled by Java developers while Windows mobile application can be created using Visual Studio 2008.

Native

Advanced hardware like inbuilt camera, accelerometers etc can also be harnessed for making the mobile application feature-rich – like Auto-orientation, motion based gaming etc. The inbuilt GPS and assisted GPS can be leveraged for creating location based services. Though a plethora of applications are already providing LBS, I find it to be a tip of the iceberg. Adding LBS can make a lot of applications information rich, for end users as well as for vendors, distributors and advertisers.

Web Based

Web based applications on almost all devices, sparing iPhone in some cases; do not need specified SDKs for development. The major issue for web based apps is handling the large number of device-browser combinations that a user may use. What works for IE on BB may not work for FF on the same device. To resolve the issue of developing and maintaining code for different devices XHTML-MP is gaining wide popularity among developers.

4. Testing: Other than functionality and UI related testing, Mobile app QA requires testing for performance and connectivity related issues.

Native

Mobile software requires to be tested in real (non-simulated) Wi-Fi, GPRS, 3G etc. with different service providers. Something that works on AT&T may be blocked by T-Mobile. Also, an internet savvy application may behave differently in different geographies. Based on expected usage, the application should be tested for all the geographies. One may take assistance from www.deviceanywhere.com.

Web Based

Web apps always need to be tested on variety of browsers (Mobile browsers) for rendering issues. iPhone supports Safari, while BB supports IE and Firefox and also has it’s own browser. Rigorous manual testing can reveal functionality glitches and alignment issues. Generally for all types of browsers, testing and debugging using Firebug and HTTP watch can be quite helpful.

One should plan the development of mobile applications with these distinct yet interdependent processes in mind. It should really help in developing a standard application in minimum time.

-Ujjwal Trivedi

, , , , ,

11
Dec

The speed with which mobile technology is evolving is beyond remarkable. So much, that you may in fact, be viewing this post on your mobile. Gone are the days when you would have a mobile phone solely for the purpose of connecting with your friends & family. Now, you can connect with 300 million+ users on Facebook, listen to the latest music from Last.fm, view videos on YouTube etc. all using your ‘handheld’ device. The list of can-do’s is endless. What goes on behind the scenes is the collaboration of developer minds, striving to stretch technology, constantly redefining benchmarks to create services & applications that make life a whole lot easier.

While the success of social networking is undeniable, lifestyle & Location Based Services (LBS) have helped users to simplify their needs & achieve them; locally & globally. However, the process of satisfying user needs in a constantly changing environment requires a thoughtful understanding & analysis of the changing trends which has been successfully catered to. There is no doubt that there exists a challenge of providing quality applications to a variable audience with innumerable preferences. We have accepted this challenge, acknowledged the pros & cons & delved into bringing out the best solutions.

The iPhone is known to deliver ‘eye candy’ experience with its UI, having the user to touch & pinch to use applications. Having said that, many applications fail to utilize the potential of the iPhone, unable to handle development challenges. Given below is a little insight into some of these challenges.

Developer’s Eye View:

  • The iPhone runs only one foreground application at a time, so launching any other application requires terminating the currently running app.
  • Responding to interruptions like incoming calls, messages etc. is important because if the user decides to take a call or reply to an SMS message, the system proceeds to terminate the application.
  • Low-memory warnings are critical. If not enough memory is released – perhaps because the application is leaking or still consuming too much memory – the system may terminate the application.
  • Being a touch driven device, the controls of the application need to be placed with some thought.
  • The iPhone screen is precious as it is the component with which users interact. An application with a crowded screen may deviate the user’s attention much like in a real life market place.
  • An applications UI view differs when the iPhone is held in portrait or landscape mode. Tap’s drags, and swipes are simple gestures, typically involving only a single touch. Handling a touch event consisting of two or more touches is a more complicated affair. In addition, the iPhone generates motion events when users move the device in a certain way, such as shaking it. It is necessary to prevent the application from responding in an unexpected (and unwanted) manner in response to such events

Now let’s take a look at how one can avoid getting into the possible sticky situations given above:

  • It is imperative that an application should terminate as usual, saving any needed contextual information to return the user to the same place (if required) in the application upon next launch (or re-launch).
  • Adhering to Apple’s Human Interface Guidelines saves a lot of confusion & gives well designed interfaces.
  • Handling events, implementing event cancellation etc. correctly, prevents the app from being left in an inconsistent state.

These & many more underlying intricacies can very well determine the chances of an app being realized. Adapting to this one button device, we have delivered attractive, feature rich applications that meet App Store standards & have satisfied users looking to be part of changing lifestyle trends.

-Anup D’souza

, , , ,

15
Jun

In this blog post, we shall take a look at how to get started with programming for the BlackBerry device. We shall cover what the device is, give you an overview of BlackBerry development and then provide you with detailed steps to setup your development environment. Future blog posts will focus on programming on the BlackBerry.

What is a BlackBerry Device?

The BlackBerry is a wireless handheld device developed by the Canadian company known as Research In Motion (RIM) and was launched in year 1999. It holds 20.8% market share in worldwide Smartphone sales, making it the second most popular platform after Nokia. It is known as the most popular Smartphone around the world for its connectivity and security.

Its primary goal is to support push e-mail, web browsing, text messaging and other wireless internet services in a secure manner. Now a days the BlackBerry devices are integrated with advanced software’s which enable access to wide range of data, communications services, Email, phone, maps, GPS, organizer, social networking, games and other applications. These features of a Smartphone make life easy by allowing access to everything on the move at any place in the world on your fingertips.

The BlackBerry software development kit is a wide collection of examples, documentation, and mature set of APIs and tools grown in an extensive manner, which have shown the directions to develop all kinds of great applications. BlackBerry community and its App World help to get your application noticed and downloaded by users worldwide.

The list of BlackBerry device and its models:

BlackBerry Development Platform consists of:

BlackBerry Development Environment is completely based on the Java Platform. It is collectively integrated with BlackBerry RIM APIs, J2ME APIs and basic Java SE APIs. It is built on top of Java Micro Edition (Java ME) which itself is derived from Java SE.  In order to get into the BlackBerry Application development one need to know Object Oriented programming with the basic understanding of J2ME concepts of configurations and profiles, and in particular the CLDC and MIDP standards.

The BlackBerry Development Environment tools:

The BlackBerry application can be developed on any platform, even in Linux, OSX, the easiest and best supported is Windows 32bit platform. RIM provides two BlackBerry development environments such as:

  • BlackBerry Java Development Environments (JDEs) and
  • BlackBerry Eclipse Plug-in.

Both Blackberry development environment tools work with standard Java Software Development Kit (Java SDK) and fully integrated with development tools, simulators and provides to necessary to create, package, compile, test and debug the Blackberry application. You don’t even need the real handheld device to test the application, because it also includes the full featured Blackberry device simulator. A complete set of BlackBerry JDE API Doc is available for referring available packages and classes for development. Both the development tools are being used by many professional developers to develop BlackBerry applications. We will look into both the tools in detail. The best thing about BlackBerry development tools is that they are absolutely free.

Now we will see the step by step installations for both BlackBerry Java Development Environments (JDEs) and BlackBerry Eclipse Plug-in.

Let’s Start with Installation process:

BlackBerry Java Development Environments (JDEs)

Installing the BlackBerry JDE is very easy as compared to any other tools:

  1. Before installing the Blackberry development tools, you will need to install Java SE Development Kit (JDK) version 5 or later from http://java.sun.com. Which version has to be downloaded will depend on the version of Blackberry platform you want to target. The Java SE JDK v6.0 helps you to develop for BlackBerry Device Software version 4.2 or later. More specific information is available on the BlackBerry Developer page at http://na.blackberry.com/eng/developers/javaappdev/javadevenv.jsp
  2. Now you download appropriate version of BlackBerry Java Development Environment (JDE) from BlackBerry Developer Zone at http://www.blackberry.com/developers/ , you have to register an account. Free Developer tools, whitepapers, the developer Knowledge base and the Blackberry Developer forums are found here. (BlackBerry JDE versions: The BlackBerry OS is backward compatible, So something developed on OS 4.2 will work on OS 4.3 and later without requiring code changes done. It may be the case where certain features are only supported on higher versions. But most of the basic features are covered from OS 4.2)
  3. Once the BlackBerry JDE installer is downloaded, run the installer and follow the on-screen instructions. It will be installed to the default path C:\Program Files\Research In Motion\BlackBerry JDE 4.5.0, which can be changed during installation.
  4. Launch the BlackBerry JDE from Start>Program Files>Research In Motion> BlackBerry JDE 4.5>JDE.
  5. Once the BlackBerry JDE is launched it will look as shown in Figure 1.0. The left hand pane shows sample.jdw workspace, the right hand side shows the HelloWorldDemo.java file in editor. The sample.jdw workspace contains the Blackberry sample examples and it is located in the BlackBerry JDE folder at C:\Program Files\Research In Motion\BlackBerry JDE 4.5.0\samples. The BlackBerry API reference doc can be found in via Help>API Reference in the JDE.

BlackBerry JDE v4.2.1 with workspace in left hand side pane, source code editor in right hand side and console at the bottom

The BlackBerry JDE v4.2.1 with workspace in left hand side pane, source code editor in right hand side and console at the bottom.

BlackBerry Eclipse Plug-in installation:

You can download the Eclipse IDE at http://www.eclipse.org/downloads/ . Don’t forget to install the Java Development Kit as a pre-requisite as explained in step 1 of the BlackBerry JDE installation. And download the plug-in from BlackBerry tools at http://na.blackberry.com/eng/developers/resources/devtools.jsp

Perform the following steps to install the BlackBerry Eclipse Plug-in with Eclipse IDE of Java Development version 3.4.0.

  1. Start Eclipse
  2. From the main menu, Select Help > Software Updates.
  3. In the Software Updates and Add-ons dialog, click the Available Software tab.
  4. Click the Add Site button.
  5. In the Add Site dialog, click the Archive button.
  6. In the Repository archive dialog, select the .zip file to install.
  7. Click Open.
  8. In the Add Site dialog, click OK.
  9. Select the check box for the BlackBerry JDE Plug-in for Eclipse. All subcomponents should be checked automatically.
  10. Click Install.
  11. Click Finish.
    When the installation completes, the Software Updates dialog is displayed.
  12. Click Yes to restart Eclipse.

I hope this post is helpful in understanding the BlackBerry Environment, tools and its installation process. If you have any queries feel free to comment.

Siddhesh Bingi
Siddhesh Bingi– Member of Mobile Center of Excellence

, , , ,

29
Jun

Providing a good user experience is critical to mobile applications. UI Application development in Android requires that you have a good understanding of Layouts. In this blog post, we shall cover all about Android Layouts with code samples.

Android Layout is like a container; all the screen will use either of the one layout and all the view (components) on that screen are part of the layout. The fact that mobile screen is small in size it is very important to properly design the UI.

Let us look at the various layouts offered:

  • Linear Layout

This layout as name says is used to place the views in the linear flow one after the other. We can specify the manner in which view are placed linearly i.e. horizontally or vertically.

Let us have a look at the Linear Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
    	>
 <TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
    	 android:text="First Text View"
    	 />

 <TextView
    	 android:layout_width="fill_parent"
    	 android:layout_height="wrap_content"
    	 android:text="Second Text View"
    	 />
 </LinearLayout>

As shown the above Linear Layout have two Text Views and have orientation set to vertical (android:orientation=“vertical”), hence the two Text Views will be drawn vertically one below the other.

Linear Layout Vertical Orientation

Figure 1: Linear Layout Vertical Orientation

Look at the above XML for Linear Layout, width for layout along with Text View with the layout is set to fill_parent (android:layout_width=“fill_parent”). And since Linear Layout is the top most layout and width set to fill parent it will be stretched to cover entire screen. Similarly both the Text Views also have width set to fill parent, and since they are child to Linear Layout they are stretched to entire screen width.

Now let us change the orientation of linear layout to horizontal (android:orientation=“horizontal”).  Just changing the orientation to horizontal will draw Text View next to each other, but since each of the text view is set to have width as fill parent and by default both are written from left to right (Gravity) only one Text View (First Text View) will be visible. To overcome this set width for both the Text View to wrap_content (android:layout_width=“wrap_content”).

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
    	android:layout_width="fill_parent"
    	android:layout_height="fill_parent"
    	>
<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    		android:text="First Text View"
      />

    		<TextView
    		android:layout_width="wrap_content"
    		android:layout_height="wrap_content"
    	android:text="Second Text View"
    		android:paddingLeft="10px"
    		/>
  </LinearLayout>

Note: Since we have set width for both the Text View as wrap_content, 2nd Text View will start as soon as 1st end. Hence in the above xml we have provided left padding for 2nd Text View in order to have some space between the 2 Text View.

Linear Layout Horizontal Orientation

Figure 2 Linear Layout Horizontal Orientation

  • Table Layout

Using this layout we can place view/components in tabular format.  The best example to understand this layout is Login Screen. Below XML shows Table layout

<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

		<TableRow android:id="@+id/TableRow01">
			<TextView android:id="@+id/TextView01"
			android:text="User Name:"
			android:width="100px"/>

			<EditText android:id="@+id/EditText01"
			android:width="220px"/>
		</TableRow>

		<TableRow android:id="@+id/TableRow02">
			<TextView android:id="@+id/TextView02"
			android:text="Password:"
			/>

			<EditText android:id="@+id/EditText02"
			android:inputType="textPassword"/>
		</TableRow>

		<TableRow android:id="@+id/TableRow03">
			<Button android:id="@+id/Button01"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:text="Login"/>

			<Button android:id="@+id/Button02"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:text="Reset"
			android:width="100px"/>
</TableRow>
</TableLayout>

As shown Table consist of three rows (Table Row) and each row as two views/components. Number of columns in table is determined by the maximum number of components in a single row.

Table Layout

Figure 3 : Table Layout

One more important point to note here is that even after specifying width of Reset button in xml to 100 pixel  (android:width=“100px”), it’s width is same as that of Edit Text. This is because width of Column is determined by the maximum width of the component in that column and here Reset button is same the column as Edit Text which has width set to 220 pixel.

  • Relative Layout

This layout is flexible layout of all. This layout as name suggest allow placing components relative to other component or layout. Let us see at the example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name:"
android:width="100px"/>
<EditText android:id="@+id/EditText01"
android:layout_width="220px"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/TextView01"
android:layout_below="@+id/RelativeLayout01"
/>

<EditText android:id="@+id/EditText02"
android:layout_width="220px"
android:layout_height="wrap_content"
android:layout_below="@+id/EditText01"
android:layout_alignLeft="@+id/EditText01"
/>

<TextView android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:width="100px"
android:layout_below="@+id/EditText01"
android:layout_toLeftOf="@+id/EditText02"
/>

<Button android:text="Login"
android:id="@+id/Button01"
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_below="@id/EditText02"
android:layout_alignLeft="@id/EditText02"
/>

<Button android:text="Reset"
android:id="@+id/Button02"
android:layout_width="100px"
android:layout_height="wrap_content"
android:layout_below="@id/EditText02"
android:layout_alignRight="@id/EditText02"
/>

</RelativeLayout>

As shown,  EditText 01 has attributes android:layout_toRightOf=“@+id/TextView01″ and android:layout_below=“@+id/RelativeLayout01” for placing Edit Text next to Text View (User Name) . Similarly check EditText02 as attributes android:layout_below=“@+id/EditText01″ and android:layout_alignLeft=“@+id/EditText01″ for placing Edit Text box below the Edit Text 01.

Relative Layout

Figure 4 Relative Layout

  • Absolute Layout

As name suggest this layout is used to place views/components at the exact location on the screen using x and y. Let us see example

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="@+id/EditText01"
android:layout_width="200px" android:layout_height="wrap_content"
android:layout_x="12px"
android:layout_y="12px"/>
<Button android:text="Search"
android:id="@+id/Button01"
android:layout_width="100px" android:layout_height="wrap_content"
android:layout_x="220px"
android:layout_y="12px"/>
</AbsoluteLayout>

Absolute Layout

Figure 5 Absolute Layout

As seen we have specified android:layout_x and android:layout_y for both the components  their by providing the absolute location for the components.

  • Frame Layout

Frame Layout is one of the simplest layouts. It is like a single screen and all the views/components child to this layout will be drawn on same screen anchored to the top left corner of the screen. So it is likely that one view can overall another one and hides it unless it is transparent. Let see the example

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/FrameLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<ImageView android:id="@+id/ImageView01"
android:src="@drawable/taj_mahal"
android:scaleType="center"
android:layout_width="fill_parent" android:layout_height="fill_parent"/>

<TextView android:text="Taj Mahal"
android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="10dip"
android:textColor="#FFFFFF"
android:background="#AA0000"
/>
</FrameLayout>

Frame Layout

Figure 6 Frame Layout

Note: taj_mahal.jpg is in drawable folder

Conclusion

We looked at the basic android layouts and tried to understand them with their respective examples.


Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

, , ,

06
Jul

This blog post covers how one can maintain state in an iPhone application. Everyday interactions with the environment require us to save some form of information or data either for immediate use or maybe later.

Take for example:

  • Saving phone numbers on your mobile.
  • Backing up electronic data on a portable hard drive.
  • Performing the “Save Game” routine while playing a critical mission of your favorite console game.
  • Saving drafts of emails.
  • Saving code during development! (I too am saving this document to spare the agony of re-typing by an accidental application Quit.)

All these actions of saving, give the ability to record all information that is gathered.

Likewise, saving the state of an application is an essential, although not commonly used practice in iPhone Application Development.

In this post I intend to throw some light on aspects of  ‘state saving’.

Need for saving the state:

Consider the following situations -

  • A user can quit the application at any point in time.
  • The application is quit by the iPhone OS on an external event such as a phone call.
  • The application quits on an internal event such as the launch of the native Web Directions app/ Google Maps app.

For an application with a large number of screens (by screens I mean ‘views’), navigating through many screens to view desired information and then having the application quit accidentally or unexpectedly can get annoying. Especially if the applications flow (sequence in which views load on user interaction) requires executing search queries, entering criteria or just navigating a dozen screens!

In such cases saving the state along with the required user data helps to restore the same view that the user was on before the application quit, upon application re-launch.

What data to save?:

In order to save the state, it is absolutely crucial to save all the necessary data to bring back the correct screen on application re-launch.

This section I suppose is self explanatory, hence i’ll resort to just listing the data one may need to save.

  • User information( username, password )
  • User preferences( settings within the application )
  • Application flow data( user-saved criteria, searches executed )

When to save data?:

The answer to this question could vary depending on the context of an application. Data could be saved at regular intervals during application flow or on specific screens or just before the application quits. In iPhone projects there exists a method that is called just before the application quits.


- (void)applicationWillTerminate:(UIApplication *)application{

}

Any logic, if you choose to save data just before the application quits should go in there.

Keep in mind the priority of data to be saved, you would not want to add more overhead than already exists.

How to save the data?:

Lets get started.

1. NSUserDefaults:

The NSUserDefaults object is simply a great way to save data. The best part being that no pre-requisite database knowledge is required to use it.

Saving Data -

Using the setObject & like methods, one can save different type of data as shown below.

forKey represents the key to associate with the value.


NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];

// to save a Float

[savedData setFloat:3.14159 forKey:@"valueOfPi"];

// to save an NSInteger

[savedData setInteger:18 forKey:@"userAge"];

// to save an NSString

[savedData setObject:@"JackSparrow" forKey:@"username"];

[savedData synchronize];

The synchronize method syncs the in-memory cache with the defaults database.

You could also setBool, setDouble, setUrl.

Retrieving Data -

Retrieving the saved data is even simpler & self-explanatory!


NSUserDefaults *savedData = [NSUserDefaults standardUserDefaults];

// getting an Float

float dearPi = [savedData floatForKey:@"valueOfPi"];

// getting an NSInteger

NSInteger theAge = [savedData integerForKey:@"userAge"];

// getting an NSString

NSString *theUsername = [savedData stringForKey:@"username"];

2. .plist file:

The .plist (Property List) is a file containing a list of nested {key-value} pairs of data types such as strings, numbers, arrays & dictionaries. Plists are simple & effective, much like NSUserDefaults.

The Setup -

i.    Create a plist file in your application’s Xcode project, say savedData.plist.
ii.    Create a list of paths, we will use one of the paths to save the plist.

NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

iii.    From this list of paths, get a path to the documents directory.

NSString *documentsDir = [pathList objectAtIndex:0];

iv.    Now get a file path to the plist


NSString *plistPath = [documentsDirectory  stringByAppendingPathComponent:@"savedData.plist"];

Writing data to the plist -

[<SOME DATA> writeToFile:plistPath atomically:YES];

Reading data from the plist -

NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:plistPath];

In addition to the above methods you could also experiment with using SQLite or CoreData.

How to save data using them requires a separate post and as such, is out of the scope of this article.

What Next?:

Now that we are done with saving all that we need, a little bit of common sense & planning will go a long way in restoring the application to its previous state on re-launch. Depending upon the heaviness of the screen the user needs to see on re-launch, one may execute any number of methods within the application code to perform the necessary processing. However, let the user know that the application hasn’t hung up and is just processing things before the last viewed screen is shown, using waiting/activity indicators and alerts with appropriate messages. Preferably, build a view that continues to show as long as the required view doesn’t show up. If for some reason, restoring state is not possible, don’t let the application stare blank at the user. Instead, load an appropriate view from where the user can continue. If all fails, take the user to the first view of the application with the indication that probably the data required to load the appropriate view is insufficient or the application was unable to restore the state.

A few pointers to consider:

  1. Do not try saving excessive amounts of data, it results in latency while the application is running.
  2. Whatever you save, make sure its complete.
  3. When you are retrieving what you have saved, make sure the data exists. Null or no values spell doom.
  4. Let the user know the application hasn’t given up on him/her. Indicate processing where required.
  5. Free what is not required. Memory is vital, use it wisely.

I hope this post benefits all those looking to understand the need of saving an application state.

Anup Dsouza
Anup Dsouza– Member of Mobile Center of Excellence

07
Jul

A BlackBerry phone is primarily a business phone with additional features like Email, Phone, Maps, GPS, Organizer, Social Networking and games. Developers can take advantage of various BlackBerry APIs to take the user experience to a new level. In this article, I am going to talk about BlackBerry and Location API,that allows you to develop Location based (LB) applications.

Compatibility

BlackBerry is packed with advanced features, but they are not supported in all models. Let us quickly have a glance at some of the models.

In general there are two options for using GPS with a BlackBerry. You either have a device with an internal GPS receiver, or you will need an external Bluetooth GPS receiver, which will provide the GPS data to your BlackBerry. Refer to this link to find out the models which support GPS http://na.blackberry.com/eng/devices/features/gps.jsp

Do not be disappointed if your preferred model is not the list, you can always download the simulator from https://www.blackberry.com/Downloads/entry.do

Though, the above list mentions about GPS support by default, it should also be noted that there will be existing applications developed based on JSR 179 java ME api even if the model doesn’t not have inbuilt GPS support. GPS capabilities could also be obtained by connecting to an external GPS device over Bluetooth, but this comes with its own set of challenges. Another option is for old blackberry models (RIM 857/957), which works with a serial GPS receiver attached via cable.

Overview

You must enable GPS on your device, for applications to retrieve the current location. The location is nothing but coordinates for latitude, longitude and altitude.

Additionally, support for JSR 179 Location API for Java ME comes with device software 4.0.2 and later. If you want BlackBerry extensions to JSR 179, you will need device software 5.0.0 and later.

To obtain a location via the GPS support in your device, your application has to do the following:

○   Specify the GPS mode

○   Get the location provider

○   Make GPS request

○   Retrieve the GPS location of a BlackBerry device

Code sample: Specifying the GPS mode

/* JSR 179 */
Criteria myCriteria = new Criteria();
/* JSR 179 extension */
BlackBerryCriteria myBlackBerryCriteria = new BlackBerryCriteria(…);

Dig Deep

There are three GPS modes and they have speficic properties that are described below. You will need to select one based on your application requirements.

○   Autonomous – relies on the GPS satellite only. This mode uses the GPS receiver on the BlackBerry device to retrieve location information. This mode cannot be used indoors or in close proximity to many physical obstructions, and it can take several minutes to fully synchronize with four or more satellites for the first GPS fix. An example application that can use this mode is a Car Parking Spot application.

○   Assisted Mode – GPS satellite and servers on the wireless network only. This mode uses the wireless network to retrieve satellite information. This mode can achieve a fast retrieval of the first GPS fix. An example application that can use this mode is a Nearby Restaurants application.

○    Cell site Mode – Geolocation service or the wireless network to provide on the location information of current base station. This mode uses the wireless network to achieve the first GPS fix, and is generally considered the fastest mode. This mode does not provide BlackBerry device tracking information such as the speed and the bearing. An example application that can use this mode is a Weather Application.

Let us look at the code samples to use the BlackBerry API to get location and satellite information. The code fragments are used to highlight the API rather than give a fully working GPS Application that also provides additional value added information.

First, let us look at a Java class GPSSatteliteInfo listed below. This is a utility class in which we will wrap all the GPS related sample code. The thread implementation is currently empty.

/* packages to import */
import java.util.*;
import java.lang.*;
import net.rim.device.api.gps.*;
/* create public class */
public class GPSSatelliteInfo {
	/* member variables */
	…
	public GPSSatelliteInfo() {
		gpsThread = new GPSThread(); //private thread class reference
		gpsThread.start();
	}
	/* private thread class */
	private static class GPSThread extends Thread
	{
		public void run()
		{
			//do something
		}
	}
}

○   Next, specify the GPSMode inside the run() method of Thread class

BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);
//OR  to be on safer side
BlackBerryCriteria myCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST))
	myCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS))
	myCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);

○   Next, get the LocationProvider and create a BlackBerryLocation object to retrieve the GPS fix including a 300 second timeout expiry.

BlackBerryLocationProvider myProvider;
myProvider  = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria);
BlackBerryLocation myLocation;
myLocation = (BlackBerryLocation) myProvider.getLocation(300);

○   Retrieve the satellite information

satCount  = myLocation.getSatelliteCount();
signalQuality  = myLocation.getAverageSatelliteSignalQuality();
dataSource  = myLocation.getDataSource();
gpsMode  = myLocation.getGPSMode();
SatelliteInfo si;
StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n");
String separator = ":";
for( Enumeration infoEnum  = myLocation.getSatelliteInfo(); infoEnum != null; infoEnum.hasMoreElements();){
	si = (SatelliteInfo)e.nextElement();
	sb.append(si.getId() + separator);
	sb.append(si.getSignalQuality() + separator);
	sb.append(si.getElevation() + separator);
	sb.append(si.getAzimuth());
	sb.append('\n');
}

Note:The assisted mode can be used with BlackBerry devices that are associated with a CDMA network that utilizes PDE server technology. The assisted mode is designed to provide fast retrieval of a GPS fix. Assisted GPS capabilities are currently defined by wireless service providers. In many instances, you must enter into a formal relationship with wireless service providers before you can connect to their PDE server.

if ( !GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST) || !GPSSettings.isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST))
	return;

On similar lines, let us see how to retrieve location information.

static double lat, lon;
static float alt, spd, crs;
lat = myLocation.getQualifiedCoordinates().getLatitude();
lon = myLocation.getQualifiedCoordinates().getLongitude();
alt = myLocation.getQualifiedCoordinates().getAltitude();
spd = myLocation.getSpeed();
crs = myLocation.getCourse();

This covers how to retrieve satellite information and location coordinates.

However, there is a lot more that an application should do to provide a good user experience. Majority of times it is driven by the kind of application being developed. For example, if the application is designed to display my location on a map at a given time, then retrieving GPS location one time should suffice. But, at the same time, if the application is designed to keep retrieving the GPS coordinates as person moves some distance, then something more needs to be done. One way is to use the  setLocationListener() by passing the interval value, timeout value, and maximum age as parameters to add a LocationListener.)

myProvider.setLocationListener(new handleGPSListener(), 10, -1, -1);

In the class, implement the LocationListener interface. Implement the basic framework for the locationUpdated () method, and the providerStateChanged() method.

public static class handleGPSListener implements LocationListener
{
	public void locationUpdated(LocationProvider provider, Location location)
	{
		if (location.isValid())
		{...}
		else
		{... }
	}
	public void providerStateChanged(LocationProvider provider,	int newState)
	{
		if (newState == LocationProvider.AVAILABLE)
		{...}
		else if (newState == LocationProvider.OUT_OF_SERVICE)
		{...}
		else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE )
		{...}
	}
}

This gets invoked at a fixed interval to any location changes. This is ideal for application that is plotting user movement over a map. (Similar to the GPS navigation device to get directions).

We have now covered how to use the BlackBerry JSR 179 extension (aka GPS API) to get satellite and location coordinates. The code covered so far provides a basic working example to retrieve the satellite and location information. The same could be extended to  make complex applications. There are other areas which are “good to know” like GPS error code, Location error codes, control the power consumption, preferred response time, manage cost allowed, setting the failover mode (fall back on other available options if one is not available), etc and the reader is advised to refer to the available documentation.

Location Based Services and applications are growing in importance. The BlackBerry platform provides good support for you to get started with building location based applications today. In future posts, we shall delve into deeper topics that help you to take advantage of the full range of BlackBerry location based APIs.

Pawan Sachdeva
Pawan Sachdeva– Technical Architect

, ,

15
Jul

This blog post introduces one of the important mechanism of Async Task for Android with sample code.

Android implements single thread model and whenever an Android application is launched, a thread is created. Now assume you have long running operations like a network call on a button click in your application. On button click a request would be made to the server and response will be awaited. Now due to the single thread model of Android, till the time response is awaited your UI screen hangs or in other words, it is non-responsive.

We can overcome this by creating a new Thread and implement the run method to perform the time consuming operation, so that the UI remains responsive.

As shown below a new Thread is created in onClick method

public void onClick(View v) {
    Thread t = new Thread(){
    public void run(){
	// Long running operation
	  }
   };
   t.start();
}

But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.

There are various approaches via which control can be given back to UI thread (Main thread running the application). Handler approach is one among the various approaches.

Handler

Let us look at the code snippet below to understand Handler approach.

public void onClick(View v) {
   Thread t = new Thread(){
	public void run(){
   	   // Long time comsuming operation
	 	Message myMessage=new Message();
		Bundle resBundle = new Bundle();
		resBundle.putString("status", "SUCCESS");
		myMessage.obj=resBundle;
		handler.sendMessage(myMessage);
	}
  };
  t.start();
}

As seen we have modified the original run method and added code to create Message object, which is then passed as parameter to sendMessage method of Handler. Now let us look at the Handler. Note that the code below is present in the main activity code.

private Handler handler = new Handler() {
@Override
	public void handleMessage(Message msg) {
		// Code to process the response and update UI.
	}
};

After the execution of long running operation, the result is set in Message and passed to sendMessage of handler. Handle will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI.

Handler approach works fine, but with increasing number of long operations, Thread needs to be created,  run method needs to be implemented and Handler needs to be created. This can be a bit cumbersome. The Android framework has identified this pattern and has nicely enveloped it into what is called an Android Async Task. Let us look at how it can help simplify things.

Async Task

Android Async Task takes cares of thread management and is the recommended mechanism for performing long running operations.

Let us look at a sample class LongOperation, which extends the AsyncTask below:

private class LongOperation extends AsyncTask<String, Void, String> {

	@Override
	protected String doInBackground(String... params) {
		// perform long running operation operation
		return null;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		// execution of result of Long time consuming operation
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
	// Things to be done before execution of long running operation. For example showing ProgessDialog
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	 */
	@Override
	protected void onProgressUpdate(Void... values) {
      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
	 }
}

Modify the onClick method as shown below:

public void onClick(View v) {
new LongOperation().execute("");
}

As seen class LongOperation extends AsyncTask and implements 4 methods:

  1. doInBackground: Code performing long running operation goes in this method.  When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
  2. onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  3. onPreExecute: This method is called before doInBackground method is called.
  4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.

Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.

Points to remember:

  1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
  2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
  3. Task can be executed only once.

Hope this blog helped you understand Android async task and why it is important in Android application development.

Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.

20
Jul

The concept of retrieving location information using GPS device and Location API is already discussed in one of the earlier post (http://www.xoriant.com/blog/mobile-application-development/location-based-programming.html ). In this article we are going to learn to use of Blackberry’s Location API and work with geocoding and reverse geocoding. Though, Geocoding and reverse Geocoding information could be used in multiple applications, a majority of applications will need to integrate the location information and display that on a Map.

To start with, let me introduce some terms:

Geocoding: is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). With geographic coordinates, the features can be mapped and entered into Geographic Information Systems, or the coordinates can be embedded into media such as digital photographs via geotagging.

Reverse Geocoding: is the process of back (reverse) coding of a point location (latitude, longitude) to a readable address or place name. This permits the identification of nearby street addresses, places, and/or real subdivisions such as neighborhoods, county, state, or country. Combined with geocoding and routing services, reverse geocoding is a critical component of mobile location-based services to convert a coordinate obtained by GPS to a readable street address which is easier to understand by the end user.

Before we see the code part, let us look at the BlackBerry API (Locator) that facilitates the application to gain access to geospatial coordinates for an address and vice-versa i.e.  retrieve a street address for given coordinates in case of reverse geocoding.

Locator is a Geocoding service in BlackBerry that allows you to obtain location address for an address. This service has static method “geocode”, “reverseGeocode” and as it should be obvious by now, geocode require address and returns coordinates, reverseGeocode require coordinates and returns the address information.

There are few things to keep in mind while Locator is used in the application

  1. LBS Map API is a pre-requisite for Locator API to work. Application may throw exception if the LS MAP API is not installed.
  2. Call to geocode is synchronous in nature. And at any given time there should be one call made using the Locator class. Application may throw exception if more than one call is made.
  3. Call to geocode and reverseGeocode should be made outside the event dispatch thread. Requests to these methods that are made on the event dispatch thread are denied and result in an exception.

Let us look how to use the Locator API to retrieve geospatial coordinates for an address using geocode.

  • Packages required
import net.rim.device.api.lbs.*;
import javax.microedition.location.*;
  • Create a class and constructor
public class myGeocode
{
public myGeocode()
{

}
}
  • Create a private Thread variable
private Thread geocoder;
  • In constructor, create instance of the Thread class. As mentioned earlier, geocode cannot be performed on the application’s primary thread.
geocoder = new Thread(thread);
geocoder.setPriority(Thread.MIN_PRIORITY);
geocoder.start();
  • In the class, create a Thread that invokdes a public run() method.
Runnable thread = new Runnable() {

public void run() {

AddressInfo addrInfo = new AddressInfo();

addrInfo.setField(AddressInfo.STREET, "Whitewood Dr");

addrInfo.setField(AddressInfo.CITY, "San Jose");

addrInfo.setField(AddressInfo.STATE, "California");

addrInfo.setField(AddressInfo.POSTAL_CODE, "95110");

addrInfo.setField(AddressInfo.COUNTRY, "US");

Coordinates startCoords = new Coordinates(37.386087,-121.889244, Float.NaN);

try {

Landmark[] results = Locator.geocode(addrInfo, startCoords);

}

catch ( LocatorException lex ) {

//thrown when The BlackBerry device is not sufficiently connected to send or receive over any transport.

}

catch (MapServiceException mex) {

// if the LBS Map API is not installed on a BlackBerry device or if an application makes more than one request at a time.

}

catch (IllegalThreadStateException itex) {

// if a request is made on the event dispatch thread

}

catch(IllegalStateException isex) {

// if there is no valid radio/wi-fi connection to send the request to

}

}

};
  • The new two classes used above AddressInfo and Landmark, they allow application to pass formatted address object. However, overloaded geocode also accept “String” (e.g. Whitewood Dr, San Jose, Santa Clara, California 95110). This should also work and return the array of Landmark, the first array element contains the most relevant Landmark to the locator request. May be null if geocode request is cancelled or the request fails.
  • startCoords are for hint to the geocode for starting the search specified in the request. This could also be null.
  • Using the same class structure, let us see how to get the address info using coordinates.
Runnable thread = new Runnable() {

public void run() {

AddressInfo addrInfo = null;

int latitude = (int)(45.423488 * 100000);

int longitude = (int)(-80.32480 * 100000);

try {

Landmark[] results = Locator.reverseGeocode

(latitude, longitude, Locator.ADDRESS );

if ( results != null && results.length &gt; 0 )

addrInfo = results[0].getAddressInfo();

} catch ( LocatorException lex ) {

//do something

}

}

};
  • Pass one of the following parameters to Locator.reverseGeocode():
    • Locator.ADDRESS: requests the nearest address or nearest street to the specified latitude/longitude
    • Locator.CITY: returns a value that is focused on the city level Development Guide Retrieve an address by using reverse geocoding 44
    • Locator.COUNTRY: returns a value that is focused on the country level
    • Locator.PROVINCE_STATE: returns a value that is focused on the province or state level

Now, we’ve seen how to use the Locator API to get geospatial and address information. When we talk about coordinates, the next thing that comes to mind is how the same code can be extended to show the location on a map.

Well, BlackBerry also has a Map API that allows us to extend the above example and use the information as is i.e. to plot the address point on a map.

  • Package required
import net.rim.blackberry.api.invoke.*;
import net.rim.blackberry.api.maps.*;
  • Maps is an inbuilt application in BlackBerry. This eliminates the user from writing core Map logic like displaying images, , calling Google Maps API and rendering the image in the application. All we have to do is invoke the external application (external to your application).
  • Create class and constructor
public class showMap {
public showMap ()
{
}
}
  • In constructor create an instance of MapView
MapView mapView = new MapView();
mapView.setLatitude(4328915);
mapView.setLongitude(-8032480);
mapView.setZoom(10);
  • In the constructor, create an instance of the MapsArguments class using the MapView object as an argument. Invoke Invoke.invokeApplication() to open BlackBerry Maps and pass in the MapsArguments object.
MapsArguments mapsArgs = new MapsArguments(mapView);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs);

Or you can also use the Lankmark object return by Locator.geocode

MapsArguments mapsArgs = new MapsArguments(results);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs)

Location Based applications that incorporate maps are everywhere. The BlackBerry platform allows you to incorporate both location information and merge that into maps as we have seen in the blog post. It is important to note that the BlackBerry platform provide additional ways of showing a map using different inputs. You can also embed the map  within the application. What I have covered here are the basics and hope that this article highlights the important nuances that could be useful for developers to try things quickly and then extend the same by building more complex applications.

Pawan Sachdeva
Pawan Sachdeva– Technical Architect

05
Aug

An application menu is critical to any mobile application. This is because real estate in a mobile device is limited, so the developer has to make judicious use of menus to provide good application usability. Android provides us with various ways to introduce a menu. This blog post will cover the different types of menus that you can include in your Android application along with code samples and screenshots.

Android Menus can be classified into 3 types:

  • Options Menu
  • Context Menu
  • Submenu

Options Menu:

Options Menu is the menu displayed when MENU key on the device is clicked.

Options menu is divided into 2 types: Icon Menu and Expanded Menu, based on the number of menu options. Options menu can have any number of menu options, but only the first six options are shown directly when the MENU key is clicked and this is called as Icon Menu. In case there are more than six options then first five are show directly and remaining are available when More button is clicked and is called as Expanded Menu.

Note: It is not mandatory to have icon for Icon Menu options. In case icons are associated with menu options,then the icons are displayed for Icon Menu only.

Important Points:

  • onCreateOptionsMenu() method of the Activity is called when the user clicks the Menu Key of the device. So override this method in the activity and populate the Menu object passed as parameter to this method.
  • Multiple add() methods are available. Use the one that accepts itemId as a parameter.
  • onOptionItemSelected() method of the activity is called when a particular Item/Option of the menu is clicked. Override this method in the activity and implement your code to perform the corresponding actions based on the menu option selected.
  • setIcon() is used for assigning icon with the option.

The listing below shows how to add a menu dynamically via code. We are overriding the onCreateOptionsMenu method that is automatically invoked when the User clicks on the MENU key on the device.

public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.ic_menu_add);
menu.add(0, MENU_DELETE, 0, "Delete").setIcon(R.drawable.ic_menu_delete);
menu.add(0, MENU_SAVE, 0, "Save").setIcon(R.drawable.ic_menu_save);
menu.add(0, MENU_DONE, 0, "Done").setIcon(R.drawable.ic_menu_done);
menu.add(0, MENU_HELP, 0, "Help").setIcon(R.drawable.ic_menu_help);
menu.add(0, MENU_SETTINGS, 0, Settings").setIcon(R.drawable.ic_menu_settings);
menu.add(0, MENU_EXIT, 0, "Exit").setIcon(R.drawable.ic_menu_exit);
return true;
}

The listing below shows how to you can react to different menu items that are clicked. We are only displaying the template below. The actual implementation when a specific menu item is clicked depends on your application.

public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case MENU_ADD:
// Add
<span style="white-space: pre;"> </span>return true;
case MENU_DELETE:
// Delete
<span style="white-space: pre;"> </span>return true;
case MENU_SAVE:
// Save
<span style="white-space: pre;"> </span>return true;
case MENU_DONE:
// Done
<span style="white-space: pre;"> </span>return true;
case MENU_HELP:
// Help
return true;
case MENU_SETTINGS:
// Settings
<span style="white-space: pre;"> </span>return true;
case MENU_EXIT:
// Exit
<span style="white-space: pre;"> </span>return true;
default:
<span style="white-space: pre;"> </span>return false;
}   <span style="white-space: pre;"> </span>
}

Context Menu:

Android provides the facility to open a menu in context with the object clicked. A Long-press on the view will bring up the registered Context menu.

Important Points

  • Using registerForContextMenu() method view is registered for context menu.
  • onCreateContextMenu() method of Activity is called on click (long-press) of registered view. So override this method to populate Context menu options.
  • onContextItemSelected() method of activity is called whenever item/option from context menu is selected. Override this method to perform the appropriate operations depending on the option selected.
public void onCreateContextMenu(ContextMenu menu, View v,

 ContextMenuInfo menuInfo) {

 super.onCreateContextMenu(menu, v, menuInfo);

 menu.add(0, MENU_ADD, 0, "Edit");

 menu.add(0, MENU_DELETE, 0, "Delete");

}

public boolean onContextItemSelected(MenuItem item) {

 switch(item.getItemId()){

 case MENU_ADD:

 // Add

 return true;

 case MENU_DELETE:

 // Delete

 return true;

 default:

 return false;

 }

}

For this example context menu is register to be shown on TextView. Here tv is an instance of a TextView that is present on the layout of this activity.
registerForContextMenu(tv);
Context Menu

Menu Using XML

Menu can also be defined and populated using XML. Following XML structure represents the same menu as of above.
Create optionsmenu.xml under folder res/menu
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/MENU_ADD"  android:title="Add"
 android:icon="@drawable/ic_menu_add"/>
 <item android:title="Delete" android:id="@+id/MENU_DELETE" android:icon="@drawable/ic_menu_delete"/>
 <item android:title="Save" android:id="@+id/MENU_SAVE" android:icon="@drawable/ic_menu_save"/>
 <item android:title="Done" android:id="@+id/MENU_DONE" android:icon="@drawable/ic_menu_done"/>
 <item android:title="Help" android:id="@+id/MENU_HELP" android:icon="@drawable/ic_menu_help"/>
 <item android:title="Settings" android:id="@+id/MENU_SETTINGS" android:icon="@drawable/ic_menu_settings"/>
 <item android:title="Exit" android:id="@+id/MENU_EXIT" android:icon="@drawable/ic_menu_exit"/>
</menu>

public boolean onCreateOptionsMenu(Menu menu) {
 MenuInflater inflater = new MenuInflater(this);
 inflater.inflate(R.menu.optionsmenu, menu);
 return true;
}

Advantages of using XML for creating menu are:

  • Easily maintain/modify the menu structure due to a clear separation of the menu creation from the code.
  • The code in onCreateOptionsMenu() method is reduced.

Submenus

Sub menu can be added to any type of menu.

Below code shows adding Submenu  for Options menu:

public boolean onCreateOptionsMenu(Menu menu) {

  SubMenu sendMenu = menu.addSubMenu("Send");

sendMenu.add(0,MENU_SMS,0,"SMS");

  sendMenu.add(0,MENU_EMAIL,0,"EMAIL");

 return true;

}

public boolean onOptionsItemSelected(MenuItem item) {

switch(item.getItemId()){

 case MENU_SMS:

 // SMS

 return true;

 case MENU_EMAIL:

 // Email

 return true;

 default:

 return false;

 }

}
Submenu

Submenu

<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/MENU_SEND"
 android:title="Send">
 <menu>
 <item android:id="@+id/MENU_SMS" android:title="SMS"></item>
 <item android:id="@+id/MENU_EMAIL" android:title="EMAIL"></item>
 </menu>
</item>
</menu>
As covered in this blog post, Android provides several ways to include menus in your application. You should pick and choose them depending on your needs. Context Menus are typically expected now by users and should be used carefully in order to provide good application usability.

Prashant Thakkar
Prashant Thakkar– Team member – Xoriant Mobile Center of Excellence.