Friday 3 May 2013

PDF Download Example

private class GetPDF_Download extends AsyncTask<String, Boolean, Boolean> {
        private ProgressDialog mProgressDialog = null;
        private String PDF_URL = "";
        private String SDCARD_PDF_PATH = "";
       
        public GetPDF_Download(String PDF_URL) {
            this.PDF_URL=PDF_URL;
            this.SDCARD_PDF_PATH = Constant.PDF_FOLDER + File.separator + Products_Detail_Constant.PRODUCTS_DETAIL_VALUE.PDFNAME_VALUE.get(Selected_Product_Index).toString();
        }
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(context, "",Constant.DOWNLOAD_MESSAGE);;
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);
           
            mProgressDialog.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {

                    if (!(GetPDF_Download.this.isCancelled())) {
                        GetPDF_Download.this.cancel(true);
                    }
                }
            });
            super.onPreExecute();
        }
        protected Boolean doInBackground(String... Param) {
            try {
                    File PDFDirectory = new File(Constant.PDF_FOLDER);
                    if (!PDFDirectory.exists()) {
                        PDFDirectory.mkdir();
                    }
   
                    InputStream mInputStream = Utility.GetConnectionInputStream(PDF_URL);
                    FileOutputStream mFileOutputStream = new FileOutputStream(SDCARD_PDF_PATH);
                    byte data[] = new byte[1024];
                    int count = 0;
                    // Log.v("Total", "total = "+ mInputStream.available());
                    // int progress = mInputStream.available()/100;
                    while ((count = mInputStream.read(data)) != -1) {
                        mFileOutputStream.write(data, 0, count);
                    }
                   
                    mFileOutputStream.flush();
                    mFileOutputStream.close();
                    mInputStream.close();
   
                    return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        protected void onPostExecute(Boolean result) {
            mProgressDialog.dismiss();
            mProgressDialog=null;
            if (result){
                    PDF_VIEW(SDCARD_PDF_PATH);
            }else{
                    if(new File(SDCARD_PDF_PATH).exists()){
                        new File(SDCARD_PDF_PATH).delete();
                    }
                     Toast.makeText(context,Constant.PDF_NOT_DOWNLOAD_MESSAGE, Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(result);
        }
    }
   
    private void PDF_VIEW(String pdf_path){
        try{
                Uri PATH = Uri.fromFile(new File(pdf_path));
                Intent mIntent = new Intent(Intent.ACTION_VIEW);
                mIntent.setDataAndType(PATH, "application/pdf");
                context.startActivity(mIntent);
        }catch (Exception e) {
                 e.printStackTrace();
                 Toast.makeText(context,Constant.PDF_APPLICATION_NOT_MESSAGE,Toast.LENGTH_SHORT).show();
        }
    }
}
==============================================
btnPDF = (Button)convertView.findViewById(R.id.btn_pdf);
                btnPDF.setTypeface(Utility.setDINPro_Regular_Font(context.getResources()));
                btnPDF.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        if(Utility.MemoryCardCheck()){
                            String WEB_PDF_URL=Constant.PDF_URL + String.format("p%s",Products_Data_Constant.PRODUCTS_DATA_VALUE.PRODUCT_ID_VALUE.get(Selected_Product_Index)) + File.separator + Products_Detail_Constant.PRODUCTS_DETAIL_VALUE.PDFNAME_VALUE.get(Selected_Product_Index);
                            String SDCARD_PDF_PATH = Constant.PDF_FOLDER + File.separator + Products_Detail_Constant.PRODUCTS_DETAIL_VALUE.PDFNAME_VALUE.get(Selected_Product_Index).toString();
                            if(new File(SDCARD_PDF_PATH).exists()){
                                PDF_VIEW(SDCARD_PDF_PATH);
                            }
                            else{
                                if(Utility.CheckNetworkMessage(context)){
                                    GetPDF_Download mGetPDF_Download=new GetPDF_Download(WEB_PDF_URL);
                                    mGetPDF_Download.execute("PDF Downloading");   
                                }
                            }
                        }
                    }
                });
================================================

=========
constants
=========
     public static final File SDCARD_PATH=Environment.getExternalStorageDirectory();
     public static final String CAMERA_FOLDER="Folder Name";
     public static final String PDF_FOLDER=SDCARD_PATH.getAbsolutePath()+ File.separator + "YOUR_PDF";
     public static final String DOWNLOAD_MESSAGE="Downloading...";
     public static final String PDF_NOT_DOWNLOAD_MESSAGE="PDF File Not Download.";
     public static final String PDF_APPLICATION_NOT_MESSAGE="PDF Viewer Application Not Found in Your Device";

===========================================
Utility.java
===========================================
package com.hella.common;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Debug;
import android.os.Environment;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hella.adlight.R;
import com.hella.xmlread.Alert_Constant;
import com.hella.xmlread.Alert_Constant.ALERT_TAG;
/**
 *@author  DRCSystems
 *@version 1.1
 *@class   Utility
 *@date    5/5/2012
 *Utility class use for global use
 */
public class Utility {
   
    /**This method use for check Network Connectivity
     * @param
     * @return  boolean
     */
    public static boolean CheckNetwork(Context context) {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
            if(netinfo!=null && netinfo.isConnected()==true){
                return true;
            }
            else{
                return false;         
            }
    }
   
