A powerful FrameLayout that specifies behavior for child views for various interactions. All the components within your xml layout should be wrapped inside this coordinator layout.

we can define how views inside the Coordinator Layout relate each other and what can be expected when one of them changes. Behaviours they identify which views another view depend on, and how they behave when any of these views changes.

Android Comparisons: Service, IntentService, AsyncTask & Thread


  • Service used to perform task with no UI, task should not be long running. Use threads within service for long tasks.
  • To trigger call method onStartService().
  • Any thread can trigger.
  • Runs on main thread.It may block main thread.


  • Thread can be used for long running task.
  • For tasks in parallel use multiple threads (traditional mechanisms).
  • To trigger call thread start() method.
  • Need to manage thread manually.
  • Any thread can start.


  • IntentService used for long running task usually with no communication to main thread.
  • Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
  • To use it, extend IntentService and implement onHandleIntent(Intent).
  • IntentService will receive the Intents, launch a worker thread.only one request will be processed at a time.
  • To communicate with main thread, Thread can use main thread handler or broadcast. intents.
  • Intent is received on main thread and then worker thread is spawed.
  • Multiple intents are queued on the same worker thread.


  • This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
  • one instance can only be executed once. We cannot call execute method on same object.
  • Must be created and executed from the Main thread.
  • For tasks in parallel use multiple instances OR Executor.

Android ListView with EditText loses focus when the keyboard displays

Issue comes when you have ListView with  input capable fields (EditText)  that displays the soft keyboard on focus, the EditText loses its focus for the first time but the second time it works and gains focus.


To Solve this issue you need to add android:descendantFocusability=”beforeDescendants” in your ListView and android:windowSoftInputMode=”adjustPan” for your activity in the app Manifest.

<activity android:name=”com.yourActivity” android:windowSoftInputMode=”adjustPan”/>


and in ListView

<ListView android:id=”@+id/list” android:layout_width=”fill_parent” android:descendantFocusability=”beforeDescendants”
android:layout_height=”fill_parent” android:dividerHeight=”1.0dp”/>


You have to listen for the onFocusChange listener on the EditText and set a variable to keep track. So when the view get rendered again in your getView or getChildView method you can set the focus back to that EditText.



Android Fragment Example

A fragment is an independent component which can be used by an activity. A fragment encapsulate functionality so that it is easier to reuse within activities and layouts.

A fragment runs in the context of an activity but it has its own life cycle and typically its own user interface. It is also possible to define fragments with an user interface, i.e. headless fragments.

Fragment can be dynamically or statically added to an activity.

While working with fragment in android, one need to think for following

1) Communication between Fragment.

2) Communication between Fragment & Activity.

3) Life Cycle of Fragment.

Please wait to complete the post, sorry for inconvenience.

SurfaceView in Android

To create custom view in android, we extends View and implements onDraw() method. Extending view is fine for custom view but just imagine, what about if you want to draw something multiple times like animation. Android provides SurfaceView for animation purpose.

For View, the onDraw method is triggered by the system when it knows that the Canvas is safe to draw on. It can set things up for us before calling onDraw, and then clean up when it is done executing. Since we need to do drawing on our own schedule, we need a view class that will let us do this set up and clean up ourselves. That class is called SurfaceView.

Now as I said we are going to do drawing on our own schedule so there should be some intimation that the view has been created or view has been destroyed , so that accordingly we can do set up or  clean up task.

To intimate user program Android has provided callbacks method of SurfaceHolder.

Here SurfaceHolder plays a very important role as we know for View class, Canvas object is automatically get passed to onDraw() method.But for SurfaceView we need to get Canvas, once SurfaceView is created and draw on that canvas.

Here Going to provide simple example for Bouncing ball using surface view.

Create a surface view child class by extending it

