Wednesday, 18 April 2012

source to destination navigation(both are entered from user)

package com.qualcomm.QCARSamples.ImageTargets;

/**
* Google Maps Tutorial
* Txt2Java pCode Generated File
* Version 1.0.1.4
* B&P Software 2011
*
* This requires the Google API (Android 2.1)
* The mapping requires the correct API key in main.xml (B&P's won't work for other compilers)
* Uses the direction service to draw a blue line between the endpoints of the direction steps
* Stores the written directions also
*
*/

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

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

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.hardware.SensorListener;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
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;
import android.view.View.OnClickListener;

public class navigateAllActivity extends MapActivity {
MapView mapView;
MapController mc;
GeoPoint p;
ArrayList directions = new ArrayList();
Direction source_dir = null, dest = null;
TextView place;
EditText place_et,from;
String destination;
double lat, lng;
String source;
boolean flag_online = false;
private LocationManager locationManager;
private String provider;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.navigate_all);
mapView = (MapView) findViewById(R.id.mapview);
int height = getWindowManager().getDefaultDisplay().getHeight();
int width = getWindowManager().getDefaultDisplay().getWidth();
LinearLayout main = (LinearLayout) findViewById(R.id.main);
main.getLayoutParams().height = (int) ((height) * 0.90);

place = (TextView) findViewById(R.id.place);
place_et = (EditText) findViewById(R.id.place_et);

from = (EditText) findViewById(R.id.from_et);
source = "ahmedabad";
destination = "vadodara,gujarat";
destination = place_et.getText().toString();
Button go = (Button) findViewById(R.id.go);
go.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if (flag_online == false) {
// String coordinates[] = { "42.35849", "-71.06010" };
// lat = Double.parseDouble(coordinates[0]);
// lng = Double.parseDouble(coordinates[1]);
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// place.setText("Name of Place" + " Ahmedabad");
// getDirections("http://maps.googleapis.com/maps/api/directions/json?origin="
// + source
// + "&destination="
// + "vadodara,gujarat"
// + "&sensor=false");
//
//
// goToPoint();
// showPosition();
// flag_online = true;
// } else if (isConnected() == true) {
destination = place_et.getText().toString();
source = from.getText().toString();

// Initialize the location fields
String coordinates[] = { "42.35849", "-71.06010" };
lat = Double.parseDouble(coordinates[0]);
lng = Double.parseDouble(coordinates[1]);




p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

getDirections("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source
+ "&destination="
+ destination
+ "&sensor=false");

// directions.add(dest);
goToPoint();
showPosition();

// }
}
});

TabHost tabH = new TabHost(this);
TabWidget tabWidget = new TabWidget(this);
LinearLayout lin = new LinearLayout(this);
lin.setOrientation(LinearLayout.HORIZONTAL);
tabWidget.setId(android.R.id.tabs);
tabH.addView(tabWidget);
tabH.addView(lin);
FrameLayout fl = new FrameLayout(this);
fl.setId(android.R.id.tabcontent);
fl.setPadding(0, (int) (getWindowManager().getDefaultDisplay()
.getHeight() * 0.92), 0, 0);
lin.addView(fl);
tabH.setup();
// android.widget.TabHost.TabSpec ts1 = tabH.newTabSpec("hi");

tabH.addTab(tabH.newTabSpec("tag")

.setIndicator("").setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
// -- this tab contains multiple control grouped in a panel --
// //
LinearLayout panel = new LinearLayout(navigateAllActivity.this);
panel.setOrientation(LinearLayout.HORIZONTAL);
ImageView iv = new ImageView(navigateAllActivity.this);
iv.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i1 = new ImageView(navigateAllActivity.this);
i1.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i2 = new ImageView(navigateAllActivity.this);
i2.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i3 = new ImageView(navigateAllActivity.this);
i3.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i4 = new ImageView(navigateAllActivity.this);
i4.setBackgroundResource(R.drawable.icon_vuforia);

panel.addView(i1);
panel.addView(i2);
panel.addView(i3);
panel.addView(i4);
panel.addView(iv);
i1.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i2.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i3.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i4.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
iv.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
return panel;
} // TAB 1 done
}));
// ts1.setContent(new Intent(this,Tab1.class));
// tabH.addTab(ts1);
tabH.getTabWidget().getChildAt(0).getLayoutParams().height = (int) 0.000000001;
tabH.getTabWidget().getChildAt(0).getLayoutParams().width = (int) 0.0000000001;