    /**This method use for check Network Connectivity Message
     * @param
     * @return  boolean
     */
    public static boolean CheckNetworkMessage(Context context) {
        SharedPreferences msharePreferencesRead = context.getSharedPreferences(Constant.SHAREDPREFERENCES, Context.MODE_WORLD_READABLE);
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
            if(netinfo!=null && netinfo.isConnected()==true){
                  return true;
            }
            else{
//                 Utility.Show_Short_Toast(new WeakReference<Context>(context.getApplicationContext()),Alert_Constant.ALERT_VALUE.REQUIRESINTERNET_VALUE);
                 Utility.Show_Short_Toast(new WeakReference<Context>(context.getApplicationContext()),msharePreferencesRead.getString(ALERT_TAG.REQUIRESINTERNET_TAG, "REQUUIRESINTER NOT FOUND"));
                 return false;
            }
    }
   
    /**This method use for GetConnection InputStream to Server
     * @param
     * @return InputStream
     */
    public static InputStream GetConnectionInputStream(String strUrl) {
        HttpClient mHttpClient =null;
        HttpGet mHttpGet = null;
        HttpResponse mHttpResponse=null;
        HttpEntity mHttpEntity = null;
        try {
                //This is the default apacheconnection.
                mHttpClient = new DefaultHttpClient();
              
                //Pathe of serverside
                mHttpGet = new HttpGet(strUrl);
              
                //get the valu from the saerverside as response.
                mHttpResponse = mHttpClient.execute(mHttpGet);
                mHttpEntity = mHttpResponse.getEntity();
                if(mHttpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                    return mHttpEntity.getContent();
                }
                else{
                     return null;
                }
          }
          catch (Exception e) {
             e.printStackTrace();
             return null;
          }
    }
   
    /**This method use for PostConnection InputStream to Server
     * @param
     * @return InputStream
     */
    public static InputStream PostConnectionInputStream(String strUrl) {
            HttpClient mHttpClient =null;
            HttpPost mHttpPost = null;
            HttpResponse mHttpResponse=null;
            HttpEntity mHttpEntity = null;
            try {
                    //This is the default apacheconnection.
                    mHttpClient = new DefaultHttpClient();
                  
                    //Pathe of serverside
                    mHttpPost = new HttpPost(strUrl);
                  
                    //get the valu from the saerverside as response.
                    mHttpResponse = mHttpClient.execute(mHttpPost);
                    mHttpEntity = mHttpResponse.getEntity();
                    if(mHttpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                        return mHttpEntity.getContent();
                    }
                    else{
                         return null;
                    }
              }
              catch (Exception e) {
                 e.printStackTrace();
                 return null;
              }
    }
   
    /**This method use for InputStream To String Convert
     * @param
     * @return  String
     */
    public static String InputStreamToString(InputStream mInputStream){
        //convert response in to the string.
        try {
              if(mInputStream!=null){
                  String strLine = "";
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                    return mStringBuilder.toString();          
              }
              else{
                  return "";
              }
           }
           catch (Exception e) {
                   e.printStackTrace();
                   return "";
          }
        finally{
            closeSilently(mInputStream);
        }
    }
   
