Pages

Saturday 27 August 2011

Feeling on getting a job means for:-------

Hiii... I only want to say on excitement of job>>>






An excitement of getting a job is invitation to slave.

How to find out location on google map by user entered location in searchbox in Android


Hi,This is simple source code to find out the location without using geocoading in android.When user want to find out any location in google map,use this source code to make helpful for urself.

Here,I am making two class but you can do it only single one.

<b>mapfinder.class</b>

import android.graphics.drawable.Drawable;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

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

public class mapfinder extends MapActivity {
    private MapView map=null;
    Vector v;
   
    private MyLocationOverlay me=null;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapdemo);
        //locationlocator
        final String httpPath = "http://maps.google.com/maps/geo?q="+locationlocator.addressInput.getText().toString()+"&output=csv";
        HttpClient httpclient = new DefaultHttpClient();
           HttpGet httpget = new HttpGet(httpPath);
           try {
   
       HttpEntity httpEntity = httpclient.execute(httpget).getEntity();
       
       if (httpEntity != null){
        InputStream inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
          
        String line = null;
           String ss = null;
        while ((line = bufferedReader.readLine()) != null) {
         stringBuilder.append(line + "\n");
         ss=line;
        
        }
       
         v = new Vector();
        StringTokenizer st = new StringTokenizer (ss,",");
        while(st.hasMoreTokens()){
           
            //Log.d("cccccccccccccc","ccccccccccccccccc"+st.nextToken());
            v.add(st.nextToken());
        }
   
//        for(int i=0;i<ss.length();i++){
//             Log.d("cccccccccccccc","ccccccccccccccccc"+ss.indexOf(i));
//        }
       
       
        inputStream.close();
          
      
       
       // text.setText(stringBuilder.toString());
       }
      } catch (ClientProtocolException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      // Toast.makeText(AndroidHttpGetActivityActivity.this, e.toString(), Toast.LENGTH_LONG).show();
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      // Toast.makeText(AndroidHttpGetActivityActivity.this, e.toString(), Toast.LENGTH_LONG).show();
      }
       
       
      Log.d("vvvvvvvvvvvvvvvvvvvvvvvvvvv","vvvvvvvvvvvvvvvvvvvvvvv"+v.elementAt(3).toString());
       
        map=(MapView)findViewById(R.id.map);
       
        map.getController().setCenter(getPoint
                (Double.parseDouble(v.elementAt(2).toString()),Double.parseDouble(v.elementAt(2).toString())));
       
        map.getController().animateTo(getPoint
                (Double.parseDouble(v.elementAt(2).toString()),Double.parseDouble(v.elementAt(3).toString())));
       
        map.getController().setZoom(17);
        map.setBuiltInZoomControls(true);
       
        Drawable marker=getResources().getDrawable(R.drawable.marker);
       
        marker.setBounds(0, 0, marker.getIntrinsicWidth(),
                        marker.getIntrinsicHeight());
       
        map.getOverlays().add(new SitesOverlay(marker));
       
        me=new MyLocationOverlay(this, map);
        map.getOverlays().add(me);
    }
   
    @Override
    public void onResume() {
        super.onResume();
       
        me.enableCompass();
    }       
   
    @Override
    public void onPause() {
        super.onPause();
       
        me.disableCompass();
    }       
   
     @Override
    protected boolean isRouteDisplayed() {
        return(false);
    }
   
     @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_S) {
            map.setSatellite(!map.isSatellite());
            return(true);
        }
        else if (keyCode == KeyEvent.KEYCODE_Z) {
            map.displayZoomControls(true);
            return(true);
        }
       
        return(super.onKeyDown(keyCode, event));
    }

    private GeoPoint getPoint(double lat, double lon) {
        return(new GeoPoint((int)(lat*1000000.0),
                            (int)(lon*1000000.0)));
    }
       
    private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
        private List<OverlayItem> items=new ArrayList<OverlayItem>();
        private Drawable marker=null;
       
        public SitesOverlay(Drawable marker) {
            super(marker);
            this.marker=marker;
           
            items.add(new OverlayItem(getPoint
                    (Double.parseDouble(v.elementAt(2).toString()),Double.parseDouble(v.elementAt(3).toString())),
                                "UN", "United Nations"));
//            items.add(new OverlayItem(getPoint
//                    (30.7313450,76.7753850),
//                            "Lincoln Center",
//                                "Home of Jazz at Lincoln Center"));
//            items.add(new OverlayItem(getPoint
//                    (40.765136435316755,-173.97989511489868),
//                                "Carnegie Hall",
//                        "Where you go with practice, practice, practice"));
//            items.add(new OverlayItem(getPoint
//                    (40.70686417491799,-174.01572942733765),
//                                "The Downtown Club",
//                        "Original home of the Heisman Trophy"));

            populate();
        }
       
        @Override
        protected OverlayItem createItem(int i) {
            return(items.get(i));
        }
       
        @Override
        public void draw(Canvas canvas, MapView mapView,
                                        boolean shadow) {
            super.draw(canvas, mapView, shadow);
           
            boundCenterBottom(marker);
        }
        
        @Override
        protected boolean onTap(int i) {
            Toast.makeText(mapfinder.this,
                                items.get(i).getSnippet(),
                                Toast.LENGTH_SHORT).show();
           
            return(true);
        }
       
        @Override
        public int size() {
            return(items.size());
        }
    }
}
locationlocator.class: This is second class


