Friday, 20 September 2013

Android Activity and ImageView Animation

Android Activity and ImageView Animation 

Hi Guys, Here is sample example for animation in android. It covers almost all types of possible animations.
The Animation Demo code was borrowed from code I found different sources  on internet. I can’t find reference to it anymore so if anyone happens to find anything similar please provide reference in the comments and I’ll link it up.






Download 
Happy Coddddding :)



Tuesday, 17 September 2013

Handle "unfortunately, App has Stopped" Or "force close " situations in android


Handle "unfortunately, App has Stopped" Or  "force close " situations in android.


Many time we forget to catch exception or some time unexpected exception occur. So we should handle in some way that our app should not show "Force Close Dialog" in such condition. 
So here is simple example. For this situations
Create Simple Class As MyExceptionHandler.

package com.example.crashhandledex;

import java.io.PrintWriter;
import java.io.StringWriter;

import android.content.Context;
import android.content.Intent;

public class MyExceptionHandler implements
              java.lang.Thread.UncaughtExceptionHandler {
       private final Context myContext;
       private final Class<?> myActivityClass;

       public MyExceptionHandler(Context context, Class<?> c) {

              myContext = context;
              myActivityClass = c;
       }

       public void uncaughtException(Thread thread, Throwable exception) {

              StringWriter stackTrace = new StringWriter();
              exception.printStackTrace(new PrintWriter(stackTrace));
              System.err.println(stackTrace);// You can use LogCat too
              Intent intent = new Intent(myContext, myActivityClass);
              String s = stackTrace.toString();
              // you can use this String to know what caused the exception and in
              // which Activity
              intent.putExtra("uncaughtException",
                           "Exception is: " + stackTrace.toString());
              intent.putExtra("stacktrace", s);
              myContext.startActivity(intent);
              // for restarting the Activity
              // Process.killProcess();
              System.exit(0);
       }
}


AND IN YOUR ACTIVITY  USED AS 


public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
                           MainActivity.class));

              final Button button1 = (Button) findViewById(R.id.button1);
              button1.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {
                           //Example Crash, Here App will restart instead of showing force close dialog
                           int i = Integer.valueOf("SJDkal");
                           button1.setText(i);

                     }
              });

       }
}



Happy Codddddin :)

Best Practices for Exception Handling and Logging

Best Practices for Exception Handling and Logging

The Nature of Exceptions


Broadly speaking, there are three different situations that cause exceptions to be thrown:
Exceptions due to programming errors: In this category, exceptions are generated due to programming errors (e.g., NullPointerException and IllegalArgumentException). The client code usually cannot do anything about programming errors.
Exceptions due to client code errors: Client code attempts something not allowed by the API, and thereby violates its contract. The client can take some alternative course of action, if there is useful information provided in the exception. For example: an exception is thrown while parsing an XML document that is not well-formed. The exception contains useful information about the location in the XML document that causes the problem. The client can use this information to take recovery steps.
Exceptions due to resource failures: Exceptions that get generated when resources fail. For example: the system runs out of memory or a network connection fails. The client's response to resource failures is context-driven. The client can retry the operation after some time or just log the resource failure and bring the application to a halt.

