Archive for the ‘Android’ Category

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.

, , ,

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.

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

, , , ,

29
Aug

In the current scenario in the mobile space, there are a lot of discussions revolving around Android and its advantages and then there are those who just cannot avoid the constant comparison with the iPhone. Keeping up with the theme, now here is something that is definitely an edge for android and sure to make the iPhone users sit up and take notice. If you still haven’t guessed it, let me tell you, what  I am referring here  is the feature called widgets. For those of you who haven’t heard of widgets, this blog will give you all what you need to know.

What are Widgets?

Well, basically they are simple miniature applications/app views that can be embedded in other applications for e.g. Home screen.. I am quite sure you must be hooked up to Facebook, so say you could have a miniature view on the home screen, that allows you to post on to your wall and then constantly update you with recent likes or comments and status updates in a small scrollable view. Well this is not just a possible concept, it exists. This is exactly what a widget is. Likewise widgets exist for a variety of applications like stock market, audio manager, battery manager etc. Everything is on the home screen and you don’t even have to launch the application. The best part about a widget is, it can update itself constantly if required without you having to refresh your screen. That’s precisely as easy as it gets!!!

Now have a look at the demo snaps and then let’s get on with creating these widgets. It’s really very simple. What we are going to do is create a simple digital clock. So let’s begin!!!

Now follow these steps and you will be on your way to creating your very own widgets for the Android Application.

Step 1: Modify Android Manifest File For the Application:

What we are essentially doing here is specifying the broadcast receiver that will process the app widget updates. The meta-data tag is used to inform android about the widget provider. In this case it is located in res/xml/widget.xml. The activity tag is used to declare the activity and the event that launches it.

Have a look at the code snippet below:

<application android:icon="@drawable/icon"
                 android:label="@string/app_name"
                 android:theme="@android:style/Theme.Translucent">

		<receiver android:name=".Widget" android:label="Custom Digital Clock">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />
        </receiver>

        <activity android:name=".info">
        	<intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.INFO" />
            </intent-filter>
        </activity>

    </application>

Step 2: Create Widget Provider xml file as specified in the manifest:

Following  is the definition of the widget. It has only one element i.e. appwidget-provider which takes attributes specifying minimum width, height, the update frequency and the initial layout or design for the widget. Now that was simple wasn’t it!!!

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dip"
android:minHeight="72dip"
android:updatePeriodMillis="0"
android:initialLayout="@layout/widget"/>


Step 3: Create Layout for the Widget(widget.xml)

Now this step is pretty self explanatory. You simply have to create layout to represent the widget. Yet the Code sample is available as always for your reference.

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

 <TextView android:textColor="@android:color/primary_text_dark"
	android:padding="10dip"
	android:textSize="35dip"
	android:layout_width="wrap_content"
	android:text="12.30.35 PM"
	android:layout_gravity="center_horizontal"
	android:typeface="monospace"
	android:textStyle="bold"
	android:layout_marginRight="3dip"
	android:background="@null"
	android:layout_marginBottom="3dip"
	android:layout_marginLeft="3dip"
	android:id="@+id/widget_textview"
	android:layout_height="wrap_content"
	android:layout_marginTop="3dip"/>

</RelativeLayout>

Step 4: Create Widget Provider Class

Don’t get alarmed by the name here, it’s very simple. All you need to do is create a class that extends the AppWidgetProvider class. This is the same provider specified in the manifest file as the receiver.

The onUpdate() method needs to be overridden to include the necessary code to update time, which can be easily done using the TimerTask class in the java.util package and then it can be represented in a text view as per layout.

The onUpdate() method is called whenever an update is to be performed. Additionally pending Intents may be used to configure action to be performed on click of the widget. In this case the widget will display a simple information activity on click. Pending Intents can be given to other applications which serve as permission for the app to perform specified operation.

public class Widget extends AppWidgetProvider
{
    private Handler mHandler  = new Handler();
    RemoteViews views;
	AppWidgetManager appWidgetManager;
	ComponentName currentWidget;
	Context context;
	DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT,Locale.getDefault());

	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	{

		//Update Widget Using a a runnable and a handler to manage it.
		.
		// some code here.
		.
		mHandler.removeCallbacks(mUpdateTask);
       		mHandler.postDelayed(mUpdateTask, 100);

	} 

	final Runnable mUpdateTask = new Runnable()
	{
	   public void run()
	   {
		   Intent informationIntent = new Intent(context,info.class);
	       PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 0, informationIntent, 0);
	       views.setOnClickPendingIntent(R.id.Widget, infoPendingIntent);
		   views.setTextViewText(R.id.widget_textview,format.format(new Date()));
		   appWidgetManager.updateAppWidget(currentWidget, views);
		   mHandler.postDelayed(mUpdateTask, 1000);

	   }
	};

