Search This Blog

Tuesday, 8 March 2011

lazy loading

//package

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class PhotoGallerry extends Activity {

private Gallery gallery;
private ImageView imgView;
// HashMap hv;
Vector<Photos> vPhotos;

// String[] thumb_url;
// String[] big_url;
// Bitmap[] bitmap;
// Bitmap[] bitmap_big;
// int[] flag;
// Information information =new Information();
Photos photos = new Photos();
Button back;

@SuppressWarnings("unused")
@Override
public void onCreate(Bundle savedInstanceState)
 {
super.onCreate(savedInstanceState);

System.out.println("On create start");

Bundle bundel = getIntent().getExtras();
vPhotos = new Vector<Photos>();
vPhotos = Photos.vPhotos;

/* if(bundel!=null) vPhotos = (Vector<Photos>)bundel.get("hash_photo");
 * else System.out.println("Hash Size------------" + vPhotos.size());
 */
// photos.thumburl = new String();
// photos.bigurl = new String();
// photos.t_bitmap = new Bitmap;
// photos.b_bitmap = new Bitmap[vPhotos.size()];
// System.out.println("SSSize"+ photos.bitmap.length );
// flag = new int[vPhotos.size()];



for (int index = 0; index < vPhotos.size(); index++)
 {
Photos photos = (Photos) vPhotos.elementAt(index);
/*if (photos.t_bitmap == null)
 {
photos.thumburl = photos.thumburl;
photos.bigurl = photos.bigurl;
photos.t_bitmap = DownloadImage(photos.thumburl);
// bitmap_big[id] = DownloadImage(big_url[id]);
System.out.println("in class photos" + photos.t_bitmap);
 }*/

setContentView(R.layout.photos);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
}

Photos.vPhotos = vPhotos;
imgView = (ImageView) findViewById(R.id.ImageView01);
photos.b_bitmap = DownloadImage(photos.bigurl);
imgView.setImageBitmap(photos.b_bitmap);

back = (Button) findViewById(R.id.btnback);
back.setOnClickListener(new View.OnClickListener()
 {
public void onClick(View v)
 {
Intent intent = new Intent(PhotoGallerry.this, Testpage.class);
System.out.println("in intent");
startActivity(intent);
setResult(RESULT_OK, intent);
finish();
 }
});
gallery.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("rawtypes")
public void onItemClick(AdapterView parent, View v, int position,
long id) {
Photos photos = (Photos) vPhotos.elementAt(position);
 final ImageDownloader imageDownloader = new ImageDownloader();
 int no=2;

 imgView.setScaleType(ScaleType.FIT_XY);
imgView.setImageBitmap(photos.t_bitmap);


if (photos.b_bitmap == null) {

  imageDownloader.download(photos, (ImageView) imgView, no);
 // imgView.setScaleType(ScaleType.CENTER_INSIDE);
// photos.b_bitmap = DownloadImage(photos.bigurl);
// imgView.setImageBitmap(photos.b_bitmap);

} else {
 imgView.setScaleType(ScaleType.CENTER_INSIDE);
imgView.setImageBitmap(photos.b_bitmap);
}
// imgView.setImageBitmap(photos.b_bitmap);

}
});

System.out.println("On create end");

}

private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");

try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();

response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}

Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}

public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
 private final ImageDownloader imageDownloader = new ImageDownloader();

public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(
R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}

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

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

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

public View getView(int position, View convertView, ViewGroup parent) {
int no=1;
System.out.println("getView called");
Photos p = vPhotos.elementAt(position);
ImageView imgView = new ImageView(cont);

imgView.setLayoutParams(new Gallery.LayoutParams(100, 100));
imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imgView.setBackgroundResource(GalItemBg);

  imageDownloader.download(p, (ImageView) imgView, no);
return imgView;
}
}

}

Google Map :- Give The Current Location as well as Touchable Current Location

1).  Get Google Maps API Key and KeyStore File

2). Create New Project


