Wednesday 16 October 2013

Display Image

1)ImageLoader.java
===============
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Debug;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoader {
   
    //the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap cache=new HashMap();
    private File cacheDir;
    private int defaultimage_id;
private Context mContext=null;
private boolean Strach=false;
    private int Scale_Width=0;
    private int Scale_Height=0;
   
    public ImageLoader(Context context,int Defaultimage_id,int intidentifie,boolean strach,int Scale_Width,int Scale_Height){
    this.mContext=context;
    this.defaultimage_id=Defaultimage_id;
    this.Strach=strach;
    this.Scale_Width=Scale_Width;
    this.Scale_Height=Scale_Height;
        //Make the background thead low priority. This way it will not affect the UI performance
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
       
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
//         Toast.makeText(context, "Mounted", Toast.LENGTH_SHORT).show();
        if(intidentifie==1)
               { cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"EventSmallImageBuffer"); }
        else if(intidentifie==2)
          {cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"EventBigImageBuffer"); }
        else if(intidentifie==3)
           {cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Institute"); }
        else if(intidentifie==4)
            {cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"Advertise"); }
        }
        else
         {cacheDir=context.getCacheDir();}
         
        if(!cacheDir.exists())
             {cacheDir.mkdirs();}      
    }
   
    public void DisplayImage(String strImagePath, ImageView imgImageView)
    {
        if(cache.containsKey(strImagePath))  
        {
        if(Strach){
            Drawable mDrawable =new BitmapDrawable(cache.get(strImagePath));
            imgImageView.setBackgroundDrawable(mDrawable);          
        }
        else{
           imgImageView.setImageBitmap(cache.get(strImagePath));
        }
        }
        else
        {
            queuePhoto(strImagePath, imgImageView);
            if(Strach){
                imgImageView.setBackgroundResource(defaultimage_id);              
            }
            else{
                imgImageView.setImageBitmap(ImageShrink(BitmapFactory.decodeResource(mContext.getResources(),defaultimage_id)));  
            }
        }  
    }
   
    private void queuePhoto(String strImagePath, ImageView imgImageView)
    {
        //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
        photosQueue.Clean(imgImageView);
        PhotoToLoad p=new PhotoToLoad(strImagePath, imgImageView);
        synchronized(photosQueue.photosToLoad){
            photosQueue.photosToLoad.push(p);
            photosQueue.photosToLoad.notifyAll();
        }
       
        //start thread if it's not started yet
        if(photoLoaderThread.getState()==Thread.State.NEW)
            photoLoaderThread.start();
    }
   
    private Bitmap getBitmap(String strImagePath)
    {
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String strFilename=String.valueOf(strImagePath.hashCode());
        File mFile=new File(cacheDir, strFilename);
       
        //from SD cache
        Bitmap mBmp = DecodeFile(mFile);
        if(mBmp!=null){
               return mBmp;
        }else{
      //from web
      try{
        if(GlobalClass.CheckNetwork(mContext))
           {
           Bitmap mBitmap=null;
           InputStream mFileInputStream=new URL(strImagePath).openStream();
           OutputStream mOutputStream = new FileOutputStream(mFile);
           Utility.CopyStream(mFileInputStream, mOutputStream);
           mOutputStream.close();
           mBitmap = DecodeFile(mFile);
           return mBitmap;
           }
        else
        {
        return null;
        }
         
       } catch (Exception e){
          e.printStackTrace();
          return null;
       }
        }
    }
     
  //decodes image and scales it to reduce memory consumption
    private Bitmap DecodeFile(File mFile){
    try {    
    // Get the dimensions of the bitmap
          BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds=true;
            BitmapFactory.decodeStream(new FileInputStream(mFile),null,bmpFactoryOptions);
 
             if ( checkBitmapFitsInMemory(bmpFactoryOptions.outWidth, bmpFactoryOptions.outHeight, 2)){
//                 Log.w("Image Loader","Aborting bitmap load for avoiding memory crash");

     // Decode the image file into a Bitmap sized to fill the View
        bmpFactoryOptions.inJustDecodeBounds = false;
        bmpFactoryOptions.inPurgeable = true;
       
        Bitmap bitmapPostScale=ImageShrink(BitmapFactory.decodeStream(new FileInputStream(mFile),null,bmpFactoryOptions));
                     return bitmapPostScale;
             }
             else{
            Log.w("Bitmap Load","Memory Crash");
            Runtime.getRuntime().gc();
            return null;
             }
        }
        catch (Exception e) {
        e.printStackTrace();
        return null;
        }
    }
   
    //this function use for image large to small make
    private Bitmap ImageShrink(Bitmap bitmapPreScale){
    if(bitmapPreScale!=null){
    int oldWidth = bitmapPreScale.getWidth();
    int oldHeight = bitmapPreScale.getHeight();
    int newWidth = Scale_Width;  // whatever your desired width and height are
    int newHeight = Scale_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);
    }
    else{
    return null;
    }
   
    }
   
    private boolean checkBitmapFitsInMemory(long bmpwidth,long bmpheight, int bmpdensity ){
        long reqsize=bmpwidth*bmpheight*bmpdensity;
        long allocNativeHeap = Debug.getNativeHeapAllocatedSize();

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

    //Task for the queue
    private class PhotoToLoad
    {
        public String strImagePath;
        public ImageView mImageView;
        public PhotoToLoad(String strImagePath, ImageView mImageView){
        this.strImagePath=strImagePath;
            this.mImageView=mImageView;
        }
    }
   
    PhotosQueue photosQueue=new PhotosQueue();
   
    public void stopThread()
    {
        photoLoaderThread.interrupt();
        try {
photoLoaderThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
    }
   
    //stores list of photos to download
    class PhotosQueue
    {
        private Stack photosToLoad=new Stack();
       
        //removes all instances of this ImageView
        public void Clean(ImageView mImageV)
        {
            for(int j=0 ;j                if(photosToLoad.get(j).mImageView==mImageV)
                    photosToLoad.remove(j);
                else
                    ++j;
            }
        }
    }
   
    class PhotosLoader extends Thread {
        public void run() {
            try {
                while(true)
                {
                    //thread waits until there are any images to load in the queue
                    if(photosQueue.photosToLoad.size()==0)
                        synchronized(photosQueue.photosToLoad){
                            photosQueue.photosToLoad.wait();
                        }
                    if(photosQueue.photosToLoad.size()!=0)
                    {
                        PhotoToLoad photoToLoad;
                        synchronized(photosQueue.photosToLoad){
                            photoToLoad=photosQueue.photosToLoad.pop();
                        }
                        Bitmap bmp=getBitmap(photoToLoad.strImagePath);
                       cache.put(photoToLoad.strImagePath, bmp);
                       Object tag=photoToLoad.mImageView.getTag();
                       if(tag!=null && ((String)tag).equals(photoToLoad.strImagePath)){
                           BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.mImageView);
                           Activity a=(Activity)photoToLoad.mImageView.getContext();
                           a.runOnUiThread(bd);
                       }
                    }
                    if(Thread.interrupted())
                        break;
                }
            } catch (InterruptedException e) {
                //allow thread to exit
            }
        }
    }
   
    PhotosLoader photoLoaderThread=new PhotosLoader();
   
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap mBitmap;
        ImageView mImageView;
        public BitmapDisplayer(Bitmap mBmp, ImageView mImg)
        {
        this.mBitmap=mBmp;
        this.mImageView=mImg;
        }
        public void run()
        {
            if(mBitmap!=null)
            {
            if(Strach){
                Drawable mDrawable =new BitmapDrawable(mBitmap);
                mImageView.setBackgroundDrawable(mDrawable);
              }
            else{
               mImageView.setImageBitmap(mBitmap);
            }
            }
            else
            {
              if(Strach){
               mImageView.setBackgroundResource(defaultimage_id);
              }
              else{
              mImageView.setImageBitmap(ImageShrink(BitmapFactory.decodeResource(mContext.getResources(),defaultimage_id)));
              }
            }
        }
    }
   