Step 5: Create Information activity and xml file

This is a simple activity with a text view that is used to display some information on click of the widget. Creating a layout may be a piece of cake for you by now but the sample is there for your reference as always.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
			    android:layout_width="fill_parent"
			    android:layout_height="fill_parent"
			    android:background ="@android:color/white"
			    android:scrollbars="vertical">

	<TextView android:layout_width="fill_parent"
			  android:layout_margin="3dip"
			  android:textColor="@android:color/black"
			  android:layout_height="wrap_content"
			  android:text="@string/information" />

</RelativeLayout>

So here we go, with the help of a few simple steps, we have created our very own widget. Wasn’t that straightforward? I am sure you would be amused at the simplicity of the thing and yet its elegant beauty which is there for all to see.

As with everything, along with a dozen of advantages there are a few downsides to it , else how would we improvise? So a few things that you must keep in mind while you are involved in creating widgets are:

  • They can consume a lot of resources, battery life so you need to regularly kill open unused apps.
  • They take some real estate on screen, so you need alternate screens and launchers for some extra space.

So keep these in mind while making and embedding widgets on your home screen and you should have absolutely no problem. If you still get stuck while making your widget you can always use the entire source which is available for download or leave a comment and I would be pleased to answer it.

Vinay Ramkrishnan
Vinay Ramkrishnan– Team Member – Mobile CoE

, , , ,

06
Sep

After having invested your time and efforts in developing the most creative Android application, you surely want to make it available to a larger audience. Go ahead and read this blog to find information on How to sign your Android applications and publish them to the market.

In this blog post, I am going to talk about the very basic steps that are mandatory to get application published in to Android Market. Android Market https://market.android.com is a store developed by Google for Android devices, it allows users to download published apps of different developers.

Follow the below procedure to generate a suitable .apk file for Android market.

1. Specify Version

To define the version information for application, set following attributes in the application’s manifest file:

android:versionCode - An integer value that represents the version of the application code

android:versionName – A string value that represents the release version of the application code

Versioning is required for following reasons:

  1. To check compatibility and dependency issues between applications.
  2. While Publishing and Upgrading the application to Android market
  3. It is also used in the Android Market to automatically offer application upgrades to users.

Here’s an example manifest file that shows the android:versionCode and android:versionName attributes in the <manifest> element.

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.package.name"
android:versionCode="2"
android:versionName="1.1"&gt;
&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;

2. Signing of Application

Google expects a Signed copy of the application in order to verify the developer account. The Android system will not install or run an application that is not signed. In preparation of signing the application, you must first ensure that you have a suitable private key, if you don’t have any private key then generate it with following 2 methods.

A. Using Command line tools

B. Using Eclipse ADT

A. Using Command line tools

Following are the 4 processes to generate published .apk file.

a. Obtain a suitable private key

Use following command to generate a private key:

$ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

Command line attributes:

  • -v = Verbose mode
  • my-release-key.keystore = generated key file
  • alias_name = alias name for application
  • validity = expiry time here is 10000

The above command generates the keystore as a file called my-release-key.keystore. The keystore and key are protected by the passwords you entered. The keystore is valid for 10000 days.

b. Compile the application in release mode

To export an unsigned .apk from Eclipse follows th steps:

  1. Right-click the project in the Package Explorer
  2. Select Android Tools > Export Unsigned Application Package.
  3. Then specify the file location for the unsigned .apk.

c. Sign your application with your private key

When application package is ready to be signed, then you can sign it by using the Jarsigner tool.

$ jarsigner -verbose -keystore my-release-key.keystore my_application.apk alias_name

Command line attributes:

  • -verbose = Verbose mode
  • my-release-key.keystore = generated key file.
  • alias_name = alias name for application
  • my_application.apk = unsigned application

While running the above command, Jarsigner prompts you to provide passwords for the keystore and key. It then signed the .apk file. Use following command to verify that your .apk is signed:

$ jarsigner -verify my_signed.apk

If the .apk is signed properly, Jarsigner prints “jar verified”.

d. Align the final APK package

Once you have signed the .apk with your private key, run zipalign on the file.The zipalign tool is available inside the Android SDK, tools/ directory folder. Follow the command to align your .apk file:

$ zipalign -v 4 your_project_name-unaligned.apk your_project_name.apk