Best Practices for Exception Handling
1. When deciding on checked exceptions vs. unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs?"
If the client can take some alternate action to recover from the exception, make it a checked exception. If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.
Moreover, prefer unchecked exceptions for all programming errors: unchecked exceptions have the benefit of not forcing the client API to explicitly deal with them. They propagate to where you want to catch them, or they go all the way out and get reported. The Java API has many unchecked exceptions, such as NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.
2. Preserve encapsulation.
Never let implementation-specific checked exceptions escalate to the higher layers. For example, do not propagate SQLException from data access code to the business objects layer. Business objects layer do not need to know about SQLException. You have two options:
1) Convert SQLException into another checked exception, if the client code is expected to recuperate from the exception.
2) Convert SQLException into an unchecked exception, if the client code cannot do anything about it.
3. Try not to create new custom exceptions if they do not have useful information for client code.
4. Do not use your base exception class for "unkown" exception cases.
actually a follow-up from the first advice above. If you model your own exception hierarchy, you will typically have an exception base class (eg. MyAPIException) and several specific ones that inherit from that one (eg. MyAPIPathNotFoundException). Now it is tempting to throw the base exception class whenever you don't really know what else to throw, because the error case is not clear or very seldom. It's probably a Fault and thus you would start mixing it with your Contingency exception class hierarchy, which is obviously a bad thing.
One of the advantages of an exception base class is that the client has the choice to catch the base class if he does not want to handle the specific cases (although that's probably not the most robust code). But if that exception is also thrown in faulty situations, the client can no longer make a distinction between one-of-those-contingency-cases and all-those-unexcpected-fault-cases. And it obviously brakes your explicit exception design: there are those specific error cases you state and let the client know about, but then there is this generic exception thrown where the client cannot know what it means and is not able to handle it as a consequence.
5. When wrapping or logging exceptions, add your specific data to the message. 
6. Don't throw exceptions in methods that are likely to be used for the exception handling itself.
This follows straight from the two previous advices: if you throw or log exceptions, you are typically in exception handling code, because you wrap a lower-level exception. If you add dynamic data to your exceptions, you might access methods from the underlying API. But if those methods throw exceptions, your code becomes ugly.
7. Document exceptions.

Best Practices for Using Exceptions
1. Always clean up after yourself
If you are using resources like database connections or network connections, make sure you clean them up. If the API you are invoking uses only unchecked exceptions, you should still clean up resources after use, with try - finally blocks.
2. Never use exceptions for flow control
Generating stack traces is expensive and the value of a stack trace is in debugging. In a flow-control situation, the stack trace would be ignored, since the client just wants to know how to proceed.
3. Do not suppress or ignore exceptions
When a method from an API throws a checked exception, it is trying to tell you that you should take some counter action. If the checked exception does not make sense to you, do not hesitate to convert it into an unchecked exception and throw it again, but do not ignore it by catching it with {} and then continue as if nothing had happened.
4. Do not catch top-level exceptions
5. Log exceptions just once
Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. So just log it once.

Logging
When your code encounters an exception, it must either handle it, let it bubble up, wrap it, or log it. If your code can programmatically handle an exception (e.g., retry in the case of a network failure), then it should. If it can't, it should generally either let it bubble up (for unchecked exceptions) or wrap it (for checked exceptions). However, it is ultimately going to be someone's responsibility to log the fact that this exception occurred if nobody in the calling stack was able to handle it programmatically. This code should typically live as high in the execution stack as it can. Some examples are the onMessage() method of an MDB, and the main() method of a class. Once you catch the exception, you should log it appropriately.
The JDK has a java.util.logging package built in, although the Log4j project from Apache continues to be a commonly-used alternative. Apache also offers the Commons Logging project, which acts as a thin layer that allows you to swap out different logging implementations underneath in a pluggable fashion. All of these logging frameworks that I've mentioned have basically equivalent levels:
1) FATAL: Should be used in extreme cases, where immediate attention is needed. This level can be useful to trigger a support engineer's pager.
2) ERROR: Indicates a bug, or a general error condition, but not necessarily one that brings the system to a halt. This level can be useful to trigger email to an alerts list, where it can be filed as a bug by a support engineer.
3) WARN: Not necessarily a bug, but something someone will probably want to know about. If someone is reading a log file, they will typically want to see any warnings that arise.
4) INFO: Used for basic, high-level diagnostic information. Most often good to stick immediately before and after relatively long-running sections of code to answer the question "What is the app doing?" Messages at this level should avoid being very chatty.
5) DEBUG: Used for low-level debugging assistance.
If you are using commons-logging or Log4j, watch out for a common gotcha. The error, warn, info, and debug methods are overloaded with one version that takes only a message parameter, and one that also takes a Throwable as the second parameter. Make sure that if you are trying to log the fact that an exception was thrown, you pass both a message and the exception. If you call the version that accepts a single parameter, and pass it the exception, it hides the stack trace of the exception.
When calling log.debug(), it's good practice to always surround the call with a check for log.isDebugEnabled(). This is purely for optimization. It's simply a good habit to get into, and once you do it for a few days, it will just become automatic.
Do not use System.out or System.err. You should always use a logger. Loggers are extremely configurable and flexible, and each appender can decide which level of severity it wants to report/act on, on a package-by-package basis. Printing a message to System.out is just sloppy and generally unforgivable.

Wednesday, 11 September 2013

Design Patterns for Highly Successful Mobile Apps

Six Design Patterns for Highly Successful Mobile Apps


