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.

16
Sep

A commonly used class in any application, whether it is a desktop application or a mobile application is an application level class. An application level class also called a controller is a single instance available across the application and visible to all modules within an application. This application controller can be used to maintain global state across an application, contain common methods, etc.

Android provides support in every application to create an application wide class. The base class for this is the android.app.Application class. The official documentation of the Application class is given below:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's <application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.

Let us look at how to incorporate an Application class in our Android applications.

Step 1: Provide an implementation of the Application class

You need to extend the android.app.Application class and override the OnCreate method. This method is invoked by the Android runtime once when your application is started. So this is a good point to do application initialization and set some global settings like shared preferences, etc.

Shown below is a template for your own Application class:

public class ApplicationController extends Application {

	//Application wide instance variables
      //Preferable to expose them via getter/setter methods
@Override
	public void onCreate() {
		super.onCreate();
		//Do Application initialization over here
        }
        //Appplication wide methods
}

Step 2: Code your Application class

You can then introduce public methods in your Application class above. These public methods can then be called from anywhere in the Android application. We shall how to invoke them in Step 4.

Step 3: Specify our Application class in the Android manifest.xml file

Specify your application class in the Android manifest.xml file. Each Android manifest has the <application> tag and you need to provide the application class as an attribute of this element as shown below:

<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".android.controller.ApplicationController">

Step 4: Utilize the Application class from other places in your application

To access the Application class instance in any activity, you can use the code as shown below:


ApplicationController AC = (ApplicationController)getApplicationContext();

The main method is getApplicationContext(). This gives an instance to the Application class if defined in the application. You need to simply type cast it to your provided Application implementation class. Once you have this instance, you can invoke any public methods that you would have defined in the class. Additionally, if you provide getter/setter methods for application wide state variables, you can invoke them too.

Having an Application wide controller in your application is a commonly used design with significant benefits. Instead of rolling out your own custom implementation, Android provides a simple mechanism to introduce it in your applications, letting you focus on your Application wide logic while it takes care of its lifecycle methods. Start using the Application class to bring in structure to your applications today.

Romin Irani
Romin Irani– Principal Architect

,

31
Dec

At times we are in need to store some data locally for faster retrieving and processing. One of the ways to store data locally is to write it in the file, and read it whenever needed. But there is another approach of using Database. Advantages of using database are like one doesn’t need to read entire file, load it in memory for getting some small chuck of data, also from developer perspective retrieve data from database would be easier.

In this article we will look at how to use android’s inbuilt supported sqlite database.

Let us look at the example of employee_database with employee table having columns _id, emp_name, emp_designation. With _id set as integer, primary key and autoincrement and emp_name and emp_designation to string/text.


package com.dbexample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class EmployeeTable{

	public static final String KEY_NAME = "emp_name";
	public static final String KEY_DESIGNATION = "emp_designation";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "EmployeeTable";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	private static final String DATABASE_NAME = "employee_database";
	private static final String DATABASE_TABLE = "employee";
	private static final int DATABASE_VERSION = 3;

	/**
	 * Database creation sql statement
	 */
	private static final String DATABASE_CREATE =
		"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
		+ KEY_NAME +" text not null, " + KEY_DESIGNATION + " text not null);";

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.i(TAG, "Creating DataBase: " + DATABASE_CREATE);
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 *
	 * @param ctx the Context within which to work
	 */
	public EmployeeTable(Context ctx) {
		this.mCtx = ctx;
	}

	public EmployeeTable open() throws SQLException {
		Log.i(TAG, "OPening DataBase Connection....");
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public long createEmployee(String empName, String empDesignation) {
		Log.i(TAG, "Inserting record...");
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NAME, empName);
		initialValues.put(KEY_DESIGNATION, empDesignation);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	public boolean deleteEmployee(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	public Cursor fetchAllEmployee() {

		return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
				KEY_DESIGNATION}, null, null, null, null, null);
	}

	public Cursor fetchEmployee(long empId) throws SQLException {

		Cursor mCursor =

			mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
					KEY_NAME, KEY_DESIGNATION}, KEY_ROWID + "=" + empId, null,
					null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	public boolean updateEmployee(int empId, String empName, String empDesignation) {
		ContentValues args = new ContentValues();
		args.put(KEY_NAME, empName);
		args.put(KEY_DESIGNATION, empDesignation);

		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + empId, null) > 0;
	}

}

In above example, EmployeeTable class has a private inner class DatabaseHelper which extends SQLiteOpenHelper class. SQLiteOpenHelper calss is responsible for calling onCreate and onUpgrade method whenever database is opened for either read or writes operation. onCreate method will check whether the table exist if not will create it, similarly onUpgrade method. Beside inner class EmployeeTable contains various other methods to createEmployee, deleteEmployee etc.

Snippet for Inserting Employee


EmployeeTable employeeTable = new EmployeeTable(this);
    	employeeTable.open();
    	employeeTable.createEmployee("Prashant Thakkar", "Tech Lead");
    	employeeTable.close();

Create instance of EmployeeTable and call it’s open() method. open method of EmployeeTable will create instance of DatabaseHelper and will open database connection with write permission. After open method is called, now call createEmployee method which accepts 2 parameter employee name and designation, this will insert a record in table employee. Since emp_id is set to autoincrement while creating database it will be set appropriately. Similarly close() method of EmployeeTable will close the database connection.
Snippet for retrieving Employee