The input .apk must be signed with your private key before you optimize the package with zipalign

B. Using Eclipse ADT

Follow the steps to create a signed and aligned .apk by Eclipse ADT:

  1. Select the project in the Package and select File > Export.
  2. Open the Android folder, select Export Android Application, and click Next.
  3. The wizard now guide you the process of signing your application, including steps for selecting the private key or creating a new keystore and private key.
  4. Complete the Export Wizard and your application will be compiled, signed, aligned, and ready for distribution.

3. Preparing to Publish: A Checklist

Following checklist is useful while publishing android application to market.

  1. Complete your application testing extensively on an actual device
  2. Consider adding licensing support
  3. Specify an icon and label in the application’s manifest, you define the attributes android:icon and android:label in the <application> element of the manifest.
  4. Turn off logging and debugging and clean up data/files
  5. Remove the android:debuggable=”true” attribute from the <application> element of the manifest.
  6. Specifying an appropriate value for both the android:versionCode and android:versionName attributes of the <manifest> element in the application’s manifest file.
  7. Generate a private key by keytool utility and compile it with application by using release mode.
  8. In <manifest> file check that the proper permissions are used, so that user can grant permissions when application is installed in device.

For example:

<pre>&lt;uses-permission android:name="android.permission.CAMERA"&gt;&lt;/uses-permission&gt;
&lt;uses-permission android:name="android.permission.READ_PHONE_STATE"&gt;&lt;/uses-permission&gt;
&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"&gt;&lt;/uses-permission&gt;
&lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;</pre>

9. For supporting maximum screen sizes of devices used by customers, following attribute must be added in the Manifest file.

With these steps and procedures you are quite set to upload and disclose your Android application to the world .Some attractive screenshots along with a perfect description should get you going. So keep developing your applications with interesting UI and continue adding more innovative apps to the market and your portfolio. And if you encounter issues do write us back here and we shall surely reply.


Suresh Rapakala– Sr. Member at Xoriant QA Center of Excellence

, , , , ,

09
May

Windows 8 has some new and exciting features that far outweigh those that were offered through Windows 7. However, the question still remains, are these new features enough to convince consumers to choose Windows 8 over IOS or Android? By comparing the three, you can get a better idea of which one is the right choice for your mobile needs.

1. iOS(iPhone)

Pros

  • Offers copy and paste options
  • Allows users to multi-task
  • Has HTML5 support
  • Offers Internet tethering
  • Features video calling and visual voicemail
  • Offers threaded email with a unified inbox
  • Has exchange support
  • Application placement is customizable
  • Offers 300,000+ applications
  • Offers storage folders.

Cons

  • Does not offer widgets
  • Does not feature Facebook or Twitter integration
  • Does not offer flash support or Silverlight support
  • No removable storage available
  • No Microsoft office integration
  • No Xbox live integration.

2. Android

Pros

  • Offers copy and paste options
  • Multi-tasking
  • Flash support
  • Offers HTML5 support
  • Offers unified inbox and threaded email
  • Has video voicemail and visual calling
  • Removable storage is available
  • Offers Facebook and Twitter integration
  • Application organization is customizable
  • Features folders for storage
  • Has widgets available.

Cons

  • Does not have Silverlight support
  • Video calling is through a third party app
  • Microsoft support is through a third party app
  • 90,000+ mobile apps available.

3. Windows 8 (Windows phone)

Pros

  • Offers exchange support
  • Facebook integration
  • Has built-in Xbox live integration
  • Build in Microsoft office support
  • Customizable mosaic tile user-interface
  • Support available for ARM based chipsets, tablets and sensors
  • Application information available while the mobile app is closed
  • New charms allow users to customize apps and settings
  • Multitasking available
  • Application size change available
  • Customizable start menu
  • Two touch keyboards
  • Has Internet explorer 10 browser
  • Allows multiple users on one device
  • Web navigation by touch
  • Offers copy and paste.

Cons

  • No removable storage
  • 1,000+ mobile apps
  • No twitter integration
  • Video voice calling through third party app only.

If you’re looking for a device with the highest amount of mobile apps available, IOS is the way to go. With over 300,000+ apps available and more being offered every day, IOS has the biggest app store available in the mobile industry. For those looking to use their mobile device to watch flash videos, the Android would be a wise choice as this is the only device of the three that has flash capabilities. For someone looking for a PC like experience, Windows8 would be a wise choice. Windows8 mobile offers many of the features that are offered on a regular PC, yet fits all these features within the palm of your hand.

, , , ,