For years, building web apps has required server-side code and a database. That was great for browsers, but then mobile apps came along and changed everything. Today apps appear on any number of devices, including browsers, and the same app needs to run seamlessly on multiple devices. 
Apps are fundamentally different from their web application counterparts. Traditional web applications run on a monolithic, server-side stack, which delivers content in the form of web pages. For the most part, browsers simply display this content. When a user interacts with a web page, requests are sent to the server for additional content.
In contrast, mobile apps run on a client. Instead of deploying program logic to a back-end server, the logic is housed on the client. This fundamentally changes the dynamic between client and server, making the client no longer merely a display mechanism.
Additional considerations for the development of mobile apps come in the form of the resource constraints imposed by mobile platforms. Mobile apps need to be as lightweight and agile as possible. In other words, you simply wouldn’t run a LAMP stack on an iPhone.
Another challenge for Mobile app developers is dealing with the cumulative traffic that can be generated by even a modest number of clients.  For example, many mobile apps connect to the cloud regularly throughout the day to perform authentication, upload and download data, or to perform geo-queries against a user's current location.  This can result in what amounts to a distributed denial of service attack (DDoS) against an underpowered service architecture.
An added consideration is the data-warehousing infrastructure necessary to deal with all the information being collected. For mobile apps to deliver cutting edge, rich interaction on mobile devices they must be supported by equally rich services and data storage mechanisms.
Enter the cloud.
By hosting rich services in the cloud, client apps can deliver the interactivity that users desire while maintaining a lightweight footprint. With the emergence of mobile PaaS (Platform-as-a-Service) solutions, the days of app developers having to find another developer with a different skill set to help or spending half or more of their development time building services, may soon be gone.
Everything from storing users, groups, roles, single sign-on authentication, social interactions, feeds, queries, connections between users and objects can be provided by a PaaS solution. This leaves the developers to focus on writing cool apps and not on the server code.
So what services do mobile developers need?  We think these 6 patterns are a great start.
1. User Management
Who are you? Who do you know who has the same app? Who do you know outside the app?
One of the most fundamental needs of app developers is user management - straightforward ways to handle users’ (customers’) access control, groups, roles, subscriptions, upgrades, reminders, and so on across multiple devices and apps.
Internet ID and social connectivity also relate to user management. Developers are being rewarded for building identity into apps - from showing pictures of users to bridging to other identities like Twitter and Facebook.
2. Connected & Social Interactions
Who do you follow? Who are your friends? Who will you invite?
In-app and extra-app interactions are all core to mobile apps and devices. For example, an app might bridge out to do a notification or invite a user to join.
In the past, this would have required a generous helping of custom server-side code. Development platforms that provide activity streams, linked profiles, and so on facilitate the development of connected and social interactions.
3. Activity Streams
Activity streams are a kind of static query on moving data. They take connections and turn them into activities, adding a social layer to data and opening up real-time collaboration.
Popular activities vary depending on context but activity streams enable activities such as status updates, check-ins, comments, or other broadcasts to fellow users off of any object or off of multiple objects.
4. Sync Content & Data
Apps need to be able to share data with users, and import, export, and sync application data with third-party applications. The ability to sync data across devices allows developers to create apps, which provide consistency of experience. Think about your favorite “shopping list” or “to do” app that syncs across your laptop, your iPad, and your mobile phone!
5. Location, location, location
Geo-location or Location-Based Service (LBS) apps attach real-world locations to mobile devices and are one of the fastest growing types of apps. You can establish when and where you receive information, track your peers and friends in real-time by location and proximity, find and provide information about things and friends near you.
6. Analytics
App developers need to be able to monitor usage and analyze data to drive both app functionality and business intelligence. Important services include real-time activity processing, behavior tracking and targeting.
Analytics on individual apps are powerful and useful for decision-making about functionality, usage, troubleshooting problems, and so on.  But it’s a game changer when the insights from aggregated data - possibly from multiple apps a developer has created - allow developers to turn what they’re doing into a business and evolve it over time.

by Rod Simpson



Wednesday, 4 September 2013

ImageView Animation in Android


ImageView Animation in Android 


Animation for imageview is very simple here is simplest example.


// Step1 : create the  RotateAnimation object
RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
// Step 2:  Set the Animation properties
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);

// Step 3: Start animating the image
 image.startAnimation(anim);

// Later. if you want to  stop the animation
// image.setAnimation(null);


you can download 
another example from here for better understanding :)
http://nineoldandroids.com/

Download

Happy Coddddding :)

Tuesday, 3 September 2013


10 hard-earned lessons of a lifetime in IT



Here are 10 things I wish I knew as an IT newbie.