import java.util.Vector;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class locationlocator extends Activity implements OnClickListener {
//    @Override
//    protected boolean isRouteDisplayed() {
//        return false;
// }
   
    final String httpPath = "addressInput";
    private MapView map;
    private Button btnSearch;
    public static EditText addressInput;
    private ProgressDialog pd;
    private Vector<String> v1;
    private MyLocationOverlay me=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    //    map = (MapView) findViewById(R.id.mapview); // Get map from XML
        btnSearch = (Button) findViewById(R.id.simplebtn_search); // Get button from xml
        addressInput = (EditText) findViewById(R.id.simpleadress);
        btnSearch.setOnClickListener(this);   

    }
   
    @Override
    public void onClick(View v) {
       
        startActivity( new Intent(locationlocator.this,mapfinder.class));
    }
   
   
}
After making this class. u can also add XML file for both of class.Also remember to add permission in manifest file.
May b this code helpful for you.


How to parse a string from server side or by specific url in android

This giving example will help to parse a string from server side or by specific url.
Code is given as below:


import android.app.Activity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class httpparsing extends Activity {
    //http://maps.google.com/maps/geo?q=chandigarh&output=csv
    //    http://feeds.feedburner.com/AndroidCoding
 final String httpPath = "http://maps.google.com/maps/geo?q=chandigarh&output=csv";
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       TextView text = (TextView)findViewById(R.id.text);
      
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet httpget = new HttpGet(httpPath);
       try {

   HttpEntity httpEntity = httpclient.execute(httpget).getEntity();
   
   if (httpEntity != null){
    InputStream inputStream = httpEntity.getContent();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
      
    String line = null;
       String ss = null;
    while ((line = bufferedReader.readLine()) != null) {
     stringBuilder.append(line + "\n");
     ss=line;
    
    }
   
   
    StringTokenizer st = new StringTokenizer (ss,",");
    while(st.hasMoreTokens()){
        Log.d("cccccccccccccc","ccccccccccccccccc"+st.nextToken());
    }

//    for(int i=0;i<ss.length();i++){
//         Log.d("cccccccccccccc","ccccccccccccccccc"+ss.indexOf(i));
//    }
   
   
    inputStream.close();
      
  
   
    text.setText(stringBuilder.toString());
   }
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(httpparsing.this, e.toString(), Toast.LENGTH_LONG).show();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(httpparsing.this, e.toString(), Toast.LENGTH_LONG).show();
  }
   }
}

Hope this blog helpful for you.

By : Parmil.S&Vkhooda

XML Parsing in Connection Class in Android

public class Connection {
    private URL _url;
    private InputStream is;
    private XmlPullParser _parser;
   
    public Connection(String _urlString) {
        // TODO Auto-generated constructor stub
        try{
              _url= new URL(_urlString);
              is=_url.openConnection().getInputStream();
              _parser=Xml.newPullParser();
              _parser.setInput(is, null);

             
           }
        catch(Exception ex){
           
        }
       
    }
   
    public String getLoginData() {
        String _success = null;
       
        try {
           
            int eventType = _parser.getEventType();
            boolean done = false;
            while (eventType != XmlPullParser.END_DOCUMENT && !done){
                String name = null;
                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        name = _parser.getName();
                        Log.d("Start tagggggggggggggg","start tagggggggggggg  " + name);
                       
                        if (name.equalsIgnoreCase("Art")){
                            _success= _parser.getAttributeValue(null,"Success");
                            Log.d("stateeeeeeeeeee","stateeeeeeeeeee" + _success);
                        }
       
                        break;
                    case XmlPullParser.END_TAG:
                        name = _parser.getName();
                        if (name.equalsIgnoreCase("Art")){
                            //messages.add(_loginData);
                        }
                        break;
                }
                eventType = _parser.next();
            }
        } catch (Exception e) {
            Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
            throw new RuntimeException(e);
        }
        return _success;
    }

