Wednesday 31 July 2013

Display Image from Redirected URL in android

Today i am sharing one of my analysis for image load in android for redirected url.


Our Goal

We need to display image from URL that itself redirected to another URL.
Hit above URL on your browser, you will be redirected to actual URL like below.

Problem when using third party library like lazy loading

I have seen many library uses HttpURLConnection class to display image from URL.
Like “Universal Image Loader” , “Android-Query ” but these library can't handle URL redirection.

So, you can also manage URL redirection using HttpURLConnection class itself.
Please read below explanation to get more idea and What is best approach.
Now, We have below Http clients which are used to download image from specified URL.

  1. HttpURLConnection / HttpsURLConnection
3. DefaultHttpClient / HttpClient

  • This class does not support URL redirection automatically.
  • We need to write extra code to handle URL redirection.
  • You need to take care manually to close the connection of client.
  • It will handle HTTP to HTTPS URL redirection and vice versa.
  • It will handle only 1 URL redirection.

  1. HttpURLConnection

  • This class does not support URL redirection automatically.
  • We need to write some code by setting property setInstanceFollowRedirects = false to handle URL redirection properly.
  • You need to take care manually to close the connection of client.
  • It will handle HTTP to HTTPS URL redirection and vice versa.
  • This class handles up to 5 redirection.

  1. DefaultHttpClient / HttpClient

  • This class by default support URL redirection automatically.
  • We need not to write any code.
  • No need to close the connection.
  • It will handle HTTP to HTTPS URL redirection and vice versa.
  • This class handles greater than five redirection. I am not able to find maximum limit.

Conclusion

From above explanation, Winner is DefaultHttpClient. We must use DefaultHttpClient class. This class also handles Cookie forward mechanism very well if we use singleton pattern in cookie based authentication process in project.



Now below are code for above example.

Below is my main Activity class.


public class MainActivity extends Activity implements OnClickListener{

private static String TAG = MainActivity.class.getSimpleName();
private Button  btnAndroidHttpClient, btnDownloadHttpURLConnection, btnDownloadDefaultHttpClient;
private ImageView imgView;
private DefaultHttpClient client = null;
/**
* put your URL that itself redirected to another url that is the actual url to download image 
*/
private static final String URL_AndroidHttp = "http://graph.facebook.com/xxxxxxxxxxxx/picture/";
private static final String URL_HttpUrlConnection = "http://wired.ivvy.com/image/display/account/14/file/119806";
private static final String URL_DefaultHttp = "http://graph.facebook.com/xxxxxxxxxxxx/picture/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        btnAndroidHttpClient = (Button) findViewById(R.id.btnDownloadAndroidHttpClient);
        btnAndroidHttpClient.setOnClickListener(this);
        
        btnDownloadHttpURLConnection = (Button)findViewById(R.id.btnDownloadHttpURLConnection);
        btnDownloadHttpURLConnection.setOnClickListener(this);
        
        btnDownloadDefaultHttpClient = (Button) findViewById(R.id.btnDownloadDefaultHttpClient);
        btnDownloadDefaultHttpClient.setOnClickListener(this);
        