EmployeeTable employeeTable = new EmployeeTable(this);
    	employeeTable.open();
    	Cursor c = employeeTable.fetchEmployee(1);
    	Toast.makeText(this, “Name: ” + c.getString(1) + “ Designation: “+ c.getString(2), Toast.LENGTH_LONG).show();
    	employeeTable.close();

fetchEmployee method of EmployeeTable accepts empId as parameter and returns cursor pointing to employee.
CursorAdapter
Let us look at how we can directly use cursor returned, for populating ListView.

EmployeeTable employeeTable = new EmployeeTable(this);
employeeTable.open();
Cursor c = employeeTable.fetchAllEmployee();
if (c != null){
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this,
		R.layout.listview,
		c, // Give the cursor to the list adapter
	new String[] {c.getColumnName(1),c.getColumnName(2)}, // Map the column in the
		// employee database to...
new int[] {R.id.EmployeeName, R.id.EmployeeDesignation}); // The view defined in the XML template
		ListView empListView = (ListView)findViewById(R.id.Employee);
		empListView.setAdapter(adapter2);
		}
		employeeTable.close();

listview.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/MainLayout">
	<TextView android:id="@+id/EmployeeName" android:layout_alignLeft="@id/MainLayout"
		android:layout_width="wrap_content" android:layout_height="wrap_content" />
	<TextView android:id="@+id/EmployeeDesignation" android:layout_alignParentRight="true" android:layout_toRightOf="@id/EmployeeName"
		android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>

Point to remember is for using cursor for this kind of data binding operations we need to make sure that respective table have one column as _id
Conclusion
In this article introduces basics of Android SQLite database, created database and table, fetched records from database and also learned how to use SimpleCursorAdapter .

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

30
May

In this blog post we would try and understand the basics of Application Manifest in the Android system.

The simplest of any Android application has  the following components:

  1. Resources classified in the resource folder (res).
  2. Some auto generated code like R.java.
  3. ApplicationManifest.xml file.

This blog post will deal with the third component – Application manifest file.

Application Manifest is an xml file every Android application contains with the name ApplicationMainifest.xml in the root directory of the application.

-          The file is generated automatically on finish of wizard for android project creation.
-          File gives all the information pertaining to the successful execution of all the functionalities present in the application to the android system.
-          It is like a blue print of the application components or what you can call a make file in C++ projects like Qt, Objective C in IPhone.

Sample example:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.android.sampleApp" android:versionCode="1"
	android:versionName="1.0"> - (1)
	<application android:icon="@drawable/icon" android:label="@string/app_name"
		android:permission="android.permission.BLUETOOTH"> - (2)
		<activity android:name=".SampleActivity" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity> - (3)
	</application>
	<uses-sdk android:minSdkVersion="9" /> - (4)
	<permission android:name="com.android.myPermission"
		android:icon="@drawable/icon"
		android:label="My Permission"
		android:protectionLevel="dangerous"
		android:permissionGroup="com.android.SamplePermission"
		android:description="@string/some_description"></permission>
</manifest>

Versioning:

Refer line (1) in the code above.

<manifest> tag consists of application versioning information (android:versionCode and android:versionName) helps the android systems to maintain the upgrade/ downgrade of application.

Android system uses versionCode for understanding the upgrade of the application on the device and versionName is used only for the user notification purpose. versionName is displayed for the user to notify that a newer version of the application is available in the market.

Activity:

Refer line (3) in the code above.

Android application consists of four types of components:

  1. Service – Non-visual component always running in background to perform long operations.
  2. Content providers – It’s a data storage system eg: File storage systems and SQLite. Content providers provide a standard interface that helps in application doing standard operations on database system. E.g. address book, messages, emails etc.
  3. Broadcast receivers – status messages / events / error handling etc. for an example error messages,
  4. Activity – Activity are screens that user interacts with while using the application, it may be a form collecting keyboard inputs, clicks etc. It is same as a form is to a web application.

Activities need to be register for an application in the Manifest file for Android systems to include them in the run environment. An application may consist of one or more activities; there can be multiple activity tags in the application which may interact with each other.

<intent-filter> – Intent filters control which actions of android, user driven or application driven is going to launch the application. Activities can contains multiple intent filters. Contains:

-          <action> as MAIN (android:name=”android.intent.action.MAIN”) means that this activity is the entry point for the application.  This activity will be the top level screen (Home screen) in the application.

-          The manifest xml above show case how you can place your activity on the android home screen launcher. For that you have to put a <category> with Launcher (android:name=”android.intent.category.LAUNCHER”) telling the system that this activity should be top-level LAUNCHER.

Permission:

Refer line (2) in the code above.

Android OS model requires applications to highlight what features of OS or resources they are going to use. Take an example of an application that is going to make use of the Bluetooth for transfer of files or need internet access for connection to facebook, twitter etc.

Hence, this tag provides the information related to the access rights to the specific components or features of the application from the very same application or other applications. By default android applications do not have any permission to intervene the device data or components.

This can be provided either in <application> tag or <uses-permission>

For example:

  1. Permissions to access BLUETOOTH of device is: <application android:permission=”android.permission.BLUETOOTH” />
  2. To Receive SMS: <uses-permission android:name=”android.permission.RECEIVE_SMS” />

User can define their set of permissions under <permissions> tag.

SDK Version:

Refer line (4) in the code above.

Application which makes use of specific features like 3D transitions available in higher version Android SDK say 3.0 will not work on the devices having lower version say 2.3. Hence manifest file provides the information to the system while installation; checking for the availability of SDK version and install accordingly.

