Tuesday 15 October 2013

Image Loader For Display Images

1) VideoListAdapter.java

package com.app.v3;

import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class VideoDownloadListAdapter extends BaseAdapter{

private Context mContext;
private LayoutInflater mLayoutInflator;
private ArrayList alstVideo_Download_ID =null;
private ArrayList alstVideo_ID          =null;
private ArrayList alstVideo_Name        =null;
public ArrayList  alstVedio_File_Name   =null;
private ArrayList alstVideo_imgs        =null;
private ArrayList alstVideo_Disc        =null;
private ArrayList alstVideo_path        =null;
public ImageLoader mImageLoader                 =null;

public VideoDownloadListAdapter(Context mContext,ArrayList alstVideo_Download_ID,ArrayListalstVideo_ID,ArrayList alstVideo_Name,ArrayListalstVedio_File_Name,ArrayListalstVideo_imgs,ArrayListalstVideo_Disc,ArrayListalstVideo_path){
this.mContext=mContext;
this.mLayoutInflator = LayoutInflater.from(mContext);
this.mImageLoader=new ImageLoader(mContext,R.drawable.detailbg_video_ic,1,false,CommanClass.getImageDIP(mContext, 85),CommanClass.getImageDIP(mContext, 85));
this.alstVideo_Download_ID = alstVideo_Download_ID;
this.alstVideo_ID = alstVideo_ID;
this.alstVideo_Name = alstVideo_Name;
this.alstVedio_File_Name = alstVedio_File_Name;
this.alstVideo_imgs = alstVideo_imgs;
this.alstVideo_Disc = alstVideo_Disc;
this.alstVideo_path = alstVideo_path;
}

public int getCount() {
return alstVideo_ID.size();
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = mLayoutInflator.inflate(R.layout.xdownload_video_adapter, null);
}
ImageView imgvideo = (ImageView)convertView.findViewById(R.id.img_video);
imgvideo.setTag(alstVideo_imgs.get(position));

if(CommanClass.MemoryCardCheck())
  {
          mImageLoader.DisplayImage(alstVideo_imgs.get(position), imgvideo);
  }

TextView txtTitle = (TextView)convertView.findViewById(R.id.txt_title);
txtTitle.setText(alstVideo_Name.get(position).toString().trim());

TextView txtDisc = (TextView)convertView.findViewById(R.id.txt_desc);
txtDisc.setText(alstVideo_Disc.get(position).toString());

LinearLayout lytContent = (LinearLayout)convertView.findViewById(R.id.lyt_content);
lytContent.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Intent mIntentDownload = new Intent(mContext,VideoPlay.class);
mIntentDownload.putExtra(Constants.PLAY_VIDEO.DOWNLOAD_VIDIO_KEY, alstVedio_File_Name.get(position).toString().trim());
mIntentDownload.setAction(Constants.PLAY_VIDEO.PLAY_DONLOAD_VEDIO);
mContext.startActivity(mIntentDownload);
}
});

LinearLayout lytImage = (LinearLayout)convertView.findViewById(R.id.lytImage);
lytImage.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Intent mIntentDownload = new Intent(mContext,VideoPlay.class);
mIntentDownload.putExtra(Constants.PLAY_VIDEO.DOWNLOAD_VIDIO_KEY, alstVedio_File_Name.get(position).toString().trim());
mIntentDownload.setAction(Constants.PLAY_VIDEO.PLAY_DONLOAD_VEDIO);
mContext.startActivity(mIntentDownload);
}
});

ImageView imgDelete = (ImageView)convertView.findViewById(R.id.imgDelete);
imgDelete.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
DeleteVideo(position);
}
});
return convertView;
}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param int
 * @return void
 * @use This function is used for create dialog for delete
 */
//*************************************************************************************************************************
//This function is used for create dialog for delete
private void DeleteVideo(final int pos) {
AlertDialog mAlertDialog = new AlertDialog.Builder(ViewGroupOrganizer.group).create();
mAlertDialog.setTitle(Constants.DELETE_DIALOG.DELETE_DIALOG);
mAlertDialog.setIcon(R.drawable.ic_delete);
mAlertDialog.setMessage(Constants.DELETE_DIALOG.DELETE_DIALOG_MESSAGE);
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(Constants.DELETE_DIALOG.DELETE_DIALOG_BUTTON_YES, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Delete_byID(pos);
}
});
mAlertDialog.setButton2(Constants.DELETE_DIALOG.DELETE_DIALOG_BUTTON_NO, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
mAlertDialog.show();
}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param int
 * @return void
 * @use For play Video on click of perticular list item
 */
