Tuesday, May 17, 2011

map view with friends location and search location

package com.buddylist;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.examples.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;



public class mapAcitvity extends MapActivity implements OnClickListener,
        LocationListener {
    mapAcitvity activity;
    LinearLayout linearLayout;
    MapView mapView;
    List<Overlay> mapOverlays;
    Drawable drawable;
    MontactItemizedOverlay itemizedOverlay;
    public ImageLoader imageLoader;
    private Button btnViewFrends, btnAddFrends, btnSetting;
    GeoPoint selfTrack;
    LocationManager lm;
    private String bestProvider;
    private EditText mapSearchEdtxt;
    Context context;
    Drawable d1;
    ImageView image;
    List<HashMap<String, String>> mapList;

    @Override
    protected void onCreate(Bundle icicle) {

        super.onCreate(icicle);
        setContentView(R.layout.editmaplocation);
       
        context = getApplicationContext();
        activity=this;
        imageLoader = new ImageLoader(this.getApplicationContext());   

    //    mapSearchEdtxt = (EditText) findViewById(R.id.mapSearchEditText);
        //mapSearchEdtxt.setOnClickListener(this);

    /*    btnAddFrends.setOnClickListener(this);
        btnViewFrends.setOnClickListener(this);
        btnSetting.setOnClickListener(this);
*/
       
        //image=(ImageView)findViewById(R.id.Imageloc);
        mapList = buildGroupListForSimpleAdapter();

        mapView = (MapView) findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mapView.setStreetView(true);
        mapView.setTraffic(true);
        mapOverlays = mapView.getOverlays();
        mapView.getController().setZoom(2);
        // mapView.s

        // GeoPoint point = new GeoPoint(19240000,-99120000);
        // OverlayItem overlayitem = new OverlayItem(point, "Mexico",
        // "in mexico");
        // itemizedOverlay.addOverlay(overlayitem);
        // mapOverlays.add(itemizedOverlay);

        // japan
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
                this);
        List<String> providers = lm.getAllProviders();

        for (String provider : providers) {
            // printProvider(provider);
           
        }

        Criteria criteria = new Criteria();
        bestProvider = lm.getBestProvider(criteria, false);
        // output.append("\n\nBEST Provider:\n");
   
        Location location = lm.getLastKnownLocation(bestProvider);

        // System.out.println("location lat......"+location.getLatitude()+"location long...."+location.getLongitude());
        GeoPoint point2 = null;

        if (location != null)
        {
            //BitmapDrawable(Resources)
        // d1 = this.getResources().getDrawable(R.drawable.pin);
            //itemizedOverlay = new MontactItemizedOverlay(d1);
            double startLatitude = location.getLatitude();// 40.93293

            double startLongitude = location.getLongitude();// -73.985973

            point2 = new GeoPoint((int) (startLatitude * 1E6),
                    (int) (startLongitude * 1E6));

        /*    OverlayItem overlayitem2 = new OverlayItem(point2, "I am here",
                    "I am here");
            itemizedOverlay.addOverlay(overlayitem2);
            mapOverlays.add(itemizedOverlay);
            mapView.getController().setCenter(point2);*/

            for (int i = 0; i < mapList.size(); i++)
            {
                HashMap<String, String> temp = mapList.get(i);

                System.out.println("================1lati"+temp.get("LOC_LAT"));
                System.out.println("================1langi"+temp.get("LOC_LONG"));
                double endLatitude = Double.parseDouble(temp.get("LOC_LAT"));
                double endLongitude = Double.parseDouble(temp.get("LOC_LONG"));
               
                String userName = temp.get("LOC_NAME");
                String locname = temp.get("LOC_IMAGE");
               
               
                  //ImageView img1=new ImageView(this);
                //imageLoader.MapImage( locname,  activity, d1);
               
             //  d1=    com.traveldairy.dairylist.ImageLoader.mapd;
            //createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)
               
           
               
                /*d1= LoadImageFromWebOperations(locname);
                System.out.println("++++++++++++++++++show"+d1);
               
                */
                if (locname.equals(""))
                {
                    d1 = this.getResources().getDrawable(R.drawable.pin);
                   
                }
               
                else
                {
                Bitmap image=    imageLoader.getBitmap(locname);
                try {
                    Bitmap resizedBitmap =Bitmap.createScaledBitmap(image, 50, 50, true);
                    d1 = new BitmapDrawable(resizedBitmap);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    d1=this.getResources().getDrawable(R.drawable.stub);
                   
                    e.printStackTrace();
                }
           
               
                //    d1= LoadImageFromWebOperations(locname);
                }
                 System.out.println("++++++++++++++++++show"+d1);
               
               
               
               
                Location locationStart = new Location("Me");
                 locationStart.setLatitude(startLatitude);
                locationStart.setLongitude(startLongitude);

                Location locationEnd = new Location("frend");

                locationEnd.setLatitude(endLatitude);
                locationEnd.setLongitude(endLongitude);
                PinPoint(endLatitude, endLongitude, userName, userName);
                float distance = locationStart.distanceTo(locationEnd);
                /*if (distance <= 1000.0f) {
                    PinPoint(endLatitude, endLongitude, userName, userName);

                    System.out.println("results:-" + distance + " M");
                }*/
            }

        }
        else
        {

            double startLatitude = 40.93000;

            double startLongitude = -73.985000;
            drawable = this.getResources().getDrawable(R.drawable.pin);
            itemizedOverlay = new MontactItemizedOverlay(drawable);
            point2 = new GeoPoint((int) (startLatitude * 1E6),
                    (int) (startLongitude * 1E6));

            OverlayItem overlayitem2 = new OverlayItem(point2, "I am here",
                    "I am here");
            itemizedOverlay.addOverlay(overlayitem2);
            mapOverlays.add(itemizedOverlay);
            mapView.getController().setCenter(point2);

            for (int i = 0; i < mapList.size(); i++)
            {

                HashMap<String, String> temp = mapList.get(i);
               
                System.out.println("================1lati"+temp.get("LOC_LAT"));
                System.out.println("================1langi"+temp.get("LOC_LONG"));
                double endLatitude = Double.parseDouble(temp.get("LOC_LAT"));
                double endLongitude = Double.parseDouble(temp.get("LOC_LONG"));
               
                String userName = temp.get("LOC_NAME");
                String locname = temp.get("LOC_IMAGE");
               
                   
               
                if (locname.equals(""))
                {
                    d1 = this.getResources().getDrawable(R.drawable.pin);
                   
                }
               
                else
                {
                    Bitmap image=    imageLoader.getBitmap(locname);
                    try {
                        Bitmap resizedBitmap =Bitmap.createScaledBitmap(image, 50, 50, true);
                        d1 = new BitmapDrawable(resizedBitmap);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        d1=this.getResources().getDrawable(R.drawable.stub);
                       
                        e.printStackTrace();
                    }
               
                   
                    //    d1= LoadImageFromWebOperations(locname);
                    }
                 System.out.println("++++++++++++++++++show"+d1);
               
            //    d1= LoadImageFromWebOperations(locname);
                System.out.println("++++++++++++++++++show"+d1);
           
                Location locationStart = new Location("Me");

                locationStart.setLatitude(startLatitude);
                locationStart.setLongitude(startLongitude);

                Location locationEnd = new Location("frend");

                locationEnd.setLatitude(endLatitude);
                locationEnd.setLongitude(endLongitude);

                PinPoint(endLatitude, endLongitude, userName, userName);
                /*float distance = locationStart.distanceTo(locationEnd);
                if (distance <= 1000.0f) {

                    System.out.println("results:-" + distance + " M");*/
                //}
            }
        }

        /*Bundle b1 = getIntent().getExtras();
        boolean map = b1.getBoolean("MAP");

        if (!map) {

        } else {
            Bundle b = getIntent().getExtras();
            VisibilityUserDataList v2 = b.getParcelable("MAPDATA");

            int dataLen = v2.size();
            if (dataLen > 0) {
                for (int i = 0; i < dataLen; i++) {

                    boolean check = Boolean.parseBoolean(v2.get(i)
                            .getCheckStatus());
                    if (check == true) {
                        String lati = v2.get(i).getUserLat();
                        String longi = v2.get(i).getUserLong();

                        double lat = Double.parseDouble(lati);
                        double lng = Double.parseDouble(longi);
                        String title = v2.get(i).getUserName();
                        String montactUser = "Montact User";
                        System.out.println("lati " + lati + " longi " + longi
                                + " title " + title);

                        System.out.println("boolean check........." + check
                                + "..." + v2.get(i).getCheckStatus() + ">>"
                                + v2.get(i).getUserMobileNo());
                        PinPoint(lat, lng, title, montactUser);
                    }

                }

            } else {

            }*/

        //}

        // itemizedOverlay.addOverlay(drawable);

    }

   

    private Drawable LoadImageFromWebOperations(String url) {
       
       
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "srcname");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }



    public void PinPoint(double lati, double longi, String title, String snippet) {

        //BitmapDrawable(Resources)
       
        drawable = this.getResources().getDrawable(R.drawable.pin);
        drawable.getIntrinsicHeight();
        drawable.getIntrinsicWidth();
        System.out.println("getBounds=================="+drawable.getBounds());
       
        //image.setImageDrawable(d1);
        System.out.println("===================getIntrinsicHeight"+    d1.getIntrinsicHeight()+"\n getIntrinsicWidth====="+d1.getIntrinsicWidth());
        System.out.println("===================getMinimumHeight"+d1.getMinimumHeight()+"getMinwidth======"+d1.getMinimumWidth());
       
        itemizedOverlay = new MontactItemizedOverlay(d1);
        GeoPoint point2 = new GeoPoint((int) (lati * 1E6), (int) (longi * 1E6));

        OverlayItem overlayitem2 = new OverlayItem(point2, title, snippet);

        itemizedOverlay.addOverlay(overlayitem2);
        mapOverlays.add(itemizedOverlay);
        mapView.getController().setCenter(point2);
       
    }

   

   


    protected boolean isRouteDisplayed() {

        return false;
    }

    public class MontactItemizedOverlay extends ItemizedOverlay<OverlayItem> {

        private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

        public MontactItemizedOverlay(Drawable defaultMarker) {
            super(boundCenterBottom(defaultMarker));

            // TODO Auto-generated constructor stub
        }

        @Override
        protected OverlayItem createItem(int i) {
            // TODO Auto-generated method stub
            return mOverlays.get(i);

        }

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return mOverlays.size();

        }

        public void addOverlay(OverlayItem overlay) {
            mOverlays.add(overlay);
            populate();
        }

        @Override
        protected boolean onTap(int index) {

            Toast.makeText(mapAcitvity.this,
                    mOverlays.get(index).getTitle(), Toast.LENGTH_SHORT).show();
            return (true);

        }

    }

    public void onClick(View v) {
        // TODO Auto-generated method stub

   


       
   
       
        if (v == mapSearchEdtxt) {

            String searchStr = mapSearchEdtxt.getText().toString();
            if (searchStr != null) {

                /*
                 * Intent searchMapIntent=new Intent();
                 * searchMapIntent.putExtra("Search", searchStr);
                 * searchMapIntent.setClassName("track.me.ui",
                 * "track.me.ui.SearchMapActivity");
                 * startActivity(searchMapIntent);
                 */

                MapSearch searchLocation = new MapSearch(
                        getApplicationContext(), Locale.getDefault());
                List<Address> listAddresses = searchLocation
                        .getLocationFromName(searchStr);

                System.out.println(" listAddresses.size()"
                        + listAddresses.size());

                for (int i = 0; i < listAddresses.size(); ++i) {
                    Address temp = listAddresses.get(i);
                    double latitude = temp.getLatitude();
                    double longitude = temp.getLongitude();

                    System.out.println("latitude " + latitude + " longitude"
                            + longitude);
                    String feature = temp.getFeatureName();
                    String addressLine = temp.getAddressLine(i);
                    PinPoint(latitude, longitude, feature, addressLine);
                }

            }

        }
    }

   

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        if (location != null) {

            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            selfTrack = new GeoPoint((int) (latitude * 1000000),
                    (int) (longitude * 1000000));

            MapController mc = mapView.getController();
            mc.animateTo(selfTrack);

        }

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

   
    private List<HashMap<String, String>> buildGroupListForSimpleAdapter() {

        List<HashMap<String, String>> fillGroupMaps = new ArrayList<HashMap<String, String>>();
        String deviceid = "";
       
        int device=BuddyListAdapter.arraysize;//sort_user_device[position];
          System.out.println("device==========="+device);
       
     
          String userimageurl=  BuddylistActivity.mapimage;
       
            String Deviceid=BuddylistActivity.deviceid;
       
        System.out.println("image==========="+userimageurl);
        for(int i=0;i<device;i++)
  {
     
        String sort_user_device=BuddyListAdapter.sort_user_device[i];
        System.out.println("sort_user_device==========="+sort_user_device);
     
         deviceid=deviceid+sort_user_device+",";
  }
        System.out.println("deviceid before===="+deviceid);
        deviceid= deviceid.substring(0, deviceid.length()-1);
          System.out.println("deviceid===="+deviceid);
        
         String address ="http://imt.6te.net/Webservice_7s7/getlatlandetails_json.php?ids="+deviceid+"";
        //02-04 14:13:45.643: INFO/System.out(2319): URL:-http://java.greymatterindia.com/montacts/web/traveldiary.php/api/getDiaryLocation?data=%7B%22EndRecNo%22%3A%2220%22,%22TokenKey%22%3A%22ADpWYA==%22,%22NoOfRec%22%3A%2220%22,%22StartRecNo%22%3A%221%22,%22UsrId%22%3A%22235%22,%22TrdId%22%3A235%7D
         System.out.println("address===========:-" + address);
        JSONObject json = com.json.RestJsonClient.connect(address
                .trim());
        System.out.println("JSON===========:-" + json);
       
        //{"locationDetails":[{"date":"2011-04-24 02:45:37","lattitude":"43.6775","device_id":"56738976","longitude":"-80.7339"},{"date":"2011-04-17 07:20:57","lattitude":"59.1452","device_id":"11215211221","longitude":"12.6541"}]}

       
        try {
            JSONArray arrayitems = json.getJSONArray("locationDetails");

            for (int i = 0; i < arrayitems.length(); i++) {

                HashMap<String, String> map = new HashMap<String, String>();
                /*
                 * String locImage = arrayitems.getJSONObject(i).getString(
                 * "ProfileImage").toString();
                 */

                String TdlName = arrayitems.getJSONObject(i).getString(
                        "device_id");
                String TdlLng = arrayitems.getJSONObject(i).getString(
                        "longitude");
                String TdlLat = arrayitems.getJSONObject(i).getString(
                        "lattitude");
               
                System.out.println("TdlName===========:-" + TdlName);
                System.out.println("TdlName===========:-" + deviceid);
                if (TdlName.equals(Deviceid)) {
                    map.put("LOC_IMAGE", userimageurl);
                    map.put("LOC_NAME", "Device id: " + TdlName);
                    map.put("LOC_LONG", TdlLng);
                    map.put("LOC_LAT", TdlLat);
                    /*
                     * map.put("LOC_DESC", TdlDescription); map.put("LOC_ID",
                     * TdlUsrId); map.put("LOC_DESC", TdlDescription);
                     * map.put("LOC_DATE", Createddate);
                     */
                    map.put("CHECK_STATUS", "false");
                }
               


                else{
                   
                   
                    map.put("LOC_IMAGE", "");
                    map.put("LOC_NAME", "Device id: " + TdlName);
                    map.put("LOC_LONG", TdlLng);
                    map.put("LOC_LAT", TdlLat);
                   
                   
                }

fillGroupMaps.add(map);
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return fillGroupMaps;

    }
}

MAPsearch class:
package com.buddylist;

import java.io.IOException;
import java.util.List;
import java.util.Locale;


import android.content.Context;
import android.location.Address;
import android.location.Geocoder;

public class MapSearch
{
   
    Geocoder searchGeocode;
   
    Context context;
    Locale locale;
   
    public MapSearch()
    {
       
    }
   
   
    public MapSearch(Context context,Locale locale)
    {
       
        this.context=context;
        this.locale=locale;
        searchGeocode=new Geocoder(this.context, this.locale);
       
    }
   
   
    public List<Address> getLocationFromName(String locationName)
    {
        List<Address> listAddress = null;
       
        try {
            listAddress=searchGeocode.getFromLocationName(locationName, 4);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
       
       
        return listAddress;
    }
   
   

}

IMAGE  LOADER CLASS:
package com.buddylist;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;

import com.examples.R;







import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class ImageLoader
{
   
    public static Drawable mapd;//the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
    private HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
   
    private File cacheDir;
   
    public ImageLoader(Context context){
        //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
      
        //http://61.8.138.173:8080/montacts/web/uploads/userimg/235/travelprofileimage/4daec748ecc3c.jpg

        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
   
    final int stub_id=R.drawable.stub;
    public void DisplayImage(String url, Activity activity, ImageView imageView)
    {
        if(cache.containsKey(url))
            imageView.setImageBitmap(cache.get(url));
     
        else
        {
            queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);
        }   
    }
       
  
   
   
   
    public void MapImage(String url, Activity activity, Drawable imageView)
    {
        if(cache.containsKey(url))
       {
       // imageView.setImageBitmap(cache.get(url));
            //imageView.setBounds(30,30,30,30);
        //Log.i("tag", imageView.setImageBitmap(cache.get(url)));
         ImageView img1=new ImageView(activity);
         img1.setImageBitmap(cache.get(url));
       imageView.setBounds(10, 10, 10, 10);
        
         imageView=img1.getDrawable();
      
         mapd=imageView;
        System.out.println("d1==========1111111111"+imageView);
    }
     
       
      
        else
        {
             //imageView.setImageBitmap(cache.get(url));
           
             ImageView img1=new ImageView(activity);
      
             img1.setImageBitmap(cache.get(url));
             img1.setMinimumHeight(30);
             img1.setMinimumWidth(30);
             imageView.setBounds(10, 10, 10, 10);
             imageView=img1.getDrawable();
             //imageView=this.getResources().getDrawable(R.drawable.pin);
             mapd=imageView;
             System.out.println("d1==========222222222"+imageView);
            /* //   queuePhoto(url, activity, imageView);
            imageView.setImageResource(stub_id);*/
        }   
    }
   
   
   
   
    private void queuePhoto(String url, Activity activity, ImageView imageView)
    {
        //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(imageView);
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        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();
    }
   
    public Bitmap getBitmap(String url)
    {
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        File f=new File(cacheDir, filename);
       
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
       
        //from web
        try {
            Bitmap bitmap=null;
            InputStream is=new URL(url).openStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
           
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale++;
            }
           
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
   
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }
   
    PhotosQueue photosQueue=new PhotosQueue();
   
    public void stopThread()
    {
        photoLoaderThread.interrupt();
    }
   
    //stores list of photos to download
    class PhotosQueue
    {
        private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();
       
        //removes all instances of this ImageView
        public void Clean(ImageView image)
        {
            for(int j=0 ;j<photosToLoad.size();){
                if(photosToLoad.get(j).imageView==image)
                    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.url);
                        cache.put(photoToLoad.url, bmp);
                        System.out.println("(String)photoToLoad.imageView.getTag()"+(String)photoToLoad.imageView.getTag());
                        System.out.println("photoToLoad.url"+photoToLoad.url);
                        if(((String)photoToLoad.imageView.getTag()).equals(photoToLoad.url))
                        {
                            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                           
                            Activity a=(Activity)photoToLoad.imageView.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 bitmap;
        ImageView imageView;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
                imageView.setImageBitmap(bitmap);
            else
                imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        //clear memory cache
        cache.clear();
       
        //clear SD cache
        File[] files=cacheDir.listFiles();
        for(File f:files)
            f.delete();
    }

}




1 comment:

  1. This was a Good Project but it missing a layout.XML and Manifest to Explore more this Greet project.

    ReplyDelete