<manifest> tag holds <uses-sdk> containing minimum API level  integer (android:minSdkVersion) which helps the Android system to allow/disallow installation of the application depending upon the system’s API level.

Eg: For minSdkVersion = 9 minimum system’s API level is Android 2.3.3 SDK.

For detailed information on Manifest refer:  Application Manifest

Fahim Shaikh
Fahim Shaikh– Software Engineer – Mobile CoE

, , , , , , ,

06
Jun

Can your application tweet, can it post on walls of people who like this application? Let’s have a look at how to integrate twitter with an android application.

What is OAuth?

OAuth is an open protocol which allows the users to share their private information and assets like photos, videos etc. with another site without sharing their credentials (username and password) to the latter. Hence making it very secure way of transmission of data..

Reference: You can learn more about the same at About OAuth.

We will learn about how this connection is implemented below. Here are the steps that will lead to create a successful twitter post.

  • Get your application signed to twitter site – You will have to login first. This will give you a form to fill up the application details like Application Icon, Application Name, Organization, etc. The most important of these is the Application type (which should be Browser Type) and Callback URL. Also, give access type as Read and Write.

On submission of the form you will receive Customer Key and Customer Secret. Copy these and keep them for usage in the android application.

  • Create an Android project from the IDE, I am using Eclipse to show the below example.

In application manifest xml add the INTERNET permissions and BROWSABLE intent filter. To know more about application manifest you can refer to my post on Application Manifest where I have explained the key components of Application manifest. Here I am going to highlight only the intent filter which will launch browser and data tag which describes the call back URL where the twitter data is downloaded and displayed to the user.

<?xml ………… >
……
……
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
	<category android:name="android.intent.category.DEFAULT"></category>
	<category android:name="android.intent.category.BROWSABLE"></category>
	<data android:host="OAuthTwitter" android:scheme="myTweet"></data>
</intent-filter>
……
……
</xml>
  • Twitter4j is a Java library for Twitter API’s which also you to integrate your Java application with the Twitter services. Advantage of using this is, it is very simple to use and with OAuth it provides a very secure interaction. To know more about Twitter4j refer link. Twiiter4j related can be discussed on Google group. You’ll need to download jar files from twitter4j (twitter4j-2.2.2.zip) and signpost (signpost-core-1.2.1.1.jar & signpost-commonshttp4-1.2.1.1.jar). Add these libraries to the project. Follow below steps for the same.
  1. Right click on the project and go to build path.
  2. Click on “Add external libraries” to add the jar files into the project.

  • There are multiple ways in which you can create a tweet using twitter4j. Below is the simplest way for the same.
package com.android.OAuth;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
import oauth.signpost.OAuthProvider; // ---- (1)

import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import twitter4j.Twitter; // ---- (2)
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;

public class OAuthTwitter extends Activity {
	public final static String CONSUMER_KEY = "give your consumer key"; // ---- (3)
	public final static String CONSUMER_SECRET = "give your consumer secret";
	public final static String CALLBACK_URL = "myTweet-OAuthTwitter:///"; // ---- (4)

	private CommonsHttpOAuthConsumer commonHttpOAuthConsumer;
	private OAuthProvider authProvider;

	private Twitter twitter;

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

        commonHttpOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);  // ----- (5)
        authProvider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
        		"http://twitter.com/oauth/access_token", "http://twitter.com/oauth/authorize");
        try {
			String oAuthURL = authProvider.retrieveRequestToken(commonHttpOAuthConsumer, CALLBACK_URL);
			this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(oAuthURL)));
		} catch (OAuthMessageSignerException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (OAuthNotAuthorizedException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
    }

    protected void onNewIntent(Intent intent) { // ---- (6)
    	super.onNewIntent(intent);

    	Uri uri = intent.getData(); // ---- (7)
    	if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
    		String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
    		try {
    			authProvider.retrieveAccessToken(commonHttpOAuthConsumer, verifier); // ---- (8)

    			AccessToken accessToken = new AccessToken(commonHttpOAuthConsumer.getToken(),
    					commonHttpOAuthConsumer.getTokenSecret()); // ---- (9)

    			twitter = new TwitterFactory().getInstance(); // ---- (10)
    			twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

    			twitter.setOAuthAccessToken(accessToken); // ---- (11)

    			// Alternate way:
    			// twitter = new TwitterFactory().getOAuthAuthorizedInstance(CONSUMER_KEY, CONSUMER_SECRET,
    			//		 new AccessToken(commonHttpOAuthConsumer.getToken(), commonHttpOAuthConsumer.getTokenSecret()));

    			// Tweet message to be updated.
    			String tweet = "Hiee there, This is send from my application - OAuth, Twitter";
    			twitter.updateStatus(tweet); // ---- (12)
    		}
    		catch (Exception e) {
    			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG);
    		}
    	}
    }
}

Here is the brief about the code above. Please see inline numbers above for comments.

-          Lines (1) & (2) shows the “include” of the libraries related to signpost and twitter respectively.

-          Line (3) is where you need to add the Consumer key and Consumer Secret received after registering the application to the twitter site.

-          Line (4) describes the call back URL for the application to which return the user after authorization.

-          Line (5) follows the implementation which opens the network using the consumer key and consumer secret with the help of signpost API’s.

-          After twitter verifies the consumer key and secret the application returns to the line (6).