public void CheckNetworkStatus(int position){
//position= getIntent().getIntExtra("position", 0);
Intent intent = new Intent(mContext, VideoPlay.class);
       //   intent.setAction(android.content.Intent.ACTION_VIEW);
             final ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
             final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
             final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

             if (wifi.isAvailable()) {
                 Toast.makeText(mContext, "Wifi connection.", Toast.LENGTH_LONG).show();
                 //intent.setDataAndType(Uri.parse(anshd.get(position).toString()), "video/*");
         Log.e("log_tag=", "device is hd.");
         intent.putExtra("ans", alstVedio_File_Name.get(position));
         //intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory()+File.separator+alstVedio_File_Name.get(position)), "video/*");
             } else if (mobile.isAvailable()) {
                 Toast.makeText(mContext, "GPRS connection.", Toast.LENGTH_LONG).show();
                 intent.putExtra("ans", alstVedio_File_Name.get(position));
                // intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory()+File.separator+alstVedio_File_Name.get(position)), "video/*");
             } else {
              intent.putExtra("ans", alstVedio_File_Name.get(position));
                 Toast.makeText(mContext, "No network connection.", Toast.LENGTH_LONG).show();
             }    
//i.putExtra("name", name.get(position));
mContext.startActivity(intent);
}
private Intent getIntent() {
return null;
}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param int
 * @return void
 * @use This function is used for delete music file
 */
//***************************************************************************************************************************
public void Delete_byID(int pos){
OpenDatabase();
mDbHelper.DeleteDownloadVideo(mSQLiteDatabase,alstVideo_Download_ID.get(pos).toString());
System.out.println("Alstvideopath==="+alstVideo_path.get(pos).toString());
System.out.println("alstVedio_File_Name==="+Constants.PLAY_VIDEO.VIDEO_PATH +alstVedio_File_Name.get(pos).toString());
DeleteFile(Constants.PLAY_VIDEO.VIDEO_PATH + alstVedio_File_Name.get(pos).toString().trim());
CloseDataBase();

alstVideo_Download_ID.remove(pos);
alstVideo_ID.remove(pos);
alstVideo_Name.remove(pos);
alstVedio_File_Name.remove(pos);
alstVideo_imgs.remove(pos);
alstVideo_Disc.remove(pos);
alstVideo_path.remove(pos);
notifyDataSetChanged();
}

private void DeleteFile(String Path){
File mFile = new File(Path);
if(mFile.exists()){
mFile.delete();
Toast.makeText(mContext, Html.fromHtml(Constants.DELETE_DIALOG.DELETE_MESSAGE), Toast.LENGTH_SHORT).show();
}
}

/**THIS FUNCTION IS USED FOR OPEN DATABASE */
    private DbHelper mDbHelper=null;
  private SQLiteDatabase mSQLiteDatabase=null;
  private void OpenDatabase()
  {
        try{
           if(mDbHelper==null && mSQLiteDatabase==null){
           mDbHelper = new DbHelper(mContext);
    mSQLiteDatabase = mDbHelper.getWritableDatabase();
           }
       }
       catch (Exception e) {
e.printStackTrace();
   }
  }

/**THIS FUNCTION IS USED FOR CLOSE DATABASE */
  private void CloseDataBase()
  {
  try{
  if(mDbHelper!=null && mSQLiteDatabase!=null){
mSQLiteDatabase.close();
mDbHelper.close();
mSQLiteDatabase=null;
mDbHelper=null;
  }
  }
  catch (Exception e) {
e.printStackTrace();
  }
  }
}

2)VideoList.java
============
package com.app.v3;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;