public ArrayList<StatesData> getStateData() {
   
    ArrayList<StatesData> messages = null;
   
    try {
       
        int eventType = _parser.getEventType();
        StatesData _loginData = null;
        boolean done = false;
        while (eventType != XmlPullParser.END_DOCUMENT && !done){
            String name = null;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    messages = new ArrayList<StatesData>();
                    break;
                case XmlPullParser.START_TAG:
                    name = _parser.getName();
                   
                    Log.d("Start tagggggggggggggg","start tagggggggggggg  " + name);
                   
                    if (name.equalsIgnoreCase("Art")){
                        _loginData = new StatesData();
                        _loginData.id = _parser.getAttributeValue(null,"Success");
                        Log.d("stateeeeeeeeeee","stateeeeeeeeeee" + _loginData.id);
                       
                        _loginData._stateName = _parser.getAttributeValue(null,"DuplicateEmail");
                        Log.d("stateeeeeeeeeee","stateeeeeeeeeee" + _loginData._stateName);
                    }
   
                    break;
                case XmlPullParser.END_TAG:
                    name = _parser.getName();
                    if (name.equalsIgnoreCase("Art") && _loginData != null){
                        messages.add(_loginData);
                    }
                    break;
            }
            eventType = _parser.next();
        }
    } catch (Exception e) {
        Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
        throw new RuntimeException(e);
    }
    return messages;
}
}

public ArrayList<MessageData> getmessagedata() {
   
    ArrayList<MessageData> messagesAL = null;
   
    try {
       
        int eventType = _parser.getEventType();
        MessageData _messageData = null;
        boolean done = false;
        while (eventType != XmlPullParser.END_DOCUMENT && !done){
            String name = null;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    messagesAL = new ArrayList<MessageData>();
                    break;
                case XmlPullParser.START_TAG:
                    name = _parser.getName();
                   
                    Log.d("Start tagggggggggggggg","start tagggggggggggg " + name);
                   
                    if (name.equalsIgnoreCase("Detail")){
                        _messageData = new MessageData();
                        _messageData._msgid = _parser.getAttributeValue(null,"MessageId");
                        Log.d("iddddddddd","iddddddddddddddddddd" + _messageData._msgid);
                       
                        _messageData._sendername= _parser.getAttributeValue(null,"SenderName");
                        Log.d("descriptionnnnnnnnnnnnn","descriptionnnnnnnnnnn" +_messageData._sendername);
                       
                       
                        _messageData._image = _parser.getAttributeValue(null,"SenderImage");
                        Log.d("imageeeeeeeee","imageeeeeeeeeeeeeeeeee" + _messageData._image);
                       
                       
                        _messageData._messdesc= _parser.getAttributeValue(null,"Message");
                        Log.d("descriptionnnnnnnnnnnnn","descriptionnnnnnnnnnn" + _messageData._messdesc);
                       
                       
                       
                        _messageData._time= _parser.getAttributeValue(null,"MessageTime");
                        Log.d("descriptionnnnnnnnnnnnn","descriptionnnnnnnnnnn" + _messageData._time);
                    }
   
                    break;
                case XmlPullParser.END_TAG:
                    name = _parser.getName();
                    if (name.equalsIgnoreCase("Detail") && _messageData != null){
                        messagesAL.add(_messageData);
                    }
                    break;
            }
            eventType = _parser.next();
        }
    } catch (Exception e) {
        Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
        throw new RuntimeException(e);
    }
    return messagesAL;
}

By: Parmil.S & VkHooda

Image loader Example in android

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 android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.widget.ImageView;

public class ImageLoader {
   
    public static  HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
    private File cacheDir;
    private Context context;
    public ImageLoader(Context context){
        this.context=context;
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"PhotoShare");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
   
    final int stub_id= R.drawable.imgbgg;
    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);
        }   
    }
       
    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();
    }
   
    private 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= BitmapFactory.decodeStream(is);
            //bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           Bitmap viewBgrnd = BitmapFactory.decodeResource(this.context.getResources(), R.drawable.imgbgg);
           return viewBgrnd;
          // 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=150;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=2;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
           
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
           
//        Bitmap   bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
//       
//        Bitmap scaledImage = Bitmap.createScaledBitmap(bitmap,70,75, false);
//          
//         return scaledImage;
           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);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).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;
        int width;
        int height;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
            {
                //Bitmap bit=Bitmap.createBitmap(bitmap);
           
//            int width = bitmap.getWidth();
//
//            int height = bitmap.getHeight();
//
//            float scaleWidth = ((float)100) / width;
//
//            float scaleHeight = ((float)100) / height;
//
//            // create a matrix for the manipulation
//
//            Matrix matrix = new Matrix();
//
//            // resize the bit map
//
//            matrix.postScale(scaleWidth, scaleHeight);
//            Bitmap resizedBitmap = Bitmap.createBitmap(bit, 0, 0, width, height, matrix, true);
                //img.setImageBitmap(resizedBitmap);   
          
          
           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();
    }

}