-          Line (7) verifies the Uri from the intent if containing the call back URL.

-          Line (8) retrieves the token and secret into the OAuthConsumer.

-          Line (9) gets the access token from the OAuthConsumer.

-          Line (10) inits twitter4j for sending the tweet with the respective consumer key and secret.

-          Line (11) sets the access token from the OAuth provider to the twitter4j.

-          Line (12) updates the tweet to the server.

Now your application is ready to send tweet and update application’s status on twitter.

Fahim Shaikh
Fahim Shaikh– Software Engineer – Mobile CoE

, , , , , ,

20
Jul
This entry is part 1 of 3 in the series Mobile UI Design Pattern

The user interface plays one of the most important roles in determining how successfully you can attract and retain the users by making the UI easy to use, efficient and enjoyable. With decision making being increasingly influenced by the online medium, it’s scope is extended to mobile internet. So, it is required to enhance the user experience by developing user friendly interfaces for the apps on the go.

We all are well aware of what all features will be available on the mobile version of a product at hand.  But we are usually not sure about how to arrange them on screen(s), or decide on what framework controls to use to optimize the full potential of a particular product feature. At the end, the most important thing that must not be lost in the process is the simplicity, elegance and the vision, which invariably determines the success or failure of the application i.e. the application rank  in the market(read: popularity).

A good user experience is critical to any application, more so for mobile applications. A good UI will lead to better quality and user experience, eventually translating to popularity and profits. In such a scenario where the users are of utmost consideration in the design and planning of your application, a clean user friendly, simple and yet an innovative UI might just turn a whole lot of users to your application.  Doesn’t it sound appealing as to how something as simple as the aesthetics of an application can do?

Now, this is what we call as “Need of the hour”-But here comes the problem, does anyone know – what is a good UI? How should it look? What should it do? What should it not do, not contain!!!

In such a scenario where you know the problem but not the apt solution, it is always good to have a quick research on how others  got it right.  Abstraction of the problem statement and its respective solution when accepted by a community becomes a pattern. Earlier we had Design patterns for solving design problems of application architecture. “Evolution happened in UI” and now we have a similar set of patterns for the UI. Patterns have emerged as a natural by-product of the design process. Like Software Design Patterns, they too provide a solution to a common/recurring problem. Developing a good and an effective UI requires usage and understanding of these Design Patterns. The best of applications, , are focusing on the use of these design patterns including Twitter Apps, Facebook apps etc.

In this article I shall mainly be discussing these design patterns along with their applications and advantages in use for Android applications and in subsequent ones we shall have a look on how to go about actually creating them.

Dashboard

It has been used in applications even before it was officially introduced as a design pattern. For example, Facebook application has been providing a dashboard of its key functions before it was officially recognized as a design pattern. The Dashboard can be used in apps to highlight the key features of the application. In essence, it is an introduction to the application.  It can be used to reveal new content and capabilities to the user. The dashboard typically occupies the full screen to ensure that it stays out of the way, i.e. the user’s attention is not diverted to any other aspect of the screen/app. The Dashboard may be organized as:

  • Accounts
  • Features
  • Categories

The secondary functionality may be reserved for the Menu options. Thus by making the most common/important operations visible, it ensures that the right things are made visible to the user.

The Good

  • Highlight key features to user
  • Provide one stop access to all the major functions
  • Draw user attention to new capabilities or features introduced
  • Easy navigation around the app.

The Bad

  • All features cannot be represented on the dashboard
  • Some lesser known features not represented, may not get the desired user attention
  • Some represented features may not actually interest user, leading to loss in popularity.

Quick Actions

Quick Actions are basically actions/functions in a popup bar that are triggered by specific visual elements/buttons/items on the screen. They have minimal disruptive influences on the screen context. Quick actions ensure that the screen is not cluttered too much with icons and buttons, and at the same time these options are available to the user only when required. They are very straightforward, can be fast and fun to use. Only the most important and obvious options must be presented in the quick action view. When Items have competing internal options, quick items are typically used. In case of contexts that can/may have multiple selections, quick actions must not be used.

The Good

  • Uncluttered screen, free of too many icons and buttons
  • Minimal disruptive influence on the screen
  • Ensures that key functions can be present when needed
  • All operations/functions common to multiple items on a given screen can be placed in quick action bars.

The Bad

  • It cannot be used if context allows multiple options to be selected at once
  • Operations in the quick action bar are specific to one activity only.

Action Bar

The Action bar is typically located at the top of the screen, used to provide support for all the operations that are frequently used in the application and common to all aspects of the application. Navigation options are also provided in the action bar. It may include a home option to return to the dashboard activity or the main screen. It typically replaces the Title bar in an application. The action bar may be used to bring key actions on screen. Commonly used options present in the action bar include:

  • Search
  • New
  • Refresh
  • Stop
  • Back
  • Forward
  • Undo/Redo etc.

The Good

  • Uncluttered screen, free of too many icons
  • Easy access to key features at all times
  • Easy navigation
  • Indicates current location/state of the app.

The Bad

  • It is always present on top of the screen, taking up valuable space
  • It cannot include all functions of the application, jus t the important ones
  • Too many options (>5) in the action bar might make it clunky and heavy.

Thus ,we can summarize that the design patterns is the need of the hour which  will go a long way in providing a unified and consistent methodology for developing UI’s that will create a lasting impression on the users.