public class VideoDownloadList extends Activity implements OnClickListener{

private ListView lstDownload;
private VideoDownloadListAdapter mVideoDownloadListAdapter;
private ImageButton imgBack = null;
public ArrayList alstVideo_Download_ID =null;
public ArrayList alstVideo_ID          =null;
public ArrayList alstVideo_Name        =null;
public ArrayList alstVedio_File_Name   =null;
public ArrayList alstVideo_imgs        =null;
public ArrayList alstVideo_Disc        =null;
public ArrayList alstVideo_path        =null;

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

GetBasicData();

imgBack = (ImageButton)findViewById(R.id.imgBack);
imgBack.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ViewGroupOrganizer.group.back();
}
});
}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param none
 * @return void
 * @use For show data in listview of download video
 */
public void GetBasicData() {
alstVideo_Download_ID = new ArrayList();
alstVideo_ID = new ArrayList();
alstVideo_Name = new ArrayList();
alstVedio_File_Name = new ArrayList();
alstVideo_imgs = new ArrayList();
alstVideo_Disc = new ArrayList();
alstVideo_path = new ArrayList();

lstDownload = (ListView)findViewById(R.id.lstdownload);
mVideoDownloadListAdapter = new VideoDownloadListAdapter(this,alstVideo_Download_ID,alstVideo_ID,alstVideo_Name,alstVedio_File_Name,alstVideo_imgs,alstVideo_Disc,alstVideo_path);

OpenDatabase();
getDownloadList();
CloseDataBase();
lstDownload.setAdapter(mVideoDownloadListAdapter);
}
public void onClick(View arg0) {

}

//***********************************************************************************************************************
/**
 * @author Manisha
 * @param none
 * @return void
 * @use For Get data from database
 */
public void getDownloadList() {
Cursor c = mDbHelper.GetDownloadVideo(mSQLiteDatabase);
if(c!=null){
if(c.getCount() > 0){
c.moveToFirst();
while(c.isAfterLast() == false){
alstVideo_Download_ID.add(c.getString(0));
alstVideo_ID.add(c.getString(1));
alstVideo_Name.add(c.getString(2));
alstVedio_File_Name.add(c.getString(3));
alstVideo_imgs.add(c.getString(5));
alstVideo_Disc.add(c.getString(6));
alstVideo_path.add(c.getString(7));
c.moveToNext();
};
}
c.close();
}
}

/**THIS FUNCTION IS USED FOR OPEN DATABASE */
      private DbHelper mDbHelper=null;
  private SQLiteDatabase mSQLiteDatabase=null;
  private void OpenDatabase()
  {
        try{
           if(mDbHelper==null && mSQLiteDatabase==null){
           mDbHelper = new DbHelper(VideoDownloadList.this);
    mSQLiteDatabase = mDbHelper.getWritableDatabase();
           }
        }
        catch (Exception e) {
e.printStackTrace();
}
  }

/**THIS FUNCTION IS USED FOR CLOSE DATABASE */
  private void CloseDataBase()
  {
  try{
  if(mDbHelper!=null && mSQLiteDatabase!=null){
mSQLiteDatabase.close();
mDbHelper.close();
mSQLiteDatabase=null;
mDbHelper=null;
  }
  }
  catch (Exception e) {
e.printStackTrace();
  }
  }
}
3) ImageLoader.java
package com.app.v3;

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(),"SmallImageBuffer"); }
//         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){
             imgImageView.setBackgroundDrawable(new BitmapDrawable(cache.get(strImagePath)));          
         }
         else{
             imgImageView.setImageBitmap(cache.get(strImagePath));
         }
        }
        else
        {
            queuePhoto(strImagePath, imgImageView);
            if(Strach){
                imgImageView.setBackgroundResource(defaultimage_id);               
            }
            else{
                imgImageView.setImageResource(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 = CommanClass.DecodeFileGetBitmap(mContext, mFile.getAbsolutePath(),Scale_Width, Scale_Height);
        if(mBmp!=null){
               return mBmp;
        }else{
       //from web
       try{
         if(CommanClass.CheckNetwork(mContext))
            {
            InputStream mFileInputStream=new URL(strImagePath).openStream();
            OutputStream mOutputStream = new FileOutputStream(mFile);
            Utility.CopyStream(mFileInputStream, mOutputStream);
            mOutputStream.close();
//             mBitmap = DecodeFile(mFile);
            return CommanClass.DecodeFileGetBitmap(mContext, mFile.getAbsolutePath(),Scale_Width, Scale_Height);
            }
         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){
                 mImageView.setBackgroundDrawable(new BitmapDrawable(mBitmap));
               }
             else{
                 mImageView.setImageBitmap(mBitmap);
             }
            }
            else
            {
               if(Strach){
                 mImageView.setBackgroundResource(defaultimage_id);
               }
               else{
               mImageView.setImageResource(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();
}
}
}

$)SDCard.Java
===========
package com.app.v3;

import android.os.Environment;
import android.os.StatFs;

public class SDCard_Check {
public static boolean isFreeSpace(String path) {
//....path for sd card..."/mnt/sdcard"
//.....path for internal storage......"/data"
StatFs stat = new StatFs(path);
double sdAvailSize = (double) stat.getAvailableBlocks()
* (double) stat.getBlockSize();
double megaAvailable = sdAvailSize / 1048576;
if (megaAvailable > 10) {
return true;
} else {
return false;
}
}

public static boolean isSDCardMounted() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
}
======================================================
public static final String VIDEO_PATH = Environment.getExternalStorageDirectory() + File.separator + "FolderName"+File.separator+"video_";
==========================================================
5)ProcessDialog.java
public class ProcessDialog extends Dialog{
 private TextView title;         
     public ProcessDialog(Context context,String strtitle,String strbody) 
     {
         super(context);
         requestWindowFeature(Window.FEATURE_NO_TITLE);
         setContentView(R.layout.xprogress_dialog);
         setCancelable(true);
         //setTitle(strtitle.toString());
         title = (TextView)findViewById(R.id.txtdialogtext);
         title.setText(Html.fromHtml(strbody.toString()));
         show();
     }
}
============================================
5)

  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">

   android:layout_gravity="center"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
   

    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"/>