1. They’re called 'fundamentals' for a reason
Technology is in constant flux, and success in IT means keeping on top of new developments as they evolve. But it's not only unnecessary to learn everything -- it's impossible.
Concentrate on the fundamentals. These will serve you much better than detailed knowledge of the internal workings of transient hardware and software.
In the early 1980s, I knew almost everything about how the Apple IIe worked, to the point of rewriting the low-level disk drivers to make them more efficient. Then the IBM PC came out. I enjoyed it, of course, but the reusable knowledge in this experience would have been more easily obtained from a textbook on operating system principles.
2. Marketing is not evil
Well, it doesn't have to be evil.
When you communicate the value of your work to employers, clients, or coworkers, you are doing the work of marketing. And it's not just for folks looking to open their own business. If you ever pitch a project or feature idea in a meeting, an understanding of marketing will be far more valuable than fluency in any programming language. It also helps when you realize that your résumé is actually a sales brochure and the product is you.
All of my writing skills were improved significantly, and quickly, by studying marketing and copywriting. And I've learned that knowing how to be persuasive upfront when it counts is far more valuable than being right in hindsight.
3. Learn the difference between opportunity and distraction
Opportunities are everywhere, but so are distractions. To an IT pro, technology can be very seductive, especially new technology -- or obscure problems.
Learning about the business you're working with allows you to see past the tech into the heart of what is necessary for your company, enabling you to add unexpected value. Re-inventing object-oriented computing while trying to cram a 2D CAD system into a Commodore 64 may seem like an opportunity to demonstrate your brilliance, but it's better to make sure your hard work is on something meaningful. Believe me, I now know.
Honing your understanding of technology's place in business also helps you see opportunities outside of your job, which is how your career really grows.
4. If you don't have a contract, you don't have a job
Even the best employers or clients have occasional payment hiccups. Trust, but verify -- in writing -- and don't start work without a deposit.
I once agreed to do a rewrite of an application from Basic to Assembly language in three months and asked a friend to help me. After delivery, the client was delighted with the results, but didn't pay us. A contract lawyer might have cost a couple of hundred dollars. More important, knowing in advance that the client was unwilling to sign a contract would have prevented a $25,000 loss.
There are few lessons harder learned than those that touch your livelihood.
5. MBAs know what's best -- for themselves, not for you
You'd like to think that anyone with a higher-education degree wearing a suit knows what's best. They do know what's best -- for them, not for you.
Don't let your success depend on empty suits, empty promises, or snake-oil salesmen. It's far too easy to wait: to be selected, to be noticed, to be promoted, to be appreciated. We’re trained from childhood to trust authority figures, respect elders, and believe that we're all in this together. But when your 90-hour workweek architecting the product, coding the kernel, and managing a staff of 25 developers suddenly evaporates because the fraud of a CEO found out you got wise to his routine sabotaging of your team's work, you learn real quick that business can get dirty.
6. Recognize the patterns before they bite you
Many "executive" decisions are made accidentally, or for bizarre reasons that have nothing to do with the problem, the solution, logic, technology, economics, or you. Don't take it personally, but if you detect a consistent pattern of poor leadership, questionable choices, or shortchanging IT input, then get out of there quickly.
Especially when a company rarely has a fallback plan despite your rumblings, then it's high time to have a Plan B of your own.
Oh, and when the owner of a startup keeps asking for more and assures you "we'll take care of you," this does not mean what you think it means.
7. Relational database normalization will teach you clarity and economy of thought
I'm not kidding. This topic gets short shrift in most college courses, but is a foundational design philosophy for structuring information, recognizing patterns (especially missing elements), and identifying dependencies.
The point is not to know how to normalize poorly structured database tables (which is what most college exercises dwell on); the point is to learn to quickly identify entities and relationships, and to think and design in minimal, nonredundant structures.
Functional dependency is the Tai Chi Chuan of software development. Master it. Stumbling upon and studying the work of Edgar Codd and Chris Date was the single most important turning point in my career as a software designer.
8. Get your head out of tech (to be truly inspired)
Inspiration and insight can come from anywhere. And if there's anything I've learned about technology, it's that you have to turn off the machines sometimes to truly understand them.
For example, writing science fiction helped me realize something hiding in plain sight about writing software: You imagine something that doesn't exist, then work backward from first principles to figure out how it might be possible.
Here, reading is essential. And not just tech news and nerd magazines. Business, finance, fiction, non-fiction, biographies -- your mind always expands when you expand your sphere of knowledge.
Plus, reading (and writing) helps you learn how to organize your work, present ideas, express thoughts clearly and succinctly, and observe and improve yourself in the workplace.
9. Let your eyes wander
Don't let yourself get pigeonholed or buried for more than a few months on a project; otherwise, when you resurface, the tech world will have changed.
The IT field is vast. Look outside your current job every once in a while to stave off boredom and ossification.
Early on, I became extremely bored writing the same kinds of applications over and over. Fortunately, I happened onMarvin Minsky's work and realized there was far more to programming than what I had been doing; I haven't been bored since.
Then, after five years working with one very interesting technology, I came up for air and found all the cool kids were talking about some newfangled thing called the Internet. Good thing I looked up.
10. IT is more about people than you think
Tools come and go, but people stick. In fact, contrary to what you might think, people are the most important aspect of IT work.
The thrill of writing code to solve a problem is addictive, but short-lived. The satisfaction from making life better for the people who use your software is much more powerful and lasts far longer.
Do yourself a favor and get over yourself. Appreciate the work of others out loud. Share credit generously. Listen thoughtfully -- to colleagues, managers, especially clients and customers.
I like gadgets and problem-solving and inventing things, of course. It was the essential kernel that drew me to this field, but I was surprised to find out that I like people even more.
By Steven A. Lowe