public class GameBoard extends SurfaceView implements SurfaceHolder.Callback
private Paint p;
MyThread thread;
int x =16,y=16;
int dx = 5, dy = 5;
Bitmap bitmap = null;
public GameBoard(Context context)
p = new Paint();
thread = new MyThread(getHolder(), this);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
bitmap = bitmap.createScaledBitmap(bitmap, 10, 10, false);
// TODO Auto-generated constructor stub

public void surfaceChanged(SurfaceHolder holder, int format, int width,int height)

public void surfaceCreated(SurfaceHolder holder)

public void surfaceDestroyed(SurfaceHolder holder)
// TODO Auto-generated method stub
boolean retry = true;
retry = false;
}catch(Exception e)
public void update(Canvas canvas)
canvas.drawRect(0, 0, getWidth(), getHeight(), p);
/*Random r = new Random();
canvas.drawPoint(x,y, p);*/

canvas.drawBitmap(bitmap, x, y, p);
if(x >getWidth() - bitmap.getWidth() || x - bitmap.getWidth() < 0)
dx = -dx;
if(y > getHeight() - bitmap.getHeight() || y - bitmap.getHeight()< 0)
dy = -dy;

x +=dx;
y +=dy;


class MyThread extends Thread
SurfaceHolder holder;
GameBoard game;
boolean running = false;
public MyThread(SurfaceHolder holder,GameBoard game)
this.holder = holder; = game;
public void run()
Canvas canvas;
while (running)
canvas = null;
canvas = this.holder.lockCanvas(null);
if(canvas != null)
synchronized (this.holder)


public void setRunning(boolean b)
this.running = b;

Create an Activity say GameActivity with following content

public class GameActivity extends Activity
     protected void onCreate(Bundle savedInstanceState) 
            setContentView(new GameBoard(this));

Declare activity in manifest file and run the application.

notifyDataSetChanged() of adopter

While using ListView or Spinner we should take care how we are using notifyDataSetChanged() method.

By the android single thread model rule we can not access UI elements directly for another thread defined inside the activity.

Calling notifyDataSetChanged() in background thread (other than Main UI Thread) would cause as serious issue.

Either use  runOnUiThread() Or Handler (please refer post Handler Concept in Android).


private class ReceiverThread extends Thread {
public void run() { 
Activity_name.this.runOnUiThread(new Runnable() {

        public void run() {


Android Handler Concept

Handler Class in Android

All Android application starts a thread, which is  called MAIN UI Thread, All activities run inside that main thread. By the android single thread model rule we can not access UI elements (Toast, textview, progressbar status etc..) directly for another thread defined inside the activity.
So if we want to access UI elements by another thread then we will use  handlers.

The Handler class registers itself to a thread and provides a simple channel to other thread to send data or to communicate with this thread.

  • Handler class provides concurrency controls
  • Way to communicate and send data between the threads, without handling any extra concurrency.
  • The data which can be posted via the Handler class can be an instance of the Message or the Runnable class.

Suppose we are doing background activity and wants to update status message say Progress bar status title. Now progress bar is UI control, which is created in Main UI thread context, If we are trying to change status in another thread we will get Exception.

Best way to create subclass of Handler class inside Activity……….

// Define the Handler that receives messages from the thread and update the progress
privatefinalHandler handler = newHandler() {
 publicvoidhandleMessage(Message msg) {                           
 String aResponse = msg.getData().getString("message");
    if((null!= aResponse)) {
        "Server Response: "+aResponse,
           // ALERT MESSAGE
          "Not Got Response From Server.",


To post data to UI thread, we can do as below

         Message msgObj = handler.obtainMessage();
           Bundle b = newBundle();
           b.putString("message", msg);

Creating and reusing instances of Handlers

To use a handler you have to subclass it and override the handleMessage() method to process messages.

Your thread can post messages via the sendMessage(Message) method or via the sendEmptyMessage()method to the Handler object.

To process a Runnable you can use the post() method.

To avoid object creation you can also reuse the existing Handler object of your activity.

// Reuse existing handler if you don't 
// have to override the message processing
handler = getWindow().getDecorView().getHandler();

The View class allows you to post objects of type Runnable via the post() method.