6) CommanClass.java
===============
package com.app.v3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

public class CommanClass {
private static final String strTAG="ServerConnection";

public static boolean CheckNetwork(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
       if(netinfo!=null && netinfo.isConnected() == true)
       {
        return true;
       }
       else
       {
        Toast.makeText(mContext, Constants.NETWORK_NOT_AVAILABLE, Toast.LENGTH_LONG).show();
        return false;      
       }
}

/**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 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 method use to Check Memory Card
*/
   public static Boolean MemoryCardCheck() {

  if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
  {
  return true;
  }
  else
  {
  return false;
  }
}
 
// Getting DIP
public static boolean isTablet(Context context){
int DPI=context.getResources().getDisplayMetrics().densityDpi;
// int width = context.getResources().getDisplayMetrics().widthPixels;
// int height = context.getResources().getDisplayMetrics().heightPixels;

if((DisplayMetrics.DENSITY_MEDIUM == DPI) && (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE){
System.out.println("isTABLET - TRUE");
return true;
}
System.out.println("isTABLET - FALSE");
return false;

}

/**This method use for GetConnectionObject to Server
*/
public String GetConnectionObject(String strUrl) {
InputStream mInputStream = null;
try {
//This is the default apacheconnection.
HttpClient mHttpClient = new DefaultHttpClient();
//Pathe of serverside
HttpGet mHttpGet = new HttpGet(strUrl);

//get the valu from the saerverside as response.
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
mInputStream = mHttpEntity.getContent();

 }
 catch (Exception e) {
// TODO Auto-generated catch block
Log.e(strTAG,"Error in HttpClient,HttpPost,HttpResponse,HttpEntity");
 }

String strLine = null;
String strResult = null;
//convert response in to the string.
try {
 BufferedReader mBufferedReader = new BufferedReader(new InputStreamReader(mInputStream,"iso-8859-1"), 8);
 StringBuilder mStringBuilder = new StringBuilder();
   while((strLine = mBufferedReader.readLine()) != null) {
  mStringBuilder.append(strLine + "\n");
 }
   mInputStream.close();
   strResult = mStringBuilder.toString();
  }
  catch (Exception e) {
 //System.out.println("Error in BufferedReadering");
     Log.e(strTAG,"Error in BufferedReadering");
   }
 
return strResult;  
}

/**
* 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(Context context, String ImagePath, 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("Comman Class-->", "ImagePath Not Found.");
return null;
}

} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* This function use for calculateSampleSize
*
* @param
* @return int
*/
private 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 is only for protrait mode
public static int getImageDIP(Context context, int values) {
return (int) ((int)values * context.getResources().getDisplayMetrics().density);
}
}


No comments:

Post a Comment