Keeping these fundamental points in mind while designing any user interface, you can get a kick start to your dream to develop the most user friendly interface.  But what about the design patters for Dashboards, Quick Actions and Action Bar?  I am looking forward to soon share these design patterns. So stay connected to have an interactive information sharing.

For more information, you may want to refer to Google’s session on Android UI Design Patterns

Pradeep Sharma
Pradeep Sharma– Technical Lead – Mobile CoE

, , , , , , ,

25
Jul

As most of you all know, the two key candidates for personal Git servers are gitosis and gitolite. The major differentiator between the two is the language in which they are written and the way they handle repo permissions.

The primary focus of this blog will revolve around how to setup a central server for git using gitolite to get started with project development. It is a Perl-based rewrite of Gitosis, is a more sophisticated Git server with more powerful features that has a lot more configuration options. With Gitolite, it’s possible to specify who is able to force a push to a Git branch, an operation that perhaps is challenging when working in teams.

Items that will be covered are:-

  1. Git server setup
  2. Contributors’ and Repository creation.

Git Sever setup:

Using Ubuntu and Gitolite to do the server setup and my workstation is a laptop running Windows 7 OS, let’s get started by following a few simple steps..

Step 1.

Logon to server and add gitolite on the server, you must be in the list of sudoers. If not ask your system administrator or the person who is having sudo rights.

sudo adduser  --system   --shell /bin/bash  --home /home/gitolite gitolite
sudo passwd gitolite
exit

Step2:

Install msygit on your windows workstation from – http://code.google.com/p/msysgit/ .  I have picked up a portable installation and changed my home folder to point somewhere in E:, I didn’t like everything to be in my default windows home folder. I followed this blog – http://markashleybell.com/articles/portable-git-windows-setting-home-environment-variable

It is not necessary though, a standard install will also work.

Once you Fire the git bash shell and run git –version; you should see something like this

Step 3:

Create the ssh public/private keypair on your workstation. This will required a password less login into remote system. As of now do not put a passphrase. Hit enter key for an empty passphrase.

ssh-keygen

Step 4:

Now go to your home directory by typing the following command

cd ~

Step 5:

Copy the public key to remote server into gitolite account, key in password when asked. The key will get saved as pradeep.pub on server in /home/gitolite

scp .ssh/id_rsa.pub gitolite@ubuntu:~/pradeep.pub

Step 6:

Logon to ubuntu as gitolite

git clone git://github.com/sitaramc/gitolite
cd gitolite
src/gl-system-install
cd
echo 'export PATH=$PATH:$HOME/bin' >> $HOME/.bashrc
. $HOME/.bashrc
echo $PATH
gl-setup $HOME/pradeep.pub

Step 7:

Finally  go to git bash shell on your workstation and clone gitolite

git clone gitolite@ubuntu:gitolite-admin

Contributors’ and Repository creation.

After having set up the git server on your workstation let’s move further to create a repository.

  • The admin is already set with userid pradeep. So will now try to add a user who is having only read/write access to one of the repositories .
  • Ask your team member, in this case Fahim, to send his public key over email or you can take it on a pen drive.
  • Put the key inside gitolite-admin keydir and edit the conf/gitolite.conf to make an entry for the user. Here, I am going to create a helloworld repo and add Fahim to have RW access to it. We just need to edit the conf/gitolite.conf file. Put a new line
  • Once you check status of the repo, it should show you: git status

  • Commit and push it to central server.
git add conf/gitolite.conf
git add keydir/fahim.pub
git commit –m ‘adding new user having read/write access to helloworld repo’
git push –all gitolite@ubuntu:gitolite-admin

So, It’s done ! We got our repository created and added to Gitolite with the help of these simple steps. Hope this serves as a complete guide to setup a git server.

Pradeep Sharma
Pradeep Sharma– Technical Lead – Mobile CoE

, , , , , , ,

28
Jul
This entry is part 2 of 3 in the series Mobile UI Design Pattern

The earlier post here has covered the importance and the basics of developing a user friendly UI, taking this further we will be presenting to you a detailed view of the design patterns discussed. The following post will cover the ‘Dashboard ‘ design pattern along with a step by step process to help you develop a dashboard yourself. The code snippets attached will allow you to learn and build the dashboard in no time.

Introduction:

Trust me when I say it’s too easy. Have you seen the Facebook application for Android? You will see the home screen has image icons for all major features of the application like messages, wall posts, friends, albums etc. This is exactly what a dashboard is. You might have actually used this before without even knowing it is a design pattern. The dashboard lets you highlight key/new features and provide easy navigation to various parts of the app. A detailed description of the same was given in my blog on User Interface Design Tips which I trust you would have read. Even if you haven’t, I would suggest going back to that article and reading it to get a clear picture of the dashboard design pattern. This will make this article a better read for you as it provides simple steps for creating your very own dashboard. So let’s begin!!!

A typical dashboard for any application may look like this:

Full source code for this sample application is available on xoriant’s public github repo - https://github.com/github-xoriant/Android-Dashboard-UI-Pattern

Listed are a few steps for creating a typical dashboard with precise detailing. Follow them to have a clear understanding

Step 1: Create Home Screen

Follow these codes to get your Home Screen in simplest possible way.