Monday, 2 September 2013

The Most Common Communication Mistakes Project Managers Make


The Most Common Communication Mistakes Project Managers Make 
share by shahbaz shaikh
Don’t get me wrong! A lot of project managers are doing a fantastic job of organizing and delivering their projects and keeping their clients happy. But it’s probably still true, that the majority of PMs are stronger with the harder skills of creating plans and reports than with the softer skills of communicating and motivating people. The below mistakes are the ones I the most often see project managers make when it comes to the softer communication skills.

·   Speaking more than you listen
A big part of a project managers’ job is concerned with assigning work, resolving issues, coordinating activities and assessing progress. The pressure is on and they are busy getting everything done. In this process they often give orders and tell people what to do. Very few take the time to really connect with the individual; ask for input, listen, and check how their message has been understood. You shouldn’t just tell people what to do as that doesn’t empower or motivate anyone. Just think about the times when you have been on the receiving end of that. Instead, take the time to ask people how they are, what they make of the message you just gave them, what they worry about and how they feel the team could work smarter. Really listen to what they say. It will provide you lots of valuable information and strengthen the trust between you.

·   Communicating with the client in writing instead of face-to-face
Again and again I see project managers emailing their clients instead of speaking to them in person. Written communication is great for short messages without complexity, but should not be used simply because it’s more convenient or saves you having a difficult conversation. Many misunderstandings and disagreements are born because we don’t take the time to identify common ground with our clients and prepare them for what is coming.

·   Face-to-face communication is a must in situations where:
o You want to build trust and make sure you’re on the same page
o The stakes are high, for instance regarding an issue or a significant risk
o You sense disagreement or conflict
o You want to ask for advice or feedback
o You want to win your client’s support for an important matter
o You want to understand your client’s point of view and how to best communicate with them

·   Saying ‘yes’ when you really mean ‘no’
Many people feel pressurized to saying ‘yes’ when put on the spot and asked directly if they can deliver something– even if they haven’t had the time to properly assess what they’re saying yes to. This relates to anything from small promises of “I will send it to you straight away” to “yes, I’ll see if we can incorporate that extra feature into the next iteration!” Overpromising is a classic and very serious mistake which doesn’t serve anyone. The problem surfaces later when you realize that you can’t keep your promise and that it’s starting to affect your reputation. Instead, take time out by saying “Can I get back to you on that?” You can also offer alternatives by saying: “I can’t do A, but I can do B”.

·   Relying too heavily on the weekly status meeting
For many project managers the weekly status meeting is the primary way of communicating with the team. In this meeting the project manager enquires about progress and receives an update from each team member so that they can gauge how far the project has progressed. This type of status meeting is great for the project manager, but not necessarily for the team member who may feel it’s a waste of time. Make the status meeting short and focused on progress since last meeting and on blockages which you can help resolve. To engage each team member however, it’s essential that you set up one-2-one meetings where it’s all about them and their needs; not about what you need. Ask them what they most enjoy doing, what type of support they need from you and how you can help them work more effectively.