//    public void clearCache() {
//        //clear memory cache
////     Iterator it = cache.entrySet().iterator();
////        while (it.hasNext()) {
////            Map.Entry pairs = (Map.Entry)it.next();  
////            if(cache.get(pairs.getKey())!=null){
////             cache.get(pairs.getKey()).recycle();
////             Bitmap mBitmap=null;
////             cache.put(pairs.getKey().toString(), mBitmap);
////            }
//////            System.out.println(pairs.getKey() + " = " + pairs.getValue());
//////            it.remove(); // avoids a ConcurrentModificationException
////        }
//
//        cache.clear();      
//        //clear SD cache
//        File[] mFilesArray = cacheDir.listFiles();
//        for(File mFile:mFilesArray)
//         mFile.delete();
//    }
//  
    public void clearCache() {
        try{
        if(!cache.isEmpty()){
    for (Map.Entry entry : cache.entrySet()) {
    try{
            // Log.i(TAG,"Image Key = " + entry.getKey());
            if(entry.getValue()!=null){
            if(!entry.getValue().isRecycled()){
            entry.getValue().recycle();
            entry.setValue(null);
            System.gc();
            }
            }
     }
     catch (Exception e) {
    e.printStackTrace();
     }
             }
            }
        }
        catch (Exception e) {
    e.printStackTrace();
    }
        finally{
            //clear memory cache
            cache.clear();
            //clear SD cache
            DeleteCache();
        }
    }