LinearLayout.LayoutParams tab = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM);

// tab.setMargins(0,(int)
// (getWindowManager().getDefaultDisplay().getHeight()*0.8) , 0, 0);
addContentView(tabH, tab);

// getDirections("http://maps.googleapis.com/maps/api/directions/json?origin=Ahmedabad,Gujarat&destination=Vadodara,Gujarat&sensor=false");

mapView.setBuiltInZoomControls(true); // newer one

// This sets up where to show a push pin

// This gets everything going
// goToPoint();
// showPosition();

}// oncreate

@Override
protected boolean isRouteDisplayed() {
return true;
}// isroutedisplayed

public boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;

}

// This moves the map center to point p
public void goToPoint() {
int cx = (int) (((directions.get(0).lat + directions.get(directions
.size() - 1).lat) / 2d) * 1E6);
int cy = (int) (((directions.get(0).lng + directions.get(directions
.size() - 1).lng) / 2d) * 1E6);
GeoPoint gp = new GeoPoint(cx, cy);
int latSpan = (int) (Math.abs(directions.get(0).lat
- directions.get(directions.size() - 1).lat) * 1E6);
int lngSpan = (int) (Math.abs(directions.get(0).lng
- directions.get(directions.size() - 1).lng) * 1E6);
mc = mapView.getController();
mc.zoomToSpan(latSpan, lngSpan);
mc.animateTo(gp);

}// goto

// This shows the pushpin at point p
public void showPosition() {
MapOverlay mapOverlay = new MapOverlay();
List listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}// showpos

class MapOverlay extends Overlay {

@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);

Point screenPts = new Point();
GeoPoint gp;
int i = 0;
float lx = 0;
float ly = 0;
while (i < directions.size()) { dest = directions.get(i); gp = new GeoPoint((int) (dest.lat * 1E6), (int) (dest.lng * 1E6)); mapView.getProjection().toPixels(gp, screenPts); if (i > 0)
canvas.drawLine(lx, ly, screenPts.x, screenPts.y, paint);
lx = screenPts.x;
ly = screenPts.y;
i++;
}// drawing route

mapView.getProjection().toPixels(p, screenPts);

// This puts the marker on the map
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 46, null);
return true;
}


}// mapoverlay class

// http://maps.googleapis.com/maps/api/directions/output?parameters
// http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&sensor=false

public void getDirections(String loginUrl) {
JSONObject jArray = null;
String result = "";
String s;
String s1;
String s2;
directions.clear();

try {
HttpGet request = new HttpGet(loginUrl);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse);

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

try {
JSONArray array = jArray.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONArray legs1 = steps.getJSONArray("steps");
for (int i = 0; i < legs1.length(); i++) { JSONObject steps1 = legs1.getJSONObject(i); if (i == 0) s = steps1.getString("start_location"); else s = steps1.getString("end_location"); // Toast.makeText(getApplicationContext(), " "+s, 6000).show(); s1 = s.substring(s.indexOf(":") + 1); // cut off beginning s = s1.substring(s1.indexOf(":") + 1, s1.indexOf("}")); // isolate // longitude s1 = s1.substring(0, s1.indexOf(",")); // isolate latitude s.replaceAll(" ", ""); // remove spaces s1.replaceAll(" ", ""); s2 = steps1.getString("html_instructions"); // Toast.makeText(getApplicationContext(), ""+s2, 4000).show(); source_dir = new Direction(Double.parseDouble(s), Double.parseDouble(s1), s2); directions.add(source_dir); }// for } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } }// getdirections void getAddress() { try { Geocoder gcd = new Geocoder(this, Locale.getDefault()); List
addresses = gcd.getFromLocation(lat, lng, 5);

if (addresses.size() > 0) {
/*
* for (int i = 0; i < addresses.size(); i++) { Address address
* = addresses.get(i);
*
* int maxIndex = address.getMaxAddressLineIndex(); for (int x =
* 0; x <= maxIndex; x++) {
* result.append(address.getAddressLine(x)); result.append(",");
* } result.append(address.getLocality()); result.append(",");
* result.append(address.getPostalCode());
* result.append("\n\n"); }
*/
Address address = addresses.get(0);

String source1 = address.getAddressLine(1);
source = source1.substring(0, source1.indexOf(",") );

//Toast.makeText(getApplicationContext(), source, 4000).show();
// result.append("" + lat + lng);

}
} catch (IOException ex) {
// editTextShowLocation.append(ex.getMessage().toString());
} catch (NullPointerException f) {

}
}

public class Direction {
public double lng = 0;
public double lat = 0;
public String txt = "";

public Direction(double latitude, double longitude, String written) {
lng = longitude;
lat = latitude;
txt = written;
}// constructor

}// direction class

// TODO: Fill In Methods Etc.
}// class