   /**This method use to Check Memory Card
    * @return Boolean
    */ 
    public static Boolean MemoryCardCheck() {  
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }
        else{
            return false;
        }
    }
   
    /**This function use for get Bitmap from Sdcard
      * @param ImagePath for string image path
      * @param context Application or current activity reference
      *@param Width for image width set
      *@param Height for image height set
      * @return Bitmap
      */
   public static Bitmap DecodeFileGetBitmap(String ImagePath,Context context,int Width,int Height){
           try{       
                   File mFile=new File(ImagePath);
                 if(mFile.exists()){
                    BitmapFactory.Options mBitmapFactoryOptions = new BitmapFactory.Options();
                    mBitmapFactoryOptions.inJustDecodeBounds=true;
                    BitmapFactory.decodeFile(ImagePath, mBitmapFactoryOptions);
                    int SampleSize = calculateInSampleSize(mBitmapFactoryOptions,Width,Height);
                    mBitmapFactoryOptions.inJustDecodeBounds = false;
//                   mBitmapFactoryOptions.inPurgeable = true;
                    mBitmapFactoryOptions.inScaled=false;
                        mBitmapFactoryOptions.inSampleSize=SampleSize;
                        return BitmapFactory.decodeStream(new FileInputStream(mFile),null,mBitmapFactoryOptions);  
                 }
                   else{
                            Log.w(Constant.TAG,"ImagePath Not Found.");
                            return  BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
                   }
                

              
               }
           catch (Exception e) {
                    e.printStackTrace();
                    return  BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
           }
   }
  
   /**This function use for calculateSampleSize
      * @param
      * @return int
      */ 
   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) {

       // Calculate ratios of height and width to requested height and width
       final int heightRatio = Math.round((float) height / (float) reqHeight);
       final int widthRatio = Math.round((float) width / (float) reqWidth);

       // Choose the smallest ratio as inSampleSize value, this will guarantee
       // a final image with both dimensions larger than or equal to the
       // requested height and width.
       inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
   }

   return inSampleSize;
}
   
     /**This function use for get Bitmap from id
      * @param image_id for image resource id
      * @param context current activity reference
      *@param Width for image width set
      *@param Height for image height set
      * @return Bitmap
      */
   public static Bitmap DecodeResourceGetBitmap(int image_id,Context context,int Width,int Height){
      try{                     
             BitmapFactory.Options mBitmapFactoryOptions = new BitmapFactory.Options();
             mBitmapFactoryOptions.inJustDecodeBounds=true;
             BitmapFactory.decodeResource(context.getResources(),image_id,mBitmapFactoryOptions);
             int SampleSize = calculateInSampleSize(mBitmapFactoryOptions,Width,Height);
             // Decode the image file into a Bitmap sized to fill the View
                mBitmapFactoryOptions.inJustDecodeBounds = false;
//             mBitmapFactoryOptions.inPurgeable = true;
             mBitmapFactoryOptions.inScaled=false;
             mBitmapFactoryOptions.inSampleSize=SampleSize;
             return BitmapFactory.decodeResource(context.getResources(),image_id,mBitmapFactoryOptions);
        }
        catch (Exception e) {
                 e.printStackTrace();
                 return  BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
        }
    }
   
    /**This function use for big image to make small
     *@param
     *@param Width for image width set
     *@param Height for image height set
     *@return Bitmap
     * */
    private static Bitmap Image_Shrink(Bitmap BitmapPreScale,Context context,int Width,int Height){
      
        if(BitmapPreScale!=null){
            try{
                    int oldWidth = BitmapPreScale.getWidth();
                    int oldHeight = BitmapPreScale.getHeight();
                    int newWidth = Width;  // whatever your desired width and height are
                    int newHeight = Height;
   
                    // calculate the scale
                    float scaleWidth = ((float) newWidth) / oldWidth;
                    float scaleHeight = ((float) newHeight) / oldHeight;
   
                    // create a matrix for the manipulation
                    Matrix matrix = new Matrix();
                    // resize the bit map
                    matrix.postScale(scaleWidth, scaleHeight);
   
                    // recreate the new Bitmap
                    return Bitmap.createBitmap(BitmapPreScale, 0, 0,  oldWidth, oldHeight, matrix, true);
            }
            catch (Exception e) {
                e.printStackTrace();
                return BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
            }
            finally{
                if(BitmapPreScale!=null){
                    if(!BitmapPreScale.isRecycled()){
                        BitmapPreScale.recycle();
                        BitmapPreScale=null;
                        Utility.GC();
                    }
                }
              
            }  
        }
        else{
            return null;
        }
      
    }
 
  /**This function use for check Native free memory and store bitmap
   * @param
   * @return boolean
   * */
  private static boolean CheckBitmapFitsInMemory(long bmpwidth,long bmpheight,int bmpdensity ){
      long reqsize=bmpwidth*bmpheight*bmpdensity;
      long allocNativeHeap = Debug.getNativeHeapAllocatedSize();


      long heapPad=(long) Math.max(4*1024*1024,Runtime.getRuntime().maxMemory()*0.1);
      if ((reqsize + allocNativeHeap + heapPad) >= Runtime.getRuntime().maxMemory())
      {
          return false;
      }
      return true;
  }

   
    /**This method for setDINPro Black Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Black_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Black.ttf");
    }
   
    /**This method for setDINPro Bold Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Bold_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Bold.ttf");
    }
   
    /**This method for setArial Font set
     * @return Typeface
     */
    public static Typeface setArial_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/arial.ttf");
    }
   
    /**This method for setDINPro Light Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Light_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Light.ttf");
    }
   
    /**This method for setDINPro Medium Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Medium_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Medium.ttf");
    }
   
    /**This method for setDINPro Regular Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Regular_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Regular.ttf");
    }
   
    /**This method for Show Short Toast Message
     * @param
     * @return void
     */
    public static void Show_Short_Toast(WeakReference<Context> weakReference,final CharSequence Message){
        Toast.makeText(weakReference.get(), Message, Toast.LENGTH_SHORT).show();
    }
   
    /**This method for Show Long Toast Message
     * @param
     * @return void
     */
    public static void Show_Long_Toast(WeakReference<Context> context,final CharSequence Message){
        Toast.makeText(context.get(), Message, Toast.LENGTH_LONG).show();
    }
   
    /**This method for Show Short Custom Toast Message
     * @param
     * @return void
     */
    public static void Show_Short_Custom_Toast(WeakReference<Context> context,final CharSequence Message,final int gravity,final int x,final int y,int bg_resourceid){
            TextView txtmessage=new TextView(context.get());
            txtmessage.setBackgroundResource(bg_resourceid);
            txtmessage.setPadding(5, 2, 5, 2);
            txtmessage.setGravity(Gravity.CENTER|Gravity.CENTER_VERTICAL);
            txtmessage.setTextColor(Color.BLACK);
            txtmessage.setText(Message);
          
            Toast mToast = new Toast(context.get());
            mToast.setGravity(gravity, x, y);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.setView(txtmessage);
            mToast.show();  
    }
   
    /**This method for Text write in Bold and Normal style
     * @param
     * @return Spanned
     */
    public static Spanned Bold_Normal_Text(final String bold,final String divider,final String normal) {
         return Html.fromHtml(String.format("<b>%s</b>%s%s", bold,divider,normal).toString());
    }
   
    /**This method for Text write in Normal and Bold style
     * @param
     * @return Spanned
     */
    public static Spanned Normal_Bold_Text(final String normal,final String divider,final String bold) {
         return Html.fromHtml(String.format("%s%s<b>%s</b>", normal,divider,bold).toString());
    }
   
    /**This method for Alert_Dialog
     * @param context refrence of application
     * @param Message stings of message display
     * @return void
     */
    public static void Alert_Default_Dialog(Context context,String Message){
           AlertDialog.Builder mAlertDialogBuilder = new AlertDialog.Builder(context);
//            // set title
//           mAlertDialogBuilder.setTitle("Your Title");
           // set dialog message
                mAlertDialogBuilder
                .setMessage(Message)
                .setCancelable(false)
                .setPositiveButton(Constant.ALERTDIALOG_BUTTON.OK,new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            dialog.cancel();
                        }
                  });

                // create alert dialog
                AlertDialog mAlertDialog = mAlertDialogBuilder.create();
                mAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                mAlertDialog.setCancelable(false);
                mAlertDialog.setCanceledOnTouchOutside(false);
                // show it
                mAlertDialog.show();
    }
   
    /**This method for Alert_Dialog Custom
     * @param context refrence of application
     * @param Message stings of message display
     * @return void
     */
    private static AlertDialog mAlertDialog = null;
    public static void Alert_Custom_Dialog(Context context,String Title_Message){
           AlertDialog.Builder mAlertDialogBuilder = new AlertDialog.Builder(context);
//            // set title
//           mAlertDialogBuilder.setTitle("Your Title");
           // set dialog message
                LinearLayout mLinearLayout=new LinearLayout(context);
                mLinearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                mLinearLayout.setMinimumWidth((int)Constant.getDIP(context, 200));
                mLinearLayout.setPadding(10,10, 10,10);
                mLinearLayout.setGravity(Gravity.CENTER);
                mLinearLayout.setOrientation(LinearLayout.VERTICAL);
              
                TextView txt_Title_Message = new TextView(context);
                txt_Title_Message.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,1.0f));
                txt_Title_Message.setTextSize(22);
                txt_Title_Message.setTextColor(Color.WHITE);
                txt_Title_Message.setMinLines(2);