        imgView = (ImageView)findViewById(R.id.imgView);
        
    }

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnDownloadAndroidHttpClient:
if(Utils.isNetworkAvailable(MainActivity.this))
{
if(URL_AndroidHttp != null || !URL_AndroidHttp.equalsIgnoreCase(""))
{
new DownloadImageViaAndroidHttpClientTask().execute(URL_AndroidHttp,imgView);
}
else
{
Toast.makeText(MainActivity.this, "Please provide image url.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "Please check your internet connectivity.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnDownloadHttpURLConnection:
if(Utils.isNetworkAvailable(MainActivity.this))
{
if(URL_HttpUrlConnection != null || !URL_HttpUrlConnection.equalsIgnoreCase(""))
{
new DownloadImageViaHttpURLConnectionTask().execute(URL_HttpUrlConnection,imgView);
}
else
{
Toast.makeText(MainActivity.this, "Please provide image url.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "Please check your internet connectivity.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnDownloadDefaultHttpClient:
if(Utils.isNetworkAvailable(MainActivity.this))
{
if(URL_DefaultHttp != null || !URL_DefaultHttp.equalsIgnoreCase(""))
{
new DownloadImageViaDefaultHttpClientTask().execute(URL_DefaultHttp,imgView);
}
else
{
Toast.makeText(MainActivity.this, "Please provide image url.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(MainActivity.this, "Please check your internet connectivity.", Toast.LENGTH_SHORT).show();
}
break;
}
}

class DownloadImageViaAndroidHttpClientTask extends AsyncTask<Object, Void, Drawable>
{
private ImageView imgView;
private ProgressDialog dialog;
private AndroidHttpClient androidHttpClient =  AndroidHttpClient.newInstance("Android");
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait...");
dialog.show();
}


@Override
protected Drawable doInBackground(Object... params) {
imgView =  (ImageView) params[1];
try {
   HttpGet httpGet=new HttpGet((String)params[0]);
   HttpResponse httpResponse=androidHttpClient.execute(httpGet);
   androidHttpClient.close();
  
   final int statusCode = httpResponse.getStatusLine().getStatusCode();
   
   if (statusCode != HttpStatus.SC_OK) {
           Header[] headers = httpResponse.getHeaders("Location");
           
           if (headers != null && headers.length != 0) {
               String newUrl =  headers[headers.length - 1].getValue();
               
               AppLog.i(TAG, "newUrl=>"+newUrl);
               
               /**
                * call again with new URL to get image 
               */
               return downloadImage(newUrl);
           } else {
               return null;
           }
       }
}
catch (Exception ex)
{
AppLog.e(TAG, "DownloadImageTask doInBackground() Exception=>"+ex);
}
return null;
}
@Override
protected void onPostExecute(Drawable drawable) {
if (dialog.isShowing()) {
           dialog.dismiss();
       }
if(drawable != null)
{
imgView.setImageDrawable(drawable);
}
}
}
class DownloadImageViaHttpURLConnectionTask extends AsyncTask<Object, Void, Drawable>
{
private ImageView imgView;
private ProgressDialog dialog;
private HttpURLConnection con = null;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait...");
dialog.show();
}


@Override
protected Drawable doInBackground(Object... params) {
imgView =  (ImageView) params[1];
try {
con = (HttpURLConnection)(new URL((String)params[0]).openConnection());
   con.disconnect();
   con.setInstanceFollowRedirects(false);
   con.connect();
   final int responseCode = con.getResponseCode();
   
   AppLog.i(TAG, "responseCode=>"+responseCode);
   
   if (responseCode != HttpStatus.SC_OK) {
    String newUrl = con.getHeaderField("Location");;
           
               AppLog.i(TAG, "newUrl=>"+newUrl);
               
               return downloadImage(newUrl);
   }
}
catch (Exception ex)
{
AppLog.e(TAG, "DownloadImageTask doInBackground() Exception=>"+ex);
}
finally
{
if(con != null)
{
con.disconnect();
con= null;
}
}
return null;
}
@Override
protected void onPostExecute(Drawable drawable) {
if (dialog.isShowing()) {
           dialog.dismiss();
       }
if(drawable != null)
{
imgView.setImageDrawable(drawable);
}
}
}
class DownloadImageViaDefaultHttpClientTask extends AsyncTask<Object, Void, Drawable>
{
private ImageView imgView;
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait...");
dialog.show();
}


@Override
protected Drawable doInBackground(Object... params) {
imgView =  (ImageView) params[1];
try {
/**
* check for whether client os initialized or not. first time it is null, after first request 
* it will not create client. it will use existing initialized client to reduce memory consumption and improve performance.
* It will also used to cookie based implementation if we are using only one instance of client to redirect cookie to further request.  
*/
if(client==null)
       {
        createClient();
       }
        HttpParams httpParams = client.getParams();
        httpParams.setIntParameter("http.connection.timeout", 30000); // 30 SECONDS
        httpParams.setIntParameter("http.socket.timeout", 30000); // 30 SECONDS
   
   HttpGet httpGet=new HttpGet((String)params[0]);
   HttpResponse httpResponse=client.execute(httpGet);
   
   InputStream is=httpResponse.getEntity().getContent();
   Drawable d = Drawable.createFromStream(is, "src name");
   is.close();
   
   return d;
}
catch (Exception ex)
{
AppLog.e(TAG, "DownloadImageTask doInBackground() Exception=>"+ex);
}
return null;
}
@Override
protected void onPostExecute(Drawable drawable) {
if (dialog.isShowing()) {
           dialog.dismiss();
       }
if(drawable != null)
{
imgView.setImageDrawable(drawable);
}
}
}
private static Drawable downloadImage(String stringUrl) {
   URL url = null;
   HttpURLConnection connection = null;
   InputStream inputStream = null;
   
   try {
       url = new URL(stringUrl);
       connection = (HttpURLConnection) url.openConnection();
       connection.setUseCaches(true);
       inputStream = connection.getInputStream();
       
       
   Drawable d = Drawable.createFromStream(inputStream, "src name");
   inputStream.close();
   
       return d;
   } catch (Exception e) {
       AppLog.e(TAG, "Error while retrieving bitmap from " + e);
   } finally {
       if (connection != null) {
           connection.disconnect();
       }
   }
   
   return null;
}
public void createClient() {
   BasicHttpParams params = new BasicHttpParams();
   SchemeRegistry schemeRegistry = new SchemeRegistry();
   schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
   schemeRegistry.register( new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
   ClientConnectionManager ccm = new ThreadSafeClientConnManager( params, schemeRegistry);
   client = new DefaultHttpClient( ccm, params);
}
   
    
}


----------------------------------------------------------------------------------------------------------

public class AppLog {

private static boolean sFlagDebug= true;
private static boolean sFlagInfo= true;
private static boolean sFlagErr= true;
/**
* THis will print in Blue
* @param tag
* @param message
*/
public  static void d(String tag, String message){
if(sFlagDebug)
{
Log.d(tag,message);
}
}
/**
* This will print in Green
* @param tag
* @param message
*/
public  static void i(String tag, String message){
if(sFlagInfo)
{
Log.i(tag,message);
}
}
/**
* This will print in Error
* @param tag
* @param message
*/
public  static void e(String tag, String message){
if(sFlagErr)
{
Log.e(tag,message);
}
}
}


---------------------------------------------------------------------------------------------------------

public class Utils {

private static final String TAG = Utils.class.getSimpleName();


/**
* Check Internet connection flag.
* @param context
* @return
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}

}






Friday 4 January 2013

Loading Large Bitmaps Efficiently in android

Below is code for loading large image from url  in android mobile.

Below is code for loading large image from url  in android mobile.


public class ImageLoadActivity extends Activity {
ImageView mImageView;    
BitmapWorkTask mBitmapWorkTask;    
public static final String URL="http://www.iiccentre.org/image/Restaurants.jpg";
public static final String URL2="http://nssdc.gsfc.nasa.gov/planetary/image/cassini_titan_15.jpg";    
ProgressDialog mProgressDialog;    
public static int deviceHeight;
public static int deviceWidth;
DisplayMetrics dm;    

@Override   protected void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);      
setContentView(R.layout.activity_image_load);  
displayIntialize();  
mImageView=(ImageView)findViewById(R.id.img_loaded);    
mBitmapWorkTask=new BitmapWorkTask();  
mBitmapWorkTask.execute(URL,URL2);    

}          

private void displayIntialize(){      
dm= new DisplayMetrics();      
getWindowManager().getDefaultDisplay().getMetrics(dm);      
deviceHeight=dm.heightPixels;      
deviceWidth=dm.widthPixels;      

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {    // Inflate the menu; this adds items to the action bar if it is present.  
getMenuInflater().inflate(R.menu.activity_image_load, menu);  
return true;
}      

public class BitmapWorkTask extends AsyncTask{  

@Override  
protected void onPreExecute() {        
super.onPreExecute();  
mProgressDialog=new ProgressDialog(ImageLoadActivity.this, ProgressDialog.STYLE_SPINNER);  
mProgressDialog=ProgressDialog.show(ImageLoadActivity.this, "Please wait", "While image is loading");
mProgressDialog.show();  
}


protected void onPostExecute(Bitmap result) {  
// TODO Auto-generated method stub  
super.onPostExecute(result);        
if(result!=null){    
mImageView.setImageBitmap(result);  

}        
if(mProgressDialog!=null){  
mProgressDialog.dismiss();  
}  
}  
@Override    protected Bitmap doInBackground(String... params) {      
Bitmap mBitmap=null;  
int size=params.length;        
String urlIs=params[1];      
mBitmap=downloadBitmap(urlIs);      
return mBitmap;  
}            
}        


static Bitmap downloadBitmap(String url) {    
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");    
final HttpGet getRequest = new HttpGet(url);    
try {                
HttpResponse response = client.execute(getRequest);        
final int statusCode = response.getStatusLine().getStatusCode();        
if (statusCode != HttpStatus.SC_OK) {

Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;        
}                
final HttpEntity entity = response.getEntity();        
if (entity != null) {            
InputStream inputStream = null;            
try {                
inputStream = entity.getContent();                
BufferedInputStream bis = new BufferedInputStream(inputStream);                
bis.mark(1024 * 1024);                
final Bitmap bitmap = decodeSampledBitmapFromResource(bis,deviceWidth,deviceHeight);                
return bitmap;            
} finally {                
if (inputStream != null) {                    
inputStream.close();                
}                
entity.consumeContent();            
}        
}    
} catch (Exception e) {           // Could provide a more explicit error message for IOException or IllegalStateException        
getRequest.abort();        
//Log.w("ImageDownloader", "Error while retrieving bitmap from " + url, e.toString());                
Log.e("LOG_TAG", "Error while retrieving bitmap from" + url + e.toString());    
} finally {        
if (client != null) {            
client.close();        
}    
}       return null;

}      

public static Bitmap decodeSampledBitmapFromResource(BufferedInputStream inputStream,int reqWidth, int reqHeight) {       // First decode with
//inJustDecodeBounds=true
//to check dimensions    
final BitmapFactory.Options options = new BitmapFactory.Options();    
options.inJustDecodeBounds = true;    
BitmapFactory.decodeStream(inputStream, null, options);       // Calculate inSampleSize    
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);       // Decode bitmap with inSampleSize set    
options.inJustDecodeBounds = false;    
try {          
inputStream.reset();      
} catch (IOException e) {      
e.printStackTrace();  
}    


return BitmapFactory.decodeStream(inputStream, null, options);


}      

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {    // Raw height and width of image  
final int height = options.outHeight;  
final int width = options.outWidth;  
int inSampleSize = 1;  
if (height > reqHeight || width > reqWidth) {  
if (width > height) {    
inSampleSize = Math.round((float) height / (float) reqHeight);  
} else {    
inSampleSize = Math.round((float) width / (float) reqWidth);  
}  
}    return inSampleSize;
}
}

  }

}

}




 Here is output:

Friday 4 May 2012

Android Custom ListView with Seekbar ,TextView and Button


In this Example you can see how to use Custom Listview with Seekbar ,TextView and Button in android ListView.

Below is code for Activity which have ListView .



public class SeekBarExampleActivity extends ListActivity implements
  OnClickListener, OnTouchListener, OnSeekBarChangeListener {
 /** Called when the activity is first created. */
 ListView mListView;
 public static final int TOTAL_ITEM = 25;

 ImageView mImageView;
 ArrayList mSeekbarValue;

 ImageButton mImageButton;
 ListAdapter mListAdapter;
 TextView mTempTextview;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mListView = getListView();
  mSeekbarValue = new ArrayList(TOTAL_ITEM);
  for(int i=0;i adapter, View view,
    int position, long lon) {

  }
 };

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  Log.v("Log_tag", "LinearView is Click");
  /*LinearLayout mLinearlayout = (LinearLayout) v;
  if (mLinearlayout.getChildCount() > 0) {
   LinearLayout mtopLinearlayout = (LinearLayout) mLinearlayout
     .getChildAt(0);
   mTempTextview = (TextView) mtopLinearlayout.getChildAt(0);
   Log.v("Log_tag", "Tecview chnage");
  }*/

  return false;
 }

 @Override
 public void onProgressChanged(SeekBar seekBar, int progress,
   boolean fromUser) {
  int position = seekBar.getId();
  LinearLayout mLinearlayout=(LinearLayout) seekBar.getParent();
  if (mLinearlayout.getChildCount() > 0) {
   LinearLayout mtopLinearlayout = (LinearLayout) mLinearlayout
     .getChildAt(0);
   mTempTextview = (TextView) mtopLinearlayout.getChildAt(0);
   Log.v("Log_tag", "Tecview chnage");
  }
  //mSeekbarValue.add(position, progress);
  mSeekbarValue.set(position, progress);
  updateTextview(progress);
 }

 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {

 }

 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {

 }

 public void updateTextview(int paramValue) {
  if (mTempTextview != null) {
   mTempTextview.setText(String.valueOf(paramValue));
  }
 }
}



Here is My Row xml used for Custom ListView:

list_row_view.xml:





    

        

        

    



main.xml





    
    







Friday 20 April 2012

Android Dialog with Custom View

You can create Android Dialog with Below code .


public class DatePickerDialogActivity extends Activity {
 
     @Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
return super.onMenuItemSelected(featureId, item);
}

@Override
public boolean onMenuOpened(int featureId, Menu menu) {
// TODO Auto-generated method stub
return super.onMenuOpened(featureId, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}

@Override
public void onOptionsMenuClosed(Menu menu) {
// TODO Auto-generated method stub
super.onOptionsMenuClosed(menu);
}

public static final int DATE_PICKER_DIALOG=1;
public static final int MY_NEW_DIALOG=2;
public Calendar mCalendar;
int mYear;
int mMonth;
int mDay;
String mStringdate="04/04/2012";
String mStrdate1="2012-04-04";
public DatePickerDialog mDatePickerDialog;
public Dialog mDialog;
public Button mButton;
@Override
protected Dialog onCreateDialog(int id) {
switch(id){

case DATE_PICKER_DIALOG:
mDatePickerDialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
view.setOnClickListener(mDateSetListener);
mYear=year + 1;
mMonth=monthOfYear;
mDay=dayOfMonth;
Log.v("Log_tag", "Year is " + mYear +"month is "+ monthOfYear +"Day is "+ dayOfMonth);
}
}, mYear, mMonth, mDay);
mDatePickerDialog.setTitle(R.string.date_set_message);

return mDatePickerDialog;
case MY_NEW_DIALOG:
mSimpleDialog=new Dialog(this,R.style.CustomDialogTheme);
mSimpleDialog.setContentView(R.layout.dialog_layout);
TextView mTextView=(TextView)findViewById(R.id.msgtxt);
Button mBtnYes=(Button)mSimpleDialog.findViewById(R.id.btn_yes);
Button mBtnNo=(Button)mSimpleDialog.findViewById(R.id.btn_no);
mBtnYes.setOnClickListener(DialogButtonClickListener);
mBtnNo.setOnClickListener(DialogButtonClickListener);
mSimpleDialog.setCancelable(true);
mSimpleDialog.show();
return mSimpleDialog;

}
return null;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {

super.onPrepareDialog(id, dialog);
}