private void DeleteCache(){
try{
      File[] mFilesArray=cacheDir.listFiles();
        for(File mFile:mFilesArray)
        mFile.delete();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
2)Utility.java
===========
import java.io.InputStream;
import java.io.OutputStream;

public class Utility {
    public static void CopyStream(InputStream mFileInputStream, OutputStream mOutputStream)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            while(true)
            {
              int count=mFileInputStream.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              mOutputStream.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}
3)GlobalClass
============

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oauth.signpost.http.HttpResponse;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;

public class GlobalClass {
/**This method use for check Network Connectivity
*/
public static boolean CheckNetwork(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
       if(netinfo!=null && netinfo.isConnected() == true)
       {
        //Toast.makeText(this, "Connection Avilable", Toast.LENGTH_LONG).show();
        return true;
       }
       else
       {
        Toast.makeText(mContext, Constant.NETWORK_NOT_AVAILABLE, Toast.LENGTH_LONG).show();
        return false;      
       }
}
//************************************************************************************************************************
/**This method use for email validation check
*/
public static boolean isEmailValid(String email) {
boolean isValid = false;
   String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
   CharSequence inputStr = email;

   Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
   Matcher matcher = pattern.matcher(inputStr);
   if (matcher.matches()) {
       isValid = true;
   }
   return isValid;
}
/**This method use for check Network Connectivity withot message
*/
public static boolean CheckNetworkNoMessage(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
       if(netinfo!=null && netinfo.isConnected() == true)
       {
        return true;
       }
       else
       {
        return false;      
       }
}
    /**This method for font set
*/ 
public static Typeface setHindiFont(Resources mResources){
return Typeface.createFromAsset(mResources.getAssets(),"fonts/DroidHindi.ttf");
}
    /**This method use to Check Memory Card
*/  
    public static Boolean MemoryCardCheck() {
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    {
    return true;
    }
    else
    {
    return false;
    }
}
    
    /**
This Fuction is Used to Get Image form web Server 
**/
public static Bitmap DownloadImagePost(String strUrl)
   {        
       Bitmap mBitmap = null;
       InputStream mInputStream = null;        
       try {
        mInputStream = OpenHttpConnectionPost(strUrl);
           if(mInputStream != null)
           {
           
            System.out.println("Error File Not Found");
            mBitmap = BitmapFactory.decodeStream(mInputStream);
            mInputStream.close();
           }
          
       } catch (Exception e) {
           // TODO Auto-generated catch block
         //Log.e(strTAG,"Error in DownloadImage InputStream");
       }
       return mBitmap;                
   }
/**This method use for OpenHttpConnectionpost
*/
   static InputStream OpenHttpConnectionPost(String strUrl)throws IOException
   {
       InputStream mInputStream = null;
       int intResponse = -1;
              
       URL mURL = new URL(strUrl); 
       URLConnection mURLConnection = mURL.openConnection();
                
       if (!(mURLConnection instanceof HttpURLConnection)) {           
          //Log.e(strTAG,"Error in HTTP connection Not Connect");
        System.out.println("Error in HTTP connection Not Connect");
           throw new IOException("Not an HTTP connection");
       }
       try{
           HttpURLConnection mHttpURLConnection = (HttpURLConnection) mURLConnection;
           mHttpURLConnection.setAllowUserInteraction(false);
           mHttpURLConnection.setInstanceFollowRedirects(true);
           mHttpURLConnection.setRequestMethod("POST");
           mHttpURLConnection.connect(); 
           intResponse = mHttpURLConnection.getResponseCode();
           
           if (intResponse == HttpURLConnection.HTTP_OK) {
            mInputStream = mHttpURLConnection.getInputStream();                                 
           }                     
       }
       catch (Exception e)
       {
        //Log.e(strTAG,"Error in Error connecting");
        System.out.println("Error in Error connecting");
           throw new IOException("Error connecting");            
       }
       return mInputStream;     
   }
   
   //this function use for Date format example like DD-MM-YYYY to MM-DD-YYYY change
   public static String DateFormatChange(String StrDate,String FromPattern,String ToPattern){
  try{
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(FromPattern); 
    Date mDate=mSimpleDateFormat.parse(StrDate);
    return (String)DateFormat.format(ToPattern,mDate).toString();
  }
  catch (Exception e) {
  e.printStackTrace();
  return "";
   }       
   }
   
   //this function use for GetDateDay
   public static int GetDateDay(String StrDate,String FromPattern){
  try{
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(FromPattern); 
    Date mDate=mSimpleDateFormat.parse(StrDate);
    return Integer.parseInt(DateFormat.format("dd",mDate).toString());
  }
  catch (Exception e) {
  e.printStackTrace();
  return 0;
   }       
   }
   
   //this function use for GetDateMonth
   public static int GetDateMonth(String StrDate,String FromPattern){
  try{
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(FromPattern); 
    Date mDate=mSimpleDateFormat.parse(StrDate);
    return Integer.parseInt(DateFormat.format("MM",mDate).toString());
  }
  catch (Exception e) {
  e.printStackTrace();
  return 0;
   }       
   }
   
   //this function use for GetDateYear
   public static int GetDateYear(String StrDate,String FromPattern){
  try{
    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(FromPattern); 
    Date mDate=mSimpleDateFormat.parse(StrDate);
    return Integer.parseInt(DateFormat.format("yyyy",mDate).toString());
  }
  catch (Exception e) {
  e.printStackTrace();
  return 0;
   }       
   }
   public static String SOAPPostConnection(String url,String soapAction,String envelope) {

       final DefaultHttpClient httpClient=new DefaultHttpClient();
       // request parameters
       HttpParams params = httpClient.getParams();
          HttpConnectionParams.setConnectionTimeout(params, 10000);
          HttpConnectionParams.setSoTimeout(params, 15000);
          // set parameter
       HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

       // POST the envelope
       HttpPost httppost = new HttpPost(url);
       // add headers
          httppost.setHeader("soapaction", soapAction);
          httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

          String responseString=null;
             try {
     
                           // the entity holds the request
                        HttpEntity entity = new StringEntity(envelope);
                        httppost.setEntity(entity);
     
                        // Response handler
                        ResponseHandler rh=new ResponseHandler() {
                                         // invoked when client receives response
                                         public String handleResponse(HttpResponse response)
                                           throws ClientProtocolException, IOException {
                     
                                          // get response entity
                                          HttpEntity entity = ((org.apache.http.HttpResponse) response).getEntity();
                     
                                          // read the response as byte array
                                                StringBuffer out = new StringBuffer();
                                                byte[] b = EntityUtils.toByteArray(entity);
                     
                                                // write the response byte array to a string buffer
                                                out.append(new String(b, 0, b.length));
                                                return out.toString();
                                        }

@Override
public String handleResponse(
org.apache.http.HttpResponse response)
throws ClientProtocolException,
IOException {
// TODO Auto-generated method stub
return null;
}
                        };
     
                        responseString=httpClient.execute(httppost, rh); 

           }
          catch (Exception e) {
                  Log.v("exception", e.toString());
           }

          // close the connection
       httpClient.getConnectionManager().shutdown();
       return responseString;
      
}
}

================================================
public ImageLoader mImageLoader=null;
==============================
this.mImageLoader=new ImageLoader(mContext,R.drawable.imgdefaultimage,1,false,85,85);

=============
ImageView imgtView = (ImageView)convertView.findViewById(R.id.imgImage);
imgEvent.setTag(alstEvent_Thumb_Image.get(position));
if(GlobalClass.MemoryCardCheck())
 {
         mImageLoader.DisplayImage(alst_Thumb_Image.get(position), imgView);
 }

No comments:

Post a Comment