//                txt_Title_Message.setMinWidth(600);
//                txt_Title_Message.setMinHeight(100);
                txt_Title_Message.setText(Title_Message);
                txt_Title_Message.setGravity(Gravity.CENTER);
                mLinearLayout.addView(txt_Title_Message);
              
                Button btn_Ok = new Button(context);
                btn_Ok.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                btn_Ok.setText(Constant.ALERTDIALOG_BUTTON.OK);
                btn_Ok.setMinWidth(320);
                btn_Ok.setMinHeight(40);
                btn_Ok.setGravity(Gravity.CENTER);
                btn_Ok.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mAlertDialog.dismiss();
                        mAlertDialog=null;
                    }
                });
                mLinearLayout.addView(btn_Ok);

                mAlertDialogBuilder.setView(mLinearLayout);
//                .setMessage(Title_Message)
//                .setPositiveButton(Constant.ALERTDIALOG_BUTTON.OK,new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog,int id) {
//                            dialog.cancel();
//                        }
//                  });

                // create alert dialog
                mAlertDialog = mAlertDialogBuilder.create();
                mAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                mAlertDialog.setCancelable(false);
                mAlertDialog.setCanceledOnTouchOutside(false);
                // show it
                mAlertDialog.show();
    }
   
   
//  /**This method for Alert_Message_Dialog
//  * @param context refrence of application
//  * @param Message stings of message display
//  * @return void
//     */
//    public static void Alert_Message_Dialog(Context context,String Message,Boolean center){
//        final Dialog mDialog = new Dialog(context);
//        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        mDialog.setContentView(R.layout.xalert_cust);
//        mDialog.setCancelable(false);
//        mDialog.setCanceledOnTouchOutside(false);
//        mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
//      
////        final LinearLayout llay_dialog=(LinearLayout)mDialog.findViewById(R.id.llay_dialog);
//      
//        if(center){          
//            final TextView txt_alert_message = (TextView)mDialog.findViewById(R.id.txt_alert_message);
//            txt_alert_message.setMovementMethod(new ScrollingMovementMethod());
//            txt_alert_message.setGravity(Gravity.CENTER | Gravity.CLIP_VERTICAL);
//            txt_alert_message.setText(Message);
//        }
//        else{
//            final TextView txt_alert_message = (TextView)mDialog.findViewById(R.id.txt_alert_message);
//            txt_alert_message.setMovementMethod(new ScrollingMovementMethod());
//            txt_alert_message.setText(Message);
//        }
//
//        final Button btn_alert_ok = (Button)mDialog.findViewById(R.id.btn_alert_ok);
//        btn_alert_ok.setText(Constant.ALERTDIALOG_BUTTON.OK);
//        btn_alert_ok.setOnClickListener(new OnClickListener() {
//          
//            public void onClick(View v) {
//                mDialog.dismiss();
//                Utility.GC();
//            }
//        });
//      
//        mDialog.show();
//      
////        llay_dialog.post(new Runnable() {
////            @Override
////            public void run() {
////                llay_dialog.setAnimation(AnimationUtils.loadAnimation(context, R.anim.alert_dialog));
////            }
////        });
//    }
      
    /**This method for get Bitmap from assets
     * @param context for application refrence
     * @param FileName string for image assets path
     * @return Bitmap
     */
    public static Bitmap getBitmapFromAssets(Context context,final String FileName)
    {     
            try{
                return BitmapFactory.decodeStream(context.getAssets().open(FileName));
            }
            catch (Exception e) {
                e.printStackTrace();
                return null;
            }
    }
   
    /**This method for get Bitmap from assets
     * @param context for application refrence
     * @param FileName string for image assets path
     * @param Width for imageview width
     * @param Height for imageiview height
     * @return Bitmap
     */
    public static Bitmap getBitmapFromAssets(Context context,final String FileName,int Width,int Height)
    {
        try{
                 BitmapFactory.Options mBitmapFactoryOptions = new BitmapFactory.Options();
                 mBitmapFactoryOptions.inJustDecodeBounds=true;
                 BitmapFactory.decodeStream(context.getAssets().open(FileName),null, mBitmapFactoryOptions);
                   int SampleSize = calculateInSampleSize(mBitmapFactoryOptions,Width, Height);
                   mBitmapFactoryOptions.inJustDecodeBounds = false;
//               mBitmapFactoryOptions.inPurgeable = true;
                   mBitmapFactoryOptions.inScaled=false;
                   mBitmapFactoryOptions.inSampleSize=SampleSize;
                   return BitmapFactory.decodeStream(context.getAssets().open(FileName),null, mBitmapFactoryOptions);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
   
    /**This method for String from assets
     * @param context for application refrence
     * @param FileName string for image assets path
     * @return String
     */
    public static String getStringFromAssets(Context context,final String FileName)
    {
        try{
                return InputStreamToString(context.getAssets().open(FileName));
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
   
    /**This method for close object
     * @return void
     */
    public static void closeSilently(final Closeable c) {
        if (c == null)
            return;
        try {
              c.close();
        } catch (Throwable t) {
            // do nothing
        }
    }
   
    /**This method for Garbase collection
     * @return void
     */
    public static void GC(){
        System.runFinalization();
        System.gc();
    }
   
   

}
package com.hella.common;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Debug;
import android.os.Environment;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hella.adlight.R;
import com.hella.xmlread.Alert_Constant;
import com.hella.xmlread.Alert_Constant.ALERT_TAG;
/**
 *@author  DRCSystems
 *@version 1.1
 *@class   Utility
 *@date    5/5/2012
 *Utility class use for global use
 */
public class Utility {
   
    /**This method use for check Network Connectivity
     * @param
     * @return  boolean
     */
    public static boolean CheckNetwork(Context context) {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
            if(netinfo!=null && netinfo.isConnected()==true){
                return true;
            }
            else{
                return false;         
            }
    }
   
    /**This method use for check Network Connectivity Message
     * @param
     * @return  boolean
     */
    public static boolean CheckNetworkMessage(Context context) {
        SharedPreferences msharePreferencesRead = context.getSharedPreferences(Constant.SHAREDPREFERENCES, Context.MODE_WORLD_READABLE);
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
            if(netinfo!=null && netinfo.isConnected()==true){
                  return true;
            }
            else{
//                 Utility.Show_Short_Toast(new WeakReference<Context>(context.getApplicationContext()),Alert_Constant.ALERT_VALUE.REQUIRESINTERNET_VALUE);
                 Utility.Show_Short_Toast(new WeakReference<Context>(context.getApplicationContext()),msharePreferencesRead.getString(ALERT_TAG.REQUIRESINTERNET_TAG, "REQUUIRESINTER NOT FOUND"));
                 return false;
            }
    }
   
    /**This method use for GetConnection InputStream to Server
     * @param
     * @return InputStream
     */
    public static InputStream GetConnectionInputStream(String strUrl) {
        HttpClient mHttpClient =null;
        HttpGet mHttpGet = null;
        HttpResponse mHttpResponse=null;
        HttpEntity mHttpEntity = null;
        try {
                //This is the default apacheconnection.
                mHttpClient = new DefaultHttpClient();
              
                //Pathe of serverside
                mHttpGet = new HttpGet(strUrl);
              
                //get the valu from the saerverside as response.
                mHttpResponse = mHttpClient.execute(mHttpGet);
                mHttpEntity = mHttpResponse.getEntity();
                if(mHttpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                    return mHttpEntity.getContent();
                }
                else{
                     return null;
                }
          }
          catch (Exception e) {
             e.printStackTrace();
             return null;
          }
    }
   
    /**This method use for PostConnection InputStream to Server
     * @param
     * @return InputStream
     */
    public static InputStream PostConnectionInputStream(String strUrl) {
            HttpClient mHttpClient =null;
            HttpPost mHttpPost = null;
            HttpResponse mHttpResponse=null;
            HttpEntity mHttpEntity = null;
            try {
                    //This is the default apacheconnection.
                    mHttpClient = new DefaultHttpClient();
                  
                    //Pathe of serverside
                    mHttpPost = new HttpPost(strUrl);
                  
                    //get the valu from the saerverside as response.
                    mHttpResponse = mHttpClient.execute(mHttpPost);
                    mHttpEntity = mHttpResponse.getEntity();
                    if(mHttpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                        return mHttpEntity.getContent();
                    }
                    else{
                         return null;
                    }
              }
              catch (Exception e) {
                 e.printStackTrace();
                 return null;
              }
    }
   
    /**This method use for InputStream To String Convert
     * @param
     * @return  String
     */
    public static String InputStreamToString(InputStream mInputStream){
        //convert response in to the string.
        try {
              if(mInputStream!=null){
                  String strLine = "";
                  BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,HTTP.UTF_8), 8);
                  StringBuilder mStringBuilder = new StringBuilder();
                    while((strLine = mBufferedReader.readLine()) != null) {
                      mStringBuilder.append(strLine + "\n");
                  }
                    return mStringBuilder.toString();          
              }
              else{
                  return "";
              }
           }
           catch (Exception e) {
                   e.printStackTrace();
                   return "";
          }
        finally{
            closeSilently(mInputStream);
        }
    }
   
   /**This method use to Check Memory Card
    * @return Boolean
    */ 
    public static Boolean MemoryCardCheck() {  
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            return true;
        }
        else{
            return false;
        }
    }
   
    /**This function use for get Bitmap from Sdcard
      * @param ImagePath for string image path
      * @param context Application or current activity reference
      *@param Width for image width set
      *@param Height for image height set
      * @return Bitmap
      */
   public static Bitmap DecodeFileGetBitmap(String ImagePath,Context context,int Width,int Height){
           try{       
                   File mFile=new File(ImagePath);
                 if(mFile.exists()){
                    BitmapFactory.Options mBitmapFactoryOptions = new BitmapFactory.Options();
                    mBitmapFactoryOptions.inJustDecodeBounds=true;
                    BitmapFactory.decodeFile(ImagePath, mBitmapFactoryOptions);
                    int SampleSize = calculateInSampleSize(mBitmapFactoryOptions,Width,Height);
                    mBitmapFactoryOptions.inJustDecodeBounds = false;
//                   mBitmapFactoryOptions.inPurgeable = true;
                    mBitmapFactoryOptions.inScaled=false;
                        mBitmapFactoryOptions.inSampleSize=SampleSize;
                        return BitmapFactory.decodeStream(new FileInputStream(mFile),null,mBitmapFactoryOptions);  
                 }
                   else{
                            Log.w(Constant.TAG,"ImagePath Not Found.");
                            return  BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
                   }
                

              
               }
           catch (Exception e) {
                    e.printStackTrace();
                    return  BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
           }
   }
  
   /**This function use for calculateSampleSize
      * @param
      * @return int
      */ 
   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) {

       // Calculate ratios of height and width to requested height and width
       final int heightRatio = Math.round((float) height / (float) reqHeight);
       final int widthRatio = Math.round((float) width / (float) reqWidth);

       // Choose the smallest ratio as inSampleSize value, this will guarantee
       // a final image with both dimensions larger than or equal to the
       // requested height and width.
       inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
   }

   return inSampleSize;
}
   
     /**This function use for get Bitmap from id
      * @param image_id for image resource id
      * @param context current activity reference
      *@param Width for image width set
      *@param Height for image height set
      * @return Bitmap
      */
   public static Bitmap DecodeResourceGetBitmap(int image_id,Context context,int Width,int Height){
      try{                     
             BitmapFactory.Options mBitmapFactoryOptions = new BitmapFactory.Options();
             mBitmapFactoryOptions.inJustDecodeBounds=true;
             BitmapFactory.decodeResource(context.getResources(),image_id,mBitmapFactoryOptions);
             int SampleSize = calculateInSampleSize(mBitmapFactoryOptions,Width,Height);
             // Decode the image file into a Bitmap sized to fill the View
                mBitmapFactoryOptions.inJustDecodeBounds = false;
//             mBitmapFactoryOptions.inPurgeable = true;
             mBitmapFactoryOptions.inScaled=false;
             mBitmapFactoryOptions.inSampleSize=SampleSize;
             return BitmapFactory.decodeResource(context.getResources(),image_id,mBitmapFactoryOptions);
        }
        catch (Exception e) {
                 e.printStackTrace();
                 return  BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
        }
    }
   
    /**This function use for big image to make small
     *@param
     *@param Width for image width set
     *@param Height for image height set
     *@return Bitmap
     * */
    private static Bitmap Image_Shrink(Bitmap BitmapPreScale,Context context,int Width,int Height){
      
        if(BitmapPreScale!=null){
            try{
                    int oldWidth = BitmapPreScale.getWidth();
                    int oldHeight = BitmapPreScale.getHeight();
                    int newWidth = Width;  // whatever your desired width and height are
                    int newHeight = Height;
   
                    // calculate the scale
                    float scaleWidth = ((float) newWidth) / oldWidth;
                    float scaleHeight = ((float) newHeight) / oldHeight;
   
                    // create a matrix for the manipulation
                    Matrix matrix = new Matrix();
                    // resize the bit map
                    matrix.postScale(scaleWidth, scaleHeight);
   
                    // recreate the new Bitmap
                    return Bitmap.createBitmap(BitmapPreScale, 0, 0,  oldWidth, oldHeight, matrix, true);
            }
            catch (Exception e) {
                e.printStackTrace();
                return BitmapFactory.decodeResource(context.getResources(), R.drawable.img_loading);
            }
            finally{
                if(BitmapPreScale!=null){
                    if(!BitmapPreScale.isRecycled()){
                        BitmapPreScale.recycle();
                        BitmapPreScale=null;
                        Utility.GC();
                    }
                }
              
            }  
        }
        else{
            return null;
        }
      
    }
 
  /**This function use for check Native free memory and store bitmap
   * @param
   * @return boolean
   * */
  private static boolean CheckBitmapFitsInMemory(long bmpwidth,long bmpheight,int bmpdensity ){
      long reqsize=bmpwidth*bmpheight*bmpdensity;
      long allocNativeHeap = Debug.getNativeHeapAllocatedSize();


      long heapPad=(long) Math.max(4*1024*1024,Runtime.getRuntime().maxMemory()*0.1);
      if ((reqsize + allocNativeHeap + heapPad) >= Runtime.getRuntime().maxMemory())
      {
          return false;
      }
      return true;
  }

   
    /**This method for setDINPro Black Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Black_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Black.ttf");
    }
   
    /**This method for setDINPro Bold Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Bold_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Bold.ttf");
    }
   
    /**This method for setArial Font set
     * @return Typeface
     */
    public static Typeface setArial_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/arial.ttf");
    }
   
    /**This method for setDINPro Light Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Light_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Light.ttf");
    }
   
    /**This method for setDINPro Medium Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Medium_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Medium.ttf");
    }
   
    /**This method for setDINPro Regular Font set
     * @param
     * @return Typeface
     */
    public static Typeface setDINPro_Regular_Font(final Resources mResources){
        return Typeface.createFromAsset(mResources.getAssets(),"fonts/DINPro_Regular.ttf");
    }
   
    /**This method for Show Short Toast Message
     * @param
     * @return void
     */
    public static void Show_Short_Toast(WeakReference<Context> weakReference,final CharSequence Message){
        Toast.makeText(weakReference.get(), Message, Toast.LENGTH_SHORT).show();
    }
   
    /**This method for Show Long Toast Message
     * @param
     * @return void
     */
    public static void Show_Long_Toast(WeakReference<Context> context,final CharSequence Message){
        Toast.makeText(context.get(), Message, Toast.LENGTH_LONG).show();
    }
   
    /**This method for Show Short Custom Toast Message
     * @param
     * @return void
     */
    public static void Show_Short_Custom_Toast(WeakReference<Context> context,final CharSequence Message,final int gravity,final int x,final int y,int bg_resourceid){
            TextView txtmessage=new TextView(context.get());
            txtmessage.setBackgroundResource(bg_resourceid);
            txtmessage.setPadding(5, 2, 5, 2);
            txtmessage.setGravity(Gravity.CENTER|Gravity.CENTER_VERTICAL);
            txtmessage.setTextColor(Color.BLACK);
            txtmessage.setText(Message);
          
            Toast mToast = new Toast(context.get());
            mToast.setGravity(gravity, x, y);
            mToast.setDuration(Toast.LENGTH_SHORT);
            mToast.setView(txtmessage);
            mToast.show();  
    }
   
    /**This method for Text write in Bold and Normal style
     * @param
     * @return Spanned
     */
    public static Spanned Bold_Normal_Text(final String bold,final String divider,final String normal) {
         return Html.fromHtml(String.format("<b>%s</b>%s%s", bold,divider,normal).toString());
    }
   
    /**This method for Text write in Normal and Bold style
     * @param
     * @return Spanned
     */
    public static Spanned Normal_Bold_Text(final String normal,final String divider,final String bold) {
         return Html.fromHtml(String.format("%s%s<b>%s</b>", normal,divider,bold).toString());
    }
   
    /**This method for Alert_Dialog
     * @param context refrence of application
     * @param Message stings of message display
     * @return void
     */
    public static void Alert_Default_Dialog(Context context,String Message){
           AlertDialog.Builder mAlertDialogBuilder = new AlertDialog.Builder(context);
//            // set title
//           mAlertDialogBuilder.setTitle("Your Title");
           // set dialog message
                mAlertDialogBuilder
                .setMessage(Message)
                .setCancelable(false)
                .setPositiveButton(Constant.ALERTDIALOG_BUTTON.OK,new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int id) {
                            dialog.cancel();
                        }
                  });

                // create alert dialog
                AlertDialog mAlertDialog = mAlertDialogBuilder.create();
                mAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                mAlertDialog.setCancelable(false);
                mAlertDialog.setCanceledOnTouchOutside(false);
                // show it
                mAlertDialog.show();
    }
   
    /**This method for Alert_Dialog Custom
     * @param context refrence of application
     * @param Message stings of message display
     * @return void
     */
    private static AlertDialog mAlertDialog = null;
    public static void Alert_Custom_Dialog(Context context,String Title_Message){
           AlertDialog.Builder mAlertDialogBuilder = new AlertDialog.Builder(context);
//            // set title
//           mAlertDialogBuilder.setTitle("Your Title");
           // set dialog message
                LinearLayout mLinearLayout=new LinearLayout(context);
                mLinearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                mLinearLayout.setMinimumWidth((int)Constant.getDIP(context, 200));
                mLinearLayout.setPadding(10,10, 10,10);
                mLinearLayout.setGravity(Gravity.CENTER);
                mLinearLayout.setOrientation(LinearLayout.VERTICAL);
              
                TextView txt_Title_Message = new TextView(context);
                txt_Title_Message.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,1.0f));
                txt_Title_Message.setTextSize(22);
                txt_Title_Message.setTextColor(Color.WHITE);
                txt_Title_Message.setMinLines(2);
