SearchActivity.java :  » App » uconn-map-project » com » team6 » Android Open Source

Android Open Source » App » uconn map project 
uconn map project » com » team6 » SearchActivity.java
package com.team6;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.android.maps.GeoPoint;
import com.team6.overlay.LandmarkOverlayItem;

public class SearchActivity extends ListActivity implements OnItemClickListener {

  private ArrayAdapter<String> adapter;
  private boolean forDirections;
  
  /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      
      // Get the values passed into this activity.
      Bundle extras = getIntent().getExtras(); 
      forDirections = extras.getBoolean(getString(R.string.forDirections));

      adapter = new ArrayAdapter<String>( this, R.layout.dest_item_list,
                        getResources().getStringArray(R.array.campus_landmarks));
      
      // Set the title accordingly
      if(forDirections)
        setTitle(getString(R.string.search_title_dir));      
      else
        setTitle(getString(R.string.search_title));
      
      setListAdapter(adapter);
      
      ListView lv = getListView();
      lv.setTextFilterEnabled(true);
      lv.setOnItemClickListener(this);

    }
    
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {      
      try {
        String name = String.valueOf(((TextView)parent.getChildAt(position)).getText());
      
        GeoPoint gp = reverseGeocode(name);
        LandmarkOverlayItem landmark = new LandmarkOverlayItem(gp, name);
        
        // Encode the landmark
        JSONObject json = landmark.encodeLandmark();
        
        // Use an intent to store the landmark
        Intent data = new Intent();
        data.putExtra(getString(R.string.LandmarkOverlayItem), json.toString());
        
        // Either return the landmark, or get a second one for directions
        if(forDirections) {
          // Start a directions activity
          data.setClass(getApplicationContext(), DirectionsActivity.class);
          startActivityForResult(data, R.id.GET_WDIRECTIONS);
        } else {
          // Set the result and return.
          setResult(Activity.RESULT_OK, data);
          finish();
        }
      } catch(NullPointerException e) {
        setResult(Activity.RESULT_CANCELED, null);
        finish();
      }
  }
    
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data); 
    
    switch(requestCode) {
    case R.id.GET_WDIRECTIONS:
      if(resultCode == Activity.RESULT_OK) {
        setResult(Activity.RESULT_OK, data);
        
      } else {
        setResult(Activity.RESULT_CANCELED, null);
      }
      finish();
      break;
    }
    }
  
  private GeoPoint reverseGeocode(String landmark) {
    
    GeoPoint rv = null;
    InputStream istream = null;
    String result = null;
      
    // Build a URL for querying google.
    StringBuilder geocodeUrl = new StringBuilder();
    
    geocodeUrl.append("http://maps.googleapis.com/maps/api/geocode/json?address=");
    geocodeUrl.append(landmark.replace(" ", "+"));
    geocodeUrl.append("+Storrs+CT&sensor=false");
    
    // Generate an HttpGet to get JSON encoded data from google
    try {
      HttpClient client = new DefaultHttpClient();
      HttpGet get = new HttpGet(geocodeUrl.toString());
      HttpResponse response = client.execute(get);
      HttpEntity entity = response.getEntity();
      istream = entity.getContent();
    } catch(ClientProtocolException e) {
      Log.e("HTTPe-CPE", e.toString());
    } catch(IOException e) {
      Log.e("HTTPe-IOE", e.toString());
    }
    
    // Read the result of the HttpGet to build a string encoding a JSON
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(istream,"iso-8859-1"),8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      istream.close();
      
      result = sb.toString();
    } catch(UnsupportedEncodingException e) {
      Log.e("READe-UEE", e.toString());
    } catch(IOException e) {
      Log.e("READe-IOE", e.toString());
    }
    
    // Parse the string into JSON entities,
    try {
      JSONObject root = new JSONObject(result);
      JSONArray results = root.getJSONArray("results");
      
      JSONObject location = results.getJSONObject(0)
                     .getJSONObject("geometry")
                     .getJSONObject("location");
      
      rv = new GeoPoint(  (int)(location.getDouble("lat")*(1E6)),
                (int)(location.getDouble("lng")*(1E6)));
      
    } catch(JSONException e) {
      Log.e("JSONe", e.toString());
    }
    
    return rv;
  }    
    
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.