Thursday, 12 April 2012

navigate.xml

general mapview xml file for navigaton in which mapview has apikey

navigate.xml

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









navigaet.xml










source to destination path in map

package com.qualcomm.QCARSamples.ImageTargets;

/**
* Google Maps Tutorial
* Txt2Java pCode Generated File
* Version 1.0.1.4
* B&P Software 2011
*
* This requires the Google API (Android 2.1)
* The mapping requires the correct API key in main.xml (B&P's won't work for other compilers)
* Uses the direction service to draw a blue line between the endpoints of the direction steps
* Stores the written directions also
*
*/

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

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

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.hardware.SensorListener;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
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;
import android.view.View.OnClickListener;

public class Mapper extends MapActivity implements LocationListener,
SensorListener {
MapView mapView;
MapController mc;
GeoPoint p;
ArrayList directions = new ArrayList();
Direction source_dir = null, dest = null;
TextView place;
EditText place_et;
String destination;
double lat, lng;
String source;
boolean flag_online = false;
private LocationManager locationManager;
private String provider;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.navigate);
mapView = (MapView) findViewById(R.id.mapview);
int height = getWindowManager().getDefaultDisplay().getHeight();
int width = getWindowManager().getDefaultDisplay().getWidth();
LinearLayout main = (LinearLayout) findViewById(R.id.main);
main.getLayoutParams().height = (int) ((height) * 0.90);

place = (TextView) findViewById(R.id.place);
place_et = (EditText) findViewById(R.id.place_et);

source = "ahmedabad";
destination = "vadodara,gujarat";
destination = place_et.getText().toString();
Button gps = (Button) findViewById(R.id.gps);
gps.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if (flag_online == false) {
// String coordinates[] = { "42.35849", "-71.06010" };
// lat = Double.parseDouble(coordinates[0]);
// lng = Double.parseDouble(coordinates[1]);
// p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
// place.setText("Name of Place" + " Ahmedabad");
// getDirections("http://maps.googleapis.com/maps/api/directions/json?origin="
// + source
// + "&destination="
// + "vadodara,gujarat"
// + "&sensor=false");
//
//
// goToPoint();
// showPosition();
// flag_online = true;
// } else if (isConnected() == true) {
destination = place_et.getText().toString();

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin
// provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager
.getLastKnownLocation(provider);

// Initialize the location fields
String coordinates[] = { "42.35849", "-71.06010" };
lat = Double.parseDouble(coordinates[0]);
lng = Double.parseDouble(coordinates[1]);

if (location != null) {
System.out.println("Provider " + provider
+ " has been selected.");
String lat1 = " " + (double) (location.getLatitude());
String lng1 = " " + (double) (location.getLongitude());
lat = Double.parseDouble(lat1);
lng = Double.parseDouble(lng1);

} else {

Toast.makeText(getApplicationContext(),
"Provider not available", 4000).show();
}
onLocationChanged(location);
getAddress();

p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
place.setText("Name of Place" + " " + source);
source_dir = new Direction(lat, lng, "s");
// dest = new Direction(20.25,
// 65.70, "d");
//
directions.clear();
directions.add(source_dir);
// source.replaceAll(" ", "");

getDirections_online("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source
+ "&destination="
+ destination
+ "&sensor=false");

// directions.add(dest);
goToPoint();
showPosition();

// }
}
});