·   Providing too much and too detailed information
It is often assumed that the more detail we provide our bosses and stakeholders the better. But the truth is that we need to give them just the right amount of information and no more. When you send out a weekly status report or conduct a steering committee meeting, don’t overload the recipient with unnecessary detail. Highlight the good progress you have made, summarize risks and issues and how you are addressing them, and provide an update on the budget. Make it very clear if you need their input and decision on anything or if you’re merely providing an update. Detailed information should only be provided where they are in need of making a decision on something. Keep it simple and don’t use jargon. Your aim is to engage your audience and for this you need to communicate at their level of understanding. To download a free copy of a steering committee presentation, request access to the resources page here.

·   Failing to ask for feedback

It is human nature to avoid that which we feel is unpleasant – and that includes asking for feedback. You may fear that people will tell you something negative and therefore refrain from asking in the first place. But by not asking you’re doing yourself a big disfavor. Firstly you’re much better off knowing what people think about you and the project than not knowing; when you know you can do something about it and use the feedback to your advantage. In addition, you are likely to receive feedback about something which you’re doing really well and which you were not aware of. It will lift your spirits and enable you to build on your strengths. Why not try it? Ask people you respect; a) what you should stop doing b) what you should start doing and c) what you should continue to do. Nice and simple!


Alert Dialog Android

Aler Dialog Android 






Hi friends today we will se how to create simple alert dialog in Android.
Its very simple , we can create alert dailog with 1 , 2 or 3 buttons
here is sample code.


package com.example.dailogboxexample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
       Context context;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);

              context = this;

              Button button = (Button) findViewById(R.id.button1);
              button.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           new AlertDialog.Builder(context)
                                         .setTitle("Alert Box ")
                                         .setMessage(
                                                       "Please check your Internet conection, and try again?")
                                         .setPositiveButton("Ok",
                                                       new DialogInterface.OnClickListener() {
                                                              public void onClick(DialogInterface dialog,
                                                                           int which) {

                                                                     Toast.makeText(context, "Ok Pressed", 1)
                                                                                  .show();
                                                              }
                                                       }).show();
                     }
              });

              Button button2 = (Button) findViewById(R.id.button2);
              button2.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           new AlertDialog.Builder(context)
                                         .setTitle("Alert Box ")
                                         .setMessage(
                                                       "Please check your Internet conection, and try again?")
                                         .setPositiveButton("Yes",
                                                       new DialogInterface.OnClickListener() {
                                                              public void onClick(DialogInterface dialog,
                                                                           int which) {
                                                                     Toast.makeText(context, "Yes Pressed",
                                                                                  1).show();
                                                              }
                                                       })
                                         .setNegativeButton("No",
                                                       new DialogInterface.OnClickListener() {
                                                              public void onClick(DialogInterface dialog,
                                                                           int which) {
                                                                     // do nothing
                                                                     Toast.makeText(context, "No Pressed", 1)
                                                                                  .show();
                                                              }
                                                       }).show();
                     }
              });

              Button button3 = (Button) findViewById(R.id.button3);
              button3.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           new AlertDialog.Builder(context)
                                         .setTitle("Alert Box ")
                                         .setMessage(
                                                       "Please check your Internet conection, and try again?")
                                         .setPositiveButton("Yes",
                                                       new DialogInterface.OnClickListener() {
                                                              public void onClick(DialogInterface dialog,
                                                                           int which) {
                                                                     Toast.makeText(context, "Yes Pressed",
                                                                                  1).show();
                                                              }
                                                       })
                                         .setNegativeButton("No",
                                                       new DialogInterface.OnClickListener() {
                                                              public void onClick(DialogInterface dialog,
                                                                           int which) {
                                                                     // do nothing
                                                                     Toast.makeText(context, "No Pressed", 1)
                                                                                  .show();
                                                              }
                                                       })
                                         .setNeutralButton("Cancel",
                                                       new DialogInterface.OnClickListener() {
                                                              public void onClick(DialogInterface dialog,
                                                                           int which) {
                                                                     // do nothing
                                                                     Toast.makeText(context,
                                                                                  "Cancel Pressed", 1).show();
                                                              }
                                                       }).show();

                     }
              });

       }
}


and here is xml file for buttons layout.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_centerVertical="true"
        android:text="3 Button Alert" />

    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button3"
        android:layout_alignLeft="@+id/button1"
        android:text="2 Button Alert " />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button2"
        android:layout_alignParentLeft="true"
        android:text="1 Button Alert" />

</RelativeLayout>

simple :)
Happy Codding :)