===================================================================
3). //XML File

main.xml
===================================================================

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.google.android.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0IHqSXChliCK94lmqnm0bdiNjkuXxL1kPsaP-gg"
        />
</LinearLayout>

===================================================================

4). //Write Code

GPSLocatorActivity .java

===================================================================
package com.VertexVerveInc.GPSLocator;


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

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class GPSLocatorActivity extends MapActivity {
private MapView mapView;
private MapController mapController;

    private LocationManager locationManager;
    private LocationListener locationListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
      
        locationListener = new GPSLocationListener();
      
        locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER,
            0,
            0,
            locationListener);
      
        mapView = (MapView) findViewById(R.id.mapView);
      
        // enable Street view by default
        mapView.setStreetView(true);
      
        // enable to show Satellite view
      //  mapView.setSatellite(true);
      
        // enable to show Traffic on map
        // mapView.setTraffic(true);
        mapView.setBuiltInZoomControls(true);
      
        mapController = mapView.getController();
        mapController.setZoom(16);
    }
  
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
  
    private class GPSLocationListener implements LocationListener
    {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                GeoPoint point = new GeoPoint(
                        (int) (location.getLatitude() * 1E6),
                        (int) (location.getLongitude() * 1E6));
              
                /* Toast.makeText(getBaseContext(),
                        "Latitude: " + location.getLatitude() +
                        " Longitude: " + location.getLongitude(),
                        Toast.LENGTH_SHORT).show();*/
                              
                mapController.animateTo(point);
                mapController.setZoom(16);
              
                // add marker
                MapOverlay mapOverlay = new MapOverlay();
     mapOverlay.setPointToDraw(point);
     List<Overlay> listOfOverlays = mapView.getOverlays();
     listOfOverlays.clear();
     listOfOverlays.add(mapOverlay);
    
                String address = ConvertPointToLocation(point);
                Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();

                mapView.invalidate();
            }
        }
      
        public String ConvertPointToLocation(GeoPoint point) {
         String address = "";
            Geocoder geoCoder = new Geocoder(
                    getBaseContext(), Locale.getDefault());
            try {
                List<Address> addresses = geoCoder.getFromLocation(
                 point.getLatitudeE6()  / 1E6,
                    point.getLongitudeE6() / 1E6, 1);

        if (addresses.size() > 0) {
            for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
             address += addresses.get(0).getAddressLine(index) + " ";
        }
            }
            catch (IOException e) {              
                e.printStackTrace();
            }
          
            return address;
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
  
    class MapOverlay extends Overlay
    {
     private GeoPoint pointToDraw;
    
     public void setPointToDraw(GeoPoint point) {
     pointToDraw = point;
     }

     public GeoPoint getPointToDraw() {
     return pointToDraw;
     }
    
        @Override
        public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
            super.draw(canvas, mapView, shadow);                

            // convert point to pixels
            Point screenPts = new Point();
            mapView.getProjection().toPixels(pointToDraw, screenPts);

            // add marker
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.mapmarker);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image      
            return true;
        }
      
        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView)
        {
         GPSLocationListener loc=new GPSLocationListener();
            //---when user lifts his finger---
            if (event.getAction() == 1) {              
                GeoPoint p = mapView.getProjection().fromPixels(
                    (int) event.getX(),
                    (int) event.getY());
              
//                    Toast.makeText(getBaseContext(),
//                        p.getLatitudeE6() / 1E6 + "," +
//                        p.getLongitudeE6() /1E6 ,
//                        Toast.LENGTH_SHORT).show();
              
              
                // add marker
                MapOverlay mapOverlay = new MapOverlay();
     mapOverlay.setPointToDraw(p);
     List<Overlay> listOfOverlays = mapView.getOverlays();
     listOfOverlays.clear();
     listOfOverlays.add(mapOverlay);
              
                    String address = loc.ConvertPointToLocation(p);
                    Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
                  
                  
            }                          
            return false;
        }      
      
    }
}