TabHost tabH = new TabHost(this);
TabWidget tabWidget = new TabWidget(this);
LinearLayout lin = new LinearLayout(this);
lin.setOrientation(LinearLayout.HORIZONTAL);
tabWidget.setId(android.R.id.tabs);
tabH.addView(tabWidget);
tabH.addView(lin);
FrameLayout fl = new FrameLayout(this);
fl.setId(android.R.id.tabcontent);
fl.setPadding(0, (int) (getWindowManager().getDefaultDisplay()
.getHeight() * 0.92), 0, 0);
lin.addView(fl);
tabH.setup();
// android.widget.TabHost.TabSpec ts1 = tabH.newTabSpec("hi");

tabH.addTab(tabH.newTabSpec("tag")

.setIndicator("").setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
// -- this tab contains multiple control grouped in a panel --
// //
LinearLayout panel = new LinearLayout(Mapper.this);
panel.setOrientation(LinearLayout.HORIZONTAL);
ImageView iv = new ImageView(Mapper.this);
iv.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i1 = new ImageView(Mapper.this);
i1.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i2 = new ImageView(Mapper.this);
i2.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i3 = new ImageView(Mapper.this);
i3.setBackgroundResource(R.drawable.icon_vuforia);
ImageView i4 = new ImageView(Mapper.this);
i4.setBackgroundResource(R.drawable.icon_vuforia);

panel.addView(i1);
panel.addView(i2);
panel.addView(i3);
panel.addView(i4);
panel.addView(iv);
i1.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i2.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i3.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
i4.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
iv.getLayoutParams().width = getWindowManager()
.getDefaultDisplay().getWidth() / 5;
return panel;
} // TAB 1 done
}));
// ts1.setContent(new Intent(this,Tab1.class));
// tabH.addTab(ts1);
tabH.getTabWidget().getChildAt(0).getLayoutParams().height = (int) 0.000000001;
tabH.getTabWidget().getChildAt(0).getLayoutParams().width = (int) 0.0000000001;

LinearLayout.LayoutParams tab = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM);

// tab.setMargins(0,(int)
// (getWindowManager().getDefaultDisplay().getHeight()*0.8) , 0, 0);
addContentView(tabH, tab);

// getDirections("http://maps.googleapis.com/maps/api/directions/json?origin=Ahmedabad,Gujarat&destination=Vadodara,Gujarat&sensor=false");

mapView.setBuiltInZoomControls(true); // newer one

// This sets up where to show a push pin

// This gets everything going
// goToPoint();
// showPosition();

}// oncreate

@Override
protected boolean isRouteDisplayed() {
return true;
}// isroutedisplayed

public boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;

}

// This moves the map center to point p
public void goToPoint() {
int cx = (int) (((directions.get(0).lat + directions.get(directions
.size() - 1).lat) / 2d) * 1E6);
int cy = (int) (((directions.get(0).lng + directions.get(directions
.size() - 1).lng) / 2d) * 1E6);
GeoPoint gp = new GeoPoint(cx, cy);
int latSpan = (int) (Math.abs(directions.get(0).lat
- directions.get(directions.size() - 1).lat) * 1E6);
int lngSpan = (int) (Math.abs(directions.get(0).lng
- directions.get(directions.size() - 1).lng) * 1E6);
mc = mapView.getController();
mc.zoomToSpan(latSpan, lngSpan);
mc.animateTo(gp);

}// goto

// This shows the pushpin at point p
public void showPosition() {
MapOverlay mapOverlay = new MapOverlay();
List listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}// showpos

class MapOverlay extends Overlay {

@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);

Point screenPts = new Point();
GeoPoint gp;
int i = 0;
float lx = 0;
float ly = 0;
while (i < directions.size()) { dest = directions.get(i); gp = new GeoPoint((int) (dest.lat * 1E6), (int) (dest.lng * 1E6)); mapView.getProjection().toPixels(gp, screenPts); if (i > 0)
canvas.drawLine(lx, ly, screenPts.x, screenPts.y, paint);
lx = screenPts.x;
ly = screenPts.y;
i++;
}// drawing route

mapView.getProjection().toPixels(p, screenPts);

// This puts the marker on the map
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.pushpin);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 46, null);
return true;
}

@Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
// Touch event
// When the map is pressed and released the pushpin goes
// to that point
if (event.getAction() == 1) {
p = mapView.getProjection().fromPixels((int) event.getX(),
(int) event.getY());
directions.clear();
source_dir = new Direction(lat, lng, "s");
// dest = new Direction(20.25,
// 65.70, "d");
//
directions.add(source_dir);
// source.replaceAll(" ", "");
getDirections_online("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source
+ "&destination="
+ destination
+ "&sensor=false");

// directions.add(dest);

goToPoint();
showPosition();
}// if
return false;
}// ontouch

}// mapoverlay class

// http://maps.googleapis.com/maps/api/directions/output?parameters
// http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&sensor=false

public void getDirections(String loginUrl) {
JSONObject jArray = null;
String result = "";
String s;
String s1;
String s2;
directions.clear();

try {
HttpGet request = new HttpGet(loginUrl);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entityResponse = response.getEntity();
result = EntityUtils.toString(entityResponse);

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

try {
JSONArray array = jArray.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONArray legs1 = steps.getJSONArray("steps");
for (int i = 0; i < legs1.length(); i++) { JSONObject steps1 = legs1.getJSONObject(i); if (i == 0) s = steps1.getString("start_location"); else s = steps1.getString("end_location"); // Toast.makeText(getApplicationContext(), " "+s, 6000).show(); s1 = s.substring(s.indexOf(":") + 1); // cut off beginning s = s1.substring(s1.indexOf(":") + 1, s1.indexOf("}")); // isolate // longitude s1 = s1.substring(0, s1.indexOf(",")); // isolate latitude s.replaceAll(" ", ""); // remove spaces s1.replaceAll(" ", ""); s2 = steps1.getString("html_instructions"); // Toast.makeText(getApplicationContext(), ""+s2, 4000).show(); source_dir = new Direction(Double.parseDouble(s), Double.parseDouble(s1), s2); directions.add(source_dir); }// for } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } }// getdirections public void getDirections_online(String loginUrl) { JSONObject jArray = null; String result = ""; String s; String s1; String s2; // directions.clear(); try { HttpGet request = new HttpGet(loginUrl); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); HttpEntity entityResponse = response.getEntity(); result = EntityUtils.toString(entityResponse); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } try { JSONArray array = jArray.getJSONArray("routes"); JSONObject routes = array.getJSONObject(0); JSONArray legs = routes.getJSONArray("legs"); JSONObject steps = legs.getJSONObject(0); JSONArray legs1 = steps.getJSONArray("steps"); for (int i = 0; i < legs1.length(); i++) { JSONObject steps1 = legs1.getJSONObject(i); /* * if (i == 0) s = steps1.getString("start_location"); else */ s = steps1.getString("end_location"); // Toast.makeText(getApplicationContext(), " "+s, 6000).show(); s1 = s.substring(s.indexOf(":") + 1); // cut off beginning s = s1.substring(s1.indexOf(":") + 1, s1.indexOf("}")); // isolate // longitude s1 = s1.substring(0, s1.indexOf(",")); // isolate latitude s.replaceAll(" ", ""); // remove spaces s1.replaceAll(" ", ""); s2 = steps1.getString("html_instructions"); // Toast.makeText(getApplicationContext(), ""+s2, 4000).show(); dest = new Direction(Double.parseDouble(s), Double.parseDouble(s1), s2); directions.add(dest); }// for } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } }// getdirections void getAddress() { try { Geocoder gcd = new Geocoder(this, Locale.getDefault()); List
addresses = gcd.getFromLocation(lat, lng, 5);

if (addresses.size() > 0) {
/*
* for (int i = 0; i < addresses.size(); i++) { Address address
* = addresses.get(i);
*
* int maxIndex = address.getMaxAddressLineIndex(); for (int x =
* 0; x <= maxIndex; x++) {
* result.append(address.getAddressLine(x)); result.append(",");
* } result.append(address.getLocality()); result.append(",");
* result.append(address.getPostalCode());
* result.append("\n\n"); }
*/
Address address = addresses.get(0);

String source1 = address.getAddressLine(1);
source = source1.substring(0, source1.indexOf(",") );

//Toast.makeText(getApplicationContext(), source, 4000).show();
// result.append("" + lat + lng);

}
} catch (IOException ex) {
// editTextShowLocation.append(ex.getMessage().toString());
} catch (NullPointerException f) {

}
}

public class Direction {
public double lng = 0;
public double lat = 0;
public String txt = "";

public Direction(double latitude, double longitude, String written) {
lng = longitude;
lat = latitude;
txt = written;
}// constructor

}// direction class

@Override
public void onAccuracyChanged(int arg0, int arg1) {
// TODO Auto-generated method stub

}

@Override
public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub

}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
String lat1 = " " + (double) (location.getLatitude());
String lng1 = " " + (double) (location.getLongitude());
lat = Double.parseDouble(lat1);
lng = Double.parseDouble(lng1);

p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
place.setText("Name of Place" + " Ahmedabad");
getAddress();
directions.clear();
source_dir = new Direction(lat, lng, "s");
// dest = new Direction(20.25,
// 65.70, "d");
//
directions.add(source_dir);
// source.replaceAll(" ", "");
getDirections_online("http://maps.googleapis.com/maps/api/directions/json?origin="
+ source + "&destination=" + destination + "&sensor=false");

// directions.add(dest);

goToPoint();
showPosition();
// Toast.makeText(getApplicationContext(), source + destination, 4000)
// .show();
}