<LinearLayout android:orientation="vertical"
      				  android:layout_width="wrap_content"
      				  android:layout_height="wrap_content"
      				  android:layout_marginTop="60dip"
      				  android:layout_marginLeft="40dip" android:layout_marginBottom="40dip">

        	<ImageView android:id="@+id/photoAlbum"
            			 style="@style/Home"
            			 android:onClick="onPhotoAlbum"
           				 android:src="@drawable/photoalbum"/>

        	<TextView style="@style/HomeText"
        			  android:id="@+id/ph1"
        			  android:text="@string/photoAlbum"
        		  	  android:layout_marginTop="10dip"/>
</LinearLayout>
<LinearLayout style="@style/TitleBar"
    			  android:id="@+id/layout1">

       <ImageView style="@style/TitleBarLogo"
       			  android:id="@+id/img1"
                  android:src="@drawable/dashboard"
                  android:onClick="onHome"
            	  android:layout_marginTop = "5dip"
            	  android:layout_marginRight="5dip"
            	  android:layout_marginLeft="5dip"
            	  android:layout_marginBottom = "5dip"
            	  android:paddingBottom = "5dip"
            	  android:background="@null"
            	  android:layout_gravity="center"
            	  android:paddingLeft="5dip"
            	  android:paddingRight="7dip" />

        <ImageView android:layout_width="1px"
        		   android:layout_height="fill_parent"
        		   android:id="@+id/sep"
			       android:background="@drawable/separator"
			       android:layout_marginRight="7dip"
			   />

        <TextView style="@style/TitleBarText"
        		  android:id="@+id/tv1"
        		  android:paddingLeft = "8dip"
        		  android:text="@string/home"/>
</LinearLayout>

The first step is to create a simple layout for the home screen that will house the image buttons. As the name itself says these are simply buttons, which are represented by icons/images present in the resources folder. The layout must have a custom title bar at the top that displays the current location/screen that the user is on, along with a straight link to reach the home screen or the dashboard. All you have to use is the “onClick” attribute of the image view to direct the user to the respective location. The layout is very simple, and all you require is basic knowledge of layout creation which you must be an expert on by this time!!!  Anyway to make it easy have a look at the code snippet for creating an image view for the image icon and the title bar given above. Keep in mind this has to be done in a proper layout.

Step 2:Create Dashboard Abstract Class

Follow these codes to create your own Dashboard Abstract Class.

public abstract class DashboardAppActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    //Lifecycle Methods

    //App Click Methods

    public void onSearch(View v)
    {
    	startActivity (new Intent(getApplicationContext(), SearchActivity.class));
    }

    public void onAbout(View v)
    {
    	startActivity (new Intent(getApplicationContext(), AboutActivity.class));
    }

    public void return2Home(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);
    }

    public void onHome (View v)
    {
    	return2Home(this);
    }
}

By now you will have your home screen ready with you. Now we just need to define the “On Click” handlers that will trigger the necessary action which could be starting a new activity or simply a toast. For this purpose all you need to do is simply define an abstract class, that will contain all the common code like lifecycle methods, On Click handlers for the icons on the dashboard and the title bar(home) as well. In our app we will have to define the handlers to redirect the user to new activities associated with the appropriate image icon. Once done, all your other activities in the application that have representations on the home page will inherit this abstract class. It’s very simple and I am pretty sure you can do this on your own. Just in case, a sample code snippet is available at your disposal as always!!!

Step 3:Create Activities and Layouts

Following are a few codes to help you create your Activities and Layouts.

public class AboutActivity extends DashboardAppActivity
{
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);

	    setContentView (R.layout.about);
	    TextView tv = (TextView) findViewById (R.id.title_text);
	    if (tv != null)
	    {
	    	tv.setText(getTitle());
	    }
	}
}

So now your Dashboard is nearly done. All you need to do is create the activities for all functions that you have listed in the dashboard. Along with the activities you will need the XML Layouts as is the case with any basic activity in Android. These activities must extend the dashboard abstract class. Also, you need to write a few lines of code to display the name of the activity in the title bar.  You can have a look at the sample code given above.

Step 4:Understanding Styles

Finally, refer to the below given codes to Understand Styles.

<style name="TitleBar">
        <item name="android:id">@id/title_container</item>
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">45dip</item>
        <item name="android:orientation">horizontal</item>
        <item name="android:background">@color/title_background</item>
    </style>

    <style name="TitleBarOperation">
        <item name="android:layout_width">45dip</item>
        <item name="android:layout_height">fill_parent</item>
    </style>

    <style name="TitleBarLogo">
        <item name="android:id">@id/title_logo</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">fill_parent</item>
 </style>

So now your dashboard is finally up and running.  Something that you will come across while going through the code is the regular use of styles. These styles are nothing new, and are very similar to style sheets used for  developing web pages. These styles have been defined in the styles.xml file, which is then referred in the app using their ids. A sample of the styles.xml file is given above.

So 4 simple steps and you have your dashboard set up. Now that was unbelievably easy as I had said. Hopefully this tutorial would have provided all the assistance that was required to create your very own creative dashboard.

Source Code

If there are still any problems you always have the complete source code of the app to fall back on Xoriant’s git hub repository. Xoriant- Source code for Android Dashboard UI Pattern

Also you can post your comments here and I will be more than happy to answer them.

I will soon be writing about yet another effective and easy design pattern, “The Action Bar” in my next blog. But till then keep experimenting with your dashboards!!!!

Pradeep Sharma
Pradeep Sharma– Technical Lead – Mobile CoE

, , , , , , ,

03
Aug
This entry is part 3 of 3 in the series Mobile UI Design Pattern

The previous posts on User Interface tips and Dashboard design pattern gave you a fair idea on how to get going with your User Interface.