//                txt_Title_Message.setMinWidth(600);
//                txt_Title_Message.setMinHeight(100);
                txt_Title_Message.setText(Title_Message);
                txt_Title_Message.setGravity(Gravity.CENTER);
                mLinearLayout.addView(txt_Title_Message);
              
                Button btn_Ok = new Button(context);
                btn_Ok.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
                btn_Ok.setText(Constant.ALERTDIALOG_BUTTON.OK);
                btn_Ok.setMinWidth(320);
                btn_Ok.setMinHeight(40);
                btn_Ok.setGravity(Gravity.CENTER);
                btn_Ok.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mAlertDialog.dismiss();
                        mAlertDialog=null;
                    }
                });
                mLinearLayout.addView(btn_Ok);

                mAlertDialogBuilder.setView(mLinearLayout);
//                .setMessage(Title_Message)
//                .setPositiveButton(Constant.ALERTDIALOG_BUTTON.OK,new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog,int id) {
//                            dialog.cancel();
//                        }
//                  });

                // create alert dialog
                mAlertDialog = mAlertDialogBuilder.create();
                mAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                mAlertDialog.setCancelable(false);
                mAlertDialog.setCanceledOnTouchOutside(false);
                // show it
                mAlertDialog.show();
    }
   
   
//  /**This method for Alert_Message_Dialog
//  * @param context refrence of application
//  * @param Message stings of message display
//  * @return void
//     */
//    public static void Alert_Message_Dialog(Context context,String Message,Boolean center){
//        final Dialog mDialog = new Dialog(context);
//        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        mDialog.setContentView(R.layout.xalert_cust);
//        mDialog.setCancelable(false);
//        mDialog.setCanceledOnTouchOutside(false);
//        mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
//      
////        final LinearLayout llay_dialog=(LinearLayout)mDialog.findViewById(R.id.llay_dialog);
//      
//        if(center){          
//            final TextView txt_alert_message = (TextView)mDialog.findViewById(R.id.txt_alert_message);
//            txt_alert_message.setMovementMethod(new ScrollingMovementMethod());
//            txt_alert_message.setGravity(Gravity.CENTER | Gravity.CLIP_VERTICAL);
//            txt_alert_message.setText(Message);
//        }
//        else{
//            final TextView txt_alert_message = (TextView)mDialog.findViewById(R.id.txt_alert_message);
//            txt_alert_message.setMovementMethod(new ScrollingMovementMethod());
//            txt_alert_message.setText(Message);
//        }
//
//        final Button btn_alert_ok = (Button)mDialog.findViewById(R.id.btn_alert_ok);
//        btn_alert_ok.setText(Constant.ALERTDIALOG_BUTTON.OK);
//        btn_alert_ok.setOnClickListener(new OnClickListener() {
//          
//            public void onClick(View v) {
//                mDialog.dismiss();
//                Utility.GC();
//            }
//        });
//      
//        mDialog.show();
//      
////        llay_dialog.post(new Runnable() {
////            @Override
////            public void run() {
////                llay_dialog.setAnimation(AnimationUtils.loadAnimation(context, R.anim.alert_dialog));
////            }
////        });
//    }
      
    /**This method for get Bitmap from assets
     * @param context for application refrence
     * @param FileName string for image assets path
     * @return Bitmap
     */
    public static Bitmap getBitmapFromAssets(Context context,final String FileName)
    {     
            try{
                return BitmapFactory.decodeStream(context.getAssets().open(FileName));
            }
            catch (Exception e) {
                e.printStackTrace();
                return null;
            }
    }
   
    /**This method for get Bitmap from assets
     * @param context for application refrence
     * @param FileName string for image assets path
     * @param Width for imageview width
     * @param Height for imageiview height
     * @return Bitmap
     */
    public static Bitmap getBitmapFromAssets(Context context,final String FileName,int Width,int Height)
    {
        try{
                 BitmapFactory.Options mBitmapFactoryOptions = new BitmapFactory.Options();
                 mBitmapFactoryOptions.inJustDecodeBounds=true;
                 BitmapFactory.decodeStream(context.getAssets().open(FileName),null, mBitmapFactoryOptions);
                   int SampleSize = calculateInSampleSize(mBitmapFactoryOptions,Width, Height);
                   mBitmapFactoryOptions.inJustDecodeBounds = false;
//               mBitmapFactoryOptions.inPurgeable = true;
                   mBitmapFactoryOptions.inScaled=false;
                   mBitmapFactoryOptions.inSampleSize=SampleSize;
                   return BitmapFactory.decodeStream(context.getAssets().open(FileName),null, mBitmapFactoryOptions);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
   
    /**This method for String from assets
     * @param context for application refrence
     * @param FileName string for image assets path
     * @return String
     */
    public static String getStringFromAssets(Context context,final String FileName)
    {
        try{
                return InputStreamToString(context.getAssets().open(FileName));
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
   
    /**This method for close object
     * @return void
     */
    public static void closeSilently(final Closeable c) {
        if (c == null)
            return;
        try {
              c.close();
        } catch (Throwable t) {
            // do nothing
        }
    }
   
    /**This method for Garbase collection
     * @return void
     */
    public static void GC(){
        System.runFinalization();
        System.gc();
    }   

}

//*****************************************************************************************
PDF broucher Download
 //For Download pdf of brochure
     private class GetPDFBoucher extends AsyncTask<String,Boolean, Boolean>{  
        //    Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        //    File mOutFile;
            
            protected void onPreExecute() {
                mProgressDialog=new BranchDialog(DrcSystemsPresentation.this, "Server PDF", "PDF downloading...");
                super.onPreExecute();
            }

            protected Boolean doInBackground(String... PDFURL) {
                boolean Status=false;
                if(mCommonClass.CheckNetworkNoMessage(DrcSystemsPresentation.this))
                {
                     if(mCommonClass.MemoryCardCheck())
                      {  
                          try{
                                 File testDirectory = new File(Environment.getExternalStorageDirectory()+"/Download/");
                                    if(!testDirectory.exists()){
                                        testDirectory.mkdir();
                                    }
                                
                                 InputStream mInputStream=mCommonClass.OpenHttpConnectionPost(PDFURL[0]);
                                 FileOutputStream fos = new FileOutputStream(testDirectory+"/drc_brochure.pdf");
              
                                    byte data[] = new byte[1024];
              
                                    int count = 0;
                                   // Log.v("Total", "total = "+ mInputStream.available());  
                                    int progress = mInputStream.available()/100;
                                    while ((count=mInputStream.read(data)) != -1)
                                    {
                                        if(progress <= mInputStream.available()){
                                            progress += progress;
                                           // Log.v("progress", "progress = "+ progress);      
                                        }
                                        fos.write(data, 0, count);
                                    }
                                    fos.close();
                                    mInputStream.close();
                                    Status=true;
                              }
                         catch (Exception e) {
                            e.printStackTrace();
                             Status=false;
                        }
                    }
            }
           else{
               Status=false;
               }
                return Status;
            }
            protected void onPostExecute(Boolean result) {
                //viewfocus.requestFocus();
                 mProgressDialog.dismiss();
                 if(result){
                        Toast.makeText(DrcSystemsPresentation.this, "Download PDF", Toast.LENGTH_SHORT).show();
                     // startActivity(Intent.createChooser(emailIntent, "Send Mail..."));
                 }
                 else{
                     Toast.makeText(DrcSystemsPresentation.this, "Not Download PDF", Toast.LENGTH_SHORT).show();
                 }    
                super.onPostExecute(result);          
            }
         }
     private BranchDialog mProgressDialog=null;
     public class BranchDialog extends Dialog
        {
            private TextView title;          
            public BranchDialog(Context context,String strtitle,String strbody)
            {
                super(context);      
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                setContentView(R.layout.customdialog);
                setCancelable(true);
                //setTitle(strtitle.toString());
                title = (TextView)findViewById(R.id.txtdialogtext);
                title.setText(strbody.toString());
                show();
            }
        }

============================================
 if(v==imgBroucher){
            new GetPDFBoucher().execute("http://www.drcsystems.com/brochure/drc_brochure.pdf");
        }

===============================================
custom dialog xml
<?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:gravity="center"
  android:layout_height="wrap_content">
  <ProgressBar android:id="@+id/progressBar1"
   android:layout_gravity="center"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
   </ProgressBar>
  <TextView
    android:id="@+id/txtdialogtext"
    android:text="Loging ..."
    android:layout_marginLeft="15dip"
    android:layout_gravity="center"
    android:textSize="18dip"
    android:textColor="#FFF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

No comments:

Post a Comment