@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

}
// TODO: Fill In Methods Etc.
}// class

Thursday, 29 March 2012

passing string and receiving json data from php webserver(setting activity)

package com.qualcomm.QCARSamples.ImageTargets;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oauth.signpost.http.HttpResponse;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class SettingsActivity extends Activity {
String u_id;
String responseBody;
String[] items, errors;
List pairs;
HttpClient client;
HttpPost post;
HttpResponse response;
EditText email, homecity;
String result;
JSONArray jArray;
String email_string, city, facebook, twitter;
ProgressDialog dialog;
String URL = "http://www.travel.chemistree.in/admin/androidsupport/getsettings";
boolean flag = false, flag_saveclicked = false;
RadioButton yesfb, yestwitter, nofb, notwitter;
AlertDialog alertDialog;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
errors = new String[1];
errors[0]= "enter valid Email";
email = (EditText) findViewById(R.id.email);
homecity = (EditText) findViewById(R.id.homecity);
yesfb = (RadioButton) findViewById(R.id.yes_fb);
nofb = (RadioButton) findViewById(R.id.no_fb);
yestwitter = (RadioButton) findViewById(R.id.yes_twitter);
notwitter = (RadioButton) findViewById(R.id.no_twitter);
alertDialog = new AlertDialog.Builder(SettingsActivity.this).create();
alertDialog.setTitle("");

Bundle extras = getIntent().getExtras();

if (extras != null) {

u_id = extras.getString("u_id");

}
Button chuser = (Button) findViewById(R.id.changeuser);
chuser.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Intent intent = new Intent(SettingsActivity.this,
LoginActivity.class);
intent.putExtra("u_id", u_id);
startActivity(intent);

}
});

Button back = (Button) findViewById(R.id.back);
Button save = (Button) findViewById(R.id.save);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

Intent intent = new Intent(SettingsActivity.this,
ZoomByEnterPageActivity.class);
intent.putExtra("u_id", u_id);
startActivity(intent);

}
});
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
flag_saveclicked = true;
dialog = ProgressDialog.show(SettingsActivity.this, "",
"Loading Data ...Please Wait", true);
double TIMEOUT_MILLISEC = 1234567890;

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
(int) TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams,
(int) TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("u_id", u_id);

p.setParameter("key", "c89a7662dae613ea3d20d334339b6dff");
p.setParameter("submit", "Edit settings");
if (homecity.getText().equals(null)) {
p.setParameter("city", "null");
} else {
p.setParameter("city", homecity.getText().toString());
}
Validate validate = new Validate();
if (validate.Check_Lengh(email)) {

alertDialog.setMessage("Enter Email.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {

// here you can
// add functions

}
});
alertDialog.show();
} else if (validate.checkEmail(email) == false) {
alertDialog.setMessage("Enter Valid Email.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {

// here
// you
// can
// add
// functions

}
});
alertDialog.show();

} else {

p.setParameter("email", email.getText().toString());
}
if (nofb.isChecked()) {
facebook = "0";
} else {
facebook = "1";
}
if (notwitter.isChecked()) {
twitter = "0";
} else {
twitter = "1";
}
p.setParameter("facebook", facebook);
p.setParameter("twitter", twitter);

// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);

HttpPost httppost = new HttpPost(
"http://www.travel.chemistree.in/admin/androidsupport/updatesettings");

List nameValuePairs = new ArrayList(
7);
nameValuePairs.add(new BasicNameValuePair("u_id", u_id));

nameValuePairs.add(new BasicNameValuePair("key",
"c89a7662dae613ea3d20d334339b6dff"));
nameValuePairs.add(new BasicNameValuePair("submit",
"Edit settings"));
if (homecity.getText().equals(null)) {
// p.setParameter("city", "null");
nameValuePairs.add(new BasicNameValuePair("city", "null"));
} else {
// p.setParameter("city", homecity.getText().toString());
nameValuePairs.add(new BasicNameValuePair("city", homecity
.getText().toString()));
}
if (validate.Check_Lengh(email)) {

alertDialog.setMessage("Enter Email.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {

// here you can
// add functions

}
});
alertDialog.show();
} else if (validate.checkEmail(email) == false) {
alertDialog.setMessage("Enter Valid Email.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {

// here
// you
// can
// add
// functions

}
});
alertDialog.show();

} else {

// p.setParameter("email", email.getText().toString());
nameValuePairs.add(new BasicNameValuePair("email", email
.getText().toString()));
}
nameValuePairs
.add(new BasicNameValuePair("facebook", facebook));
nameValuePairs.add(new BasicNameValuePair("twitter", twitter));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) { // TODO
// Auto-generated
// catch
;
}

ResponseHandler responseHandler = new BasicResponseHandler();
try {
responseBody = httpclient
.execute(httppost, responseHandler);
Log.e("aaaaaaaaaaaaaaaaaaaaaaaaa+++",
responseBody.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// int start = responseBody.indexOf("{");
// int end = responseBody.length();
// String result = responseBody.substring(start, end);
// // Toast.makeText(getApplicationContext(), result,
// 9000).show();
// String result1 = "[" + result.toString().trim() + "]";
//
int start = responseBody.indexOf("status");
int end = responseBody.length();
String result = responseBody.substring(start, end);
// Toast.makeText(getApplicationContext(), result,
// 9000).show();
String result1 = "[{" + '"' + result.toString().trim()
+ "]";
// Toast.makeText(getApplicationContext(),
// result1.toString(), 14000).show();
//
try {
jArray = new JSONArray(result1.toString());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

try {
items = new String[jArray.length()];

for (int i = 0; i < jArray.length(); i++) { items[i] = jArray.getJSONObject(i) .getString("status").toString(); Log.e("item", items[i]); } /* * Toast.makeText(getApplicationContext(), * jArray.toString(), 4000) .show(); */ } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } if (items[0].equalsIgnoreCase("OK")) { try { email_string = jArray.getJSONObject(0).getString( "email"); city = jArray.getJSONObject(0).getString("city"); facebook = jArray.getJSONObject(0).getString( "facebook"); twitter = jArray.getJSONObject(0).getString( "twitter"); flag = true; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { errors[0] = jArray.getJSONObject(0) .getString("error").toString(); int start1 = errors[0].indexOf("["); int end1 = errors[0].length(); errors[0] = errors[0].substring(start1 + 1, end1 - 1); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ((dialog.isShowing())) dialog.dismiss(); Toast.makeText(getApplicationContext(), errors[0], 6000) .show(); } if (flag == true) { email.setText(email_string); if ((city.equals(null)) || (city.equalsIgnoreCase("null"))) { homecity.setText("city not entered"); } else { homecity.setText(city); } if (facebook.equalsIgnoreCase("0")) { nofb.setChecked(true); } else { yesfb.setChecked(true); } if (twitter.equalsIgnoreCase("0")) { notwitter.setChecked(true); } else { yestwitter.setChecked(true); } flag = false; if ((dialog.isShowing())) dialog.dismiss(); } } catch (NullPointerException e) { if ((dialog.isShowing())) dialog.dismiss(); Toast.makeText(getApplicationContext(), errors[0], 4000).show(); } } }); if (flag_saveclicked == false) { show_settings(); } } public void show_settings() { dialog = ProgressDialog.show(this, "", "Loading Data ...Please Wait", true); double TIMEOUT_MILLISEC = 1234567890; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, (int) TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, (int) TIMEOUT_MILLISEC); // HttpParams p = new BasicHttpParams(); // p.setParameter("name", pvo.getName()); p.setParameter("u_id", u_id); p.setParameter("key", "c89a7662dae613ea3d20d334339b6dff"); p.setParameter("submit", "View settings"); // Instantiate an HttpClient HttpClient httpclient = new DefaultHttpClient(p); HttpPost httppost = new HttpPost(URL); List nameValuePairs = new ArrayList(3);
nameValuePairs.add(new BasicNameValuePair("u_id", u_id));