OnClickListener mDateSetListener =new OnClickListener() {

@Override
public void onClick(View v) {

Log.v("Log_tag", "Set Date is done");
}
};


OnClickListener mButtonClickListener =new OnClickListener() {

@Override
public void onClick(View v) {

if(mDatePickerOn){
showDialog(DATE_PICKER_DIALOG);
}else{
showDialog(MY_NEW_DIALOG);
}

Log.v("Log_tag", "Set Date is done");

}
};



Dialog  mSimpleDialog;
ToggleButton mToggleButton;
boolean mDatePickerOn=false;

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       // requestWindowFeature(Window.)
    super.onCreate(savedInstanceState);
        setContentView(R.layout.my_dialog);
        mCalendar=Calendar.getInstance();
        mYear=mCalendar.get(Calendar.YEAR);
        mMonth=mCalendar.get(Calendar.MONTH);
        mDay=mCalendar.get(Calendar.DAY_OF_MONTH);
        mButton=(Button)findViewById(R.id.btn_show_calander);
        mButton.setOnClickListener(mButtonClickListener);
        mToggleButton=(ToggleButton)findViewById(R.id.toogleButton);
        mToggleButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
      SimpleDateFormat mSimpleDateFormat=new SimpleDateFormat("EEE, MMM d, ''yy");
        SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy");
        try {
        //dateobj1= mSimpleDateFormat.parse(mStrdate1);
        Date dateObj = curFormater.parse(mStringdate);
             SimpleDateFormat postFormater = new SimpleDateFormat("EEE,MMMM dd, yyyy");
        String newDateStr = postFormater.format(dateObj);
        // date2=mSimpleDateFormat.format(dateobj1);
        //dateobj=mSimpleDateFormat.parse(mStringdate);
        //String dateis=mSimpleDateFormat.format(dateobj);
        Log.v("Log_tag", "Here we are with Date Function"+ newDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     
    }
 
    OnCheckedChangeListener mOnCheckedChangeListener=new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if(isChecked){
mDatePickerOn=true;
}else{
mDatePickerOn=false;
}
}
};
 
    View.OnClickListener DialogButtonClickListener=new View.OnClickListener() {

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_yes:
finish();
break;
case R.id.btn_no:
mSimpleDialog.dismiss();
break;
}

}
};
}



Here is xml Layout for Custom Dialog .
dialog_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dialog_bg"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="35dp"
        android:text="@string/hello"
        android:id="@+id/msgtxt"/>

    <LinearLayout
        android:id="@+id/btn_linerLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:gravity="center_horizontal"
        android:layout_marginTop="50dp">

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="125dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
         
            android:text="@string/btn_yes"
            android:layout_marginRight="5dp" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="125dp"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
         
            android:text="@string/btn_no"
            android:layout_marginLeft="5dp"/>
    </LinearLayout>

</LinearLayout>


Another xml layout that used in Example is below
  my_dialog.xml


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

    <Button
        android:id="@+id/btn_show_calander"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mButtonClickListener"
        android:text="@string/btn_text" />

    <ToggleButton
        android:id="@+id/toogleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton"
        android:textOn="@string/text_toggle_on"
        android:textOff="@string/text_toggle_off"
        android:gravity="center"/>

</LinearLayout>