In this post, we shall look at the Action Bar design pattern in more detail which will enable you to better understand and execute Action Bars on your user interface.

Introduction:

As previously mentioned, action bar is a bar placed atop the screen that houses all the essential actions used in an application. It contains only those actions that are common to the entire application, and not activity specific ones. It is very commonly used in most applications, some even before it was introduced as a design pattern.

The Twitter Application for Android is a prime example. It has an action bar that provides actions like refresh, search, messages etc. The Facebook app is another common app that uses this pattern. Imagine if every app had an action bar, how useful and user friendly it would be. Navigation can also be added there. For now, this should suffice. Let us take a look at how do you actually go about creating it. Of the 3 patterns this is the easiest pattern to implement. So let us try and implement this step by step in the same manner as described in Dashboard Design pattern. Please refer -Xoriant Source Code for Android Dashboard UI Pattern

Take a look at the images below :

Follow these few simple steps to get going with your Action Bar:

Step 1: Create Action Bar Class

First of all, you need to create an abstract base class that houses all the common functionalities like the lifecycle method and the” onClick” handlers similar to the dashboard. In this, “onClick” handlers refer to actions that need to be triggered when the actions on the action bar are clicked. This should be pretty simple, especially after doing it for the dashboard. But as always the sample snippet is available for your reference.

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

    public void onSearch(View v)
    {
    	startActivity (new Intent(getApplicationContext(), SearchActivity.class));
    }

    public void onHome (View v)
    {
    	return2Home(this);
    }

    public void return2Home(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);
    }
}

Step 2: Create Layout For Action Bar

You have got your base class ready. That means half the job is done. Now simply create the layout for the home screen along with the action bar. Remember the title bar will not be present in the application. It will be replaced by the action bar. The layout must include an icon for home, the title of the current view and other options to be displayed on the bar. Don’t include more than 3 options as it looks cluttered. Creating layouts by now won’t be a hurdle. All you need is a couple of image views and text views. The necessary icons/images may be stored in the resources and referred to in the usual way. With the hints I have given you the layout shouldn’t take long to make. Anyhow a sample snippet is always there at your disposal. Take a look at the sample above. Just to remind you; it is only a snippet not the entire code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
			  android:orientation="horizontal"
			  android:layout_width = "fill_parent"
			  android:layout_height="wrap_content"
			  android:gravity="right"
			  android:layout_gravity="right">

			   <ImageButton style="@style/TitleBarOperation"
            			   android:src="@drawable/about_click"
            			   android:onClick="onAbout"
            			   android:layout_marginTop = "6dip"
            			   android:layout_marginBottom = "4dip"
            			   android:layout_marginLeft="5dip"
            			   android:background="@null"
            			   android:layout_marginRight="5dip"/>

			  <ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginLeft = "5dip"
			   android:layout_marginRight="5dip"
			   />

			  <ImageButton style="@style/TitleBarOperation"
            			   android:src="@drawable/search"
            			   android:layout_marginTop = "6dip"
            			   android:layout_marginBottom = "4dip"
            			   android:onClick="onSearch"
            			   android:background="@drawable/home_bg"
            			   android:layout_marginRight="5dip"/>
	</LinearLayout>

Step 3: Append Action Bar to all Activities and create layouts (Modify action bar in case of search)

Now all that remains is replicating the same layout of the home screen action bar across all the other activities. That is simple replication of the code. Also generate the layout for the remaining activities. In case of the search activity, only a slight modification will be needed to the action bar to include a search box as well. That is as simple as appending an edit text to the layout. Have a look at the code snippet below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
			  android:orientation="horizontal"
			  android:layout_width = "wrap_content"
			  android:layout_height="wrap_content"
			  android:gravity="left|center_vertical"
			  android:layout_gravity="left">

			  <ImageButton style="@style/TitleBarOperation"
            			   android:src="@drawable/home_def"
            			   android:background="@drawable/home_bg"
            			   android:onClick="onHome"
            			   android:layout_marginTop = "5dip"
            			   android:layout_marginRight="5dip"
            			   android:paddingBottom="3dip"
            			   android:layout_marginLeft = "4dip"
            			   android:layout_marginBottom = "4dip"
            			   android:layout_gravity="center"/>

              <ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginRight="5dip"/>

              <TextView style="@style/TitleBarText"
              			android:id = "@+id/title_text"
              			android:text = "Action Bar Sample"
              			/>

              <ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginLeft="5dip"
			   />

              <EditText android:id="@+id/input_text"
              			android:layout_height="fill_parent"
              			android:layout_width="100dip"
              			android:layout_marginTop="2dip"
              			android:layout_gravity="center"
              			android:textSize="10sp"
              			android:text = "search here..."
              			android:layout_marginLeft="5dip"
              			android:layout_marginRight="5dip"/>

			<ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginLeft="2dip"/>

Step 4: Modifying styles.xml

With this, your Action Bar is ready. All that remains is adding a few lines of code to your styles.xml file. This style must be appended to the manifest as a theme in the application tag. Basically these lines specify that there will be no title bar in the application, and instead will be overlaid by our own custom action bar. See the sample code to understand.

<style name="Theme.D1" parent="android:style/Theme.Light">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

We have successfully implemented the Action Bar by following these 4 simple steps. Now you can create your very own action bar with actions of your choice. With this we have completed 2 of  the 3 design patterns. The third pattern will soon follow. Only if could imagine how attractive your UI would be if you were to use all 3 patterns in an app. Hopefully you have understood and enjoyed learning these patterns as much as I  am pleased to share them.