nameValuePairs.add(new BasicNameValuePair("key",
"c89a7662dae613ea3d20d334339b6dff"));
nameValuePairs.add(new BasicNameValuePair("submit", "View settings"));

try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) { // TODO Auto-generated catch
;
}

ResponseHandler responseHandler = new BasicResponseHandler();
try {
responseBody = httpclient.execute(httppost, responseHandler);
Log.e("aaaaaaaaaaaaaaaaaaaaaaaaa+++", responseBody.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// int start = responseBody.indexOf("{");
// int end = responseBody.length();
// String result = responseBody.substring(start, end);
// // Toast.makeText(getApplicationContext(), result, 9000).show();
// String result1 = "[" + result.toString().trim() + "]";
//

int start = responseBody.indexOf("status");
int end = responseBody.length();
String result = responseBody.substring(start, end);
// Toast.makeText(getApplicationContext(), result, 9000).show();
String result1 = "[{" + '"' + result.toString().trim() + "]";

try {
jArray = new JSONArray(result1.toString());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}

try {
items = new String[jArray.length()];

for (int i = 0; i < jArray.length(); i++) { items[i] = jArray.getJSONObject(i).getString("status") .toString(); Log.e("item", items[i]); } /* * Toast.makeText(getApplicationContext(), jArray.toString(), * 4000) .show(); */ } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } if (items[0].equalsIgnoreCase("OK")) { try { email_string = jArray.getJSONObject(0).getString("email"); city = jArray.getJSONObject(0).getString("city"); facebook = jArray.getJSONObject(0).getString("facebook"); twitter = jArray.getJSONObject(0).getString("twitter"); flag = true; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if ((dialog.isShowing())) dialog.dismiss(); Toast.makeText(getApplicationContext(), "try after some time", 4000).show(); } if (flag == true) { email.setText(email_string); if ((city.equals(null)) || (city.equalsIgnoreCase("null"))) { homecity.setText("city not entered"); } else { homecity.setText(city); } if (facebook.equalsIgnoreCase("0")) { nofb.setChecked(true); } else { yesfb.setChecked(true); } if (twitter.equalsIgnoreCase("0")) { notwitter.setChecked(true); } else { yestwitter.setChecked(true); } flag = false; if ((dialog.isShowing())) dialog.dismiss(); } } catch (NullPointerException e) { if ((dialog.isShowing())) dialog.dismiss(); Toast.makeText(getApplicationContext(), "try after some time", 4000) .show(); } } public class Validate { public boolean Check_Lengh(EditText editText) { boolean validated = false; String text = editText.getText().toString().trim(); if (text.length() == 0) { editText.setText(text); validated = true; } return validated; } public boolean checkEmail(EditText inputMail) { boolean validated; Pattern p = Pattern.compile(".+@.+\\.[a-z]+"); Matcher m = p.matcher(inputMail.getText()); boolean matchFound = m.matches(); StringTokenizer st = new StringTokenizer(inputMail.toString(), "."); String lastToken = null; while (st.hasMoreTokens()) { lastToken = st.nextToken(); } if (matchFound && lastToken.length() >= 2
&& inputMail.length() - 1 != lastToken.length()) {

// validate the country code
validated = true;
} else
validated = false;

// Log.v("log_tag", "on " + validated);

return validated;
}

}

}
================xml======================












Wednesday, 21 March 2012

mainscreen for tabactivity zoombypageactivity

mainfirstscreen for tabactivity file zoombypageactivity file is having no tab containing file,other widget xml codes are written since tab is created using pure java code.