Example of Creating a bitmap and set to image view in android

     Bitmap bit=Bitmap.createBitmap(ImageLoader.cache.get(_albumimgUrl.replaceAll(" ","%20")));
                  int width = bit.getWidth();

                    int height = bit.getHeight();

                   float scaleWidth = ((float)190) / width;

                    float scaleHeight = ((float)150) / height;

                    // create a matrix for the manipulation

                    Matrix matrix = new Matrix();

                    // resize the bit map

                    matrix.postScale(scaleWidth, scaleHeight);


// Class for image loader for image loading

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 android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.widget.ImageView;

public class ImageLoader {
   
    public static  HashMap<String, Bitmap> cache=new HashMap<String, Bitmap>();
    private File cacheDir;
    private Context context;
    public ImageLoader(Context context){
        this.context=context;
        photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"PhotoShare");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
   
    final int stub_id= R.drawable.imgbgg;
    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);
        }   
    }
       
    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();
    }
   
    private 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= BitmapFactory.decodeStream(is);
            //bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           Bitmap viewBgrnd = BitmapFactory.decodeResource(this.context.getResources(), R.drawable.imgbgg);
           return viewBgrnd;
          // 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=150;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=2;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
           
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
           
//        Bitmap   bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
//       
//        Bitmap scaledImage = Bitmap.createScaledBitmap(bitmap,70,75, false);
//          
//         return scaledImage;
           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);
                        Object tag=photoToLoad.imageView.getTag();
                        if(tag!=null && ((String)tag).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;
        int width;
        int height;
        public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
        public void run()
        {
            if(bitmap!=null)
            {
                //Bitmap bit=Bitmap.createBitmap(bitmap);
           
//            int width = bitmap.getWidth();
//
//            int height = bitmap.getHeight();
//
//            float scaleWidth = ((float)100) / width;
//
//            float scaleHeight = ((float)100) / height;
//
//            // create a matrix for the manipulation
//
//            Matrix matrix = new Matrix();
//
//            // resize the bit map
//
//            matrix.postScale(scaleWidth, scaleHeight);
//            Bitmap resizedBitmap = Bitmap.createBitmap(bit, 0, 0, width, height, matrix, true);
                //img.setImageBitmap(resizedBitmap);   
          
          
           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();
    }

}

Thursday 25 August 2011

How to Change URI path into String Path for Intent Activity in android

buttonRecording.setOnClickListener(new Button.OnClickListener(){
   
     @Override
     public void onClick(View arg0) {
      // TODO Auto-generated method stub

      Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
  
      startActivityForResult(intent, REQUEST_VIDEO_CAPTURED);
     }});

@Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            if(resultCode == RESULT_OK){
             if(requestCode == REQUEST_VIDEO_CAPTURED){
                 Uri selectedVideoUri = data.getData();
                    Log.d("uriiiiiiiiiiiii", "uriiiiiiiiiiiiiiiii"+selectedVideoUri);
                 filePath = null;

                    try {
                        // OI FILE Manager
                        String filemanagerstring = selectedVideoUri.getPath();
                        Log.d("uriiiiiiiiiiiii", "uriiiiiiiiiiiiiiiii"+filemanagerstring);
                        // MEDIA GALLERY
                        String selectedImagePath = getPath(selectedVideoUri);
                        Log.d("uriiiiiiiiiiiii", "uriiiiiiiiiiiiiiiii"+selectedImagePath);

                        if (selectedImagePath != null) {
                            filePath = selectedImagePath;
                            Log.d("uriiiiiiiiiiiii", "uriiiiiiiiiiiiiiiii"+selectedImagePath);
                        } else if (filemanagerstring != null) {
                            filePath = filemanagerstring;
                            Log.d("uriiiiiiiiiiiii", "uriiiiiiiiiiiiiiiii"+filePath);
                        } else {
                            Toast.makeText(getApplicationContext(),"Unknown path",    Toast.LENGTH_LONG).show();
                            Log.e("Bitmap", "Unknown path");
                        }

                        if (filePath != null) {
                             editpath.setText(filePath.toString());
                           
                           
                            bmp=ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);
                            videothum.setImageBitmap(bmp);
                        } else {
                            bmp = null;
                        }
                    }
                    catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Internal error",
                                Toast.LENGTH_LONG).show();
                        Log.e(e.getClass().getName(), e.getMessage(), e);
                    }
           
          }
            else
                if(resultCode == RESULT_CANCELED){
             uriVideo = null;
             Toast.makeText(VideoCapturingusingIntentActivity.this,"Cancelled!",
               Toast.LENGTH_LONG)
               .show();
            }
        }
    }
      public String getPath(Uri uri) {
            String[] projection = { MediaStore.Video.Media.DATA};
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if (cursor != null) {
                // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
                // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }
:-)