Source Code

Should you require full source code for Action Bar, please refer Xoriant-Source Code for Android Action Bar.Like always you can leave your comments here and I will look forward to answering them.

There will be the next blog on design patterns for Quick Actions soon. So watch out for the space to complete your User Interface with third and final design pattern!!

Vinay Ramkrishnan
Vinay Ramkrishnan– Team Member – Mobile CoE

, , , , , ,

16
Aug
This entry is part 4 of 3 in the series Mobile UI Design Pattern

So far with all the previous blogs we have been quite familiar to various aspects like Dashboard and Action bar for a user friendly Interface for Android mobile application.

In this post we shall discuss about the Quick Action design pattern in more detail with which you will be  have a clear understanding of the significant parts of a typical user friendly interface.

Introduction:

As previously mentioned, Quick Actions are basically actions/functions in a popup bar that are triggered by specific visual elements/buttons/items on the screen. Quick Actions are used to display contextual actions typically used in list views but not limited to it. You can imagine a phone-book or contact list on the phone. Now, there are certain set of actions that will be common to all contacts in the views like; make a call, send message, edit contact or may be even transfer files by  Email, Bluetooth etc. Basically these functions that are common to items in a context can be put in the Quick Action bar. This way the screen is uncluttered and simple and more importantly we needn’t sacrifice on the actions needed.

After having learnt about  detailed source code for an Action bar, next let us begin with the creation of the Quick Actions bar. We will make this short and simple, so just follow on…

To begin with, the demo snaps look like this:

Step 1. Create Actionable Items

The below code snippet is used to create an actionable item i.e. the actions you would want to place in the quick action bar. Creating an actionable item involves specifying the title, setting an icon that represents the item which will help you relate to the action, and finally set a Listener for the action. The term itself is self-explanatory. Yes, it is used to determine the action to be performed when clicked or pressed. As far as the icon /image goes, it can be easily set by referring to it from the resources as is the case with any external resource set in android which you would aware of, I am most certain.


final QuickActionIcons edit = new QuickActionIcons();;

 edit.setTitle("Edit");
 edit.setIcon(getResources().getDrawable(R.drawable.edit));
 edit.setOnClickListener(new OnClickListener()
 {
 public void onClick(View v)
 {
 Toast.makeText(QuickActionSampleAppActivity.this,"Edit Contact",Toast.LENGTH_SHORT).show();
 }

 });]

The above actions can be repeated depending upon the number of actions to be put in.

With this, you have successfully created your actions. Next we shall create the quick action dialog that should be displayed on clicking some button or tab.

Step 2: Create Quick Action Dialog

This part is even simpler. Like in this example, when an item in the list view is clicked / pressed, a new quick action bar/dialog is created. Then all the actionable items that you have created in the previous step are appended one by one to the quick action bar. After this you simply have to specify the animation style i.e. how do you want the dialog to be displayed on screen.


resultPane.setOnItemClickListener(new OnItemClickListener()
    {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		{
			QuickActionBar qab = new QuickActionBar(view);

			qab.addItem(edit);
			qab.addItem(call);
			qab.addItem(send_data);
			qab.setAnimationStyle(QuickActionBar.GROW_FROM_LEFT);

			qab.show();
		}
    });

And then finally you display the created quick action bar.

Step 3: Create Animation Files

All animations that you specify will have to be supported by corresponding XML files that allow the animation to play out. These XML files will form a part of your resources. It‘s really not that difficult to create these animation files. Have a look at a sample below.

<strong></strong>

<set xmlns:android="http://schemas.android.com/apk/res/android">
 <scale
 android:fromXScale="0.3" android:toXScale="1.0"
 android:fromYScale="0.3" android:toYScale="1.0"
 android:pivotX="50%" android:pivotY="100%"
 android:duration="@android:integer/config_shortAnimTime"
 />
 <alpha
 android:interpolator="@android:anim/decelerate_interpolator"
 android:fromAlpha="0.0" android:toAlpha="1.0"
 android:duration="@android:integer/config_shortAnimTime"
 />
</set>


Step 4: Create Layouts for actionable Items and Quick Action Bar

Some additional things that you would have to do are create layouts for the quick action dialog and the actionable items. It’s as simple as the layouts that you are so used to creating in android day in and day out. Go on and have a look at the snippet for the quick action items any way.


<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:gravity="center_vertical|center_horizontal"
 android:paddingTop="0dip"
 android:paddingBottom="0dip"
 android:paddingLeft="20dip"
 android:paddingRight="20dip"
 android:clickable="true"
 android:background="@drawable/button_state">

 <ImageView
 android:id="@+id/image"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"/>

 <TextView
 android:id="@+id/caption"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:gravity="center_vertical"
 android:textSize="12sp"
 android:textColor="#ff000000"/>

</LinearLayout>

You may try out the quick action dialog layout by yourself. If you’re stuck you can refer to the complete source code on Quick Action that is available anyway.

By following these 4 simple steps , you are all set and ready to have quick action dialogs zooming around in your app. So go on and try them out.

With a few design guidelines on User Friendly Interface for Android followed by:

I am most certain that you can now design and develop an efficient interface. Should you have any questions on any topic, I would be pleased to answer them.

Pradeep Sharma
Pradeep Sharma– Technical Lead – Mobile CoE

, , , ,