Implement geocoding in android 2.2 - java

Friends...
i'm woking on a project on geocoding.I tried to implement it several times.But i'm not able to retrieve the latitude and longitude values corresponding to a location.Please help me out to complete my project..

try this code hope this will help you:
package com.example.map;
import java.util.List;
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 android.app.AlertDialog;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class mapView extends MapActivity{
MapView myMap;
Button btnSearch;
EditText adress;
Geocoder gc;
double lat;
double lon;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myMap = (MapView) findViewById(R.id.simpleGM_map); // Get map from XML
btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); // Get button from xml
adress = (EditText) findViewById(R.id.simpleGM_adress); // Get address from XML
gc = new Geocoder(this); // create new geocoder instance
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String addressInput = adress.getText().toString(); // Get input text
try
{
List<Address> foundAdresses = gc.getFromLocationName(
addressInput, 5); // Search addresses
if (foundAdresses.size() == 0)
{ // if no address found,
// display an error
Dialog locationError = new AlertDialog.Builder(
mapView.this).setIcon(0).setTitle(
"Error").setPositiveButton(R.string.ok, null)
.setMessage(
"Sorry, your address doesn't exist.")
.create();
locationError.show();
}
else
{ // else display address on map
for (int i = 0; i < foundAdresses.size(); ++i)
{
// Save results as Longitude and Latitude
// #todo: if more than one result, then show a
// select-list
Address x = foundAdresses.get(i);
lat = x.getLatitude();
lon = x.getLongitude();
}
navigateToLocation((lat * 1000000), (lon * 1000000),
myMap); // display the found address
}
}
catch (Exception e)
{
// #todo: Show error message
}
}
});
}
#Override
protected boolean isRouteDisplayed()
{
// TODO Auto-generated method stub
return false;
}
/
* Navigates a given MapView to the specified Longitude and Latitude
* #param latitude
* #param longitude
* #param mv
*/
public static void navigateToLocation(double latitude, double longitude,
MapView mv)
{
GeoPoint p = new GeoPoint((int) latitude, (int) longitude); // new
// GeoPoint
mv.displayZoomControls(true); // display Zoom (seems that it doesn't
// work yet)
MapController mc = mv.getController();
mc.animateTo(p); // move map to the given point
int zoomlevel = mv.getMaxZoomLevel(); // detect maximum zoom level
mc.setZoom(zoomlevel - 1); // zoom
mv.setSatellite(false); // display only "normal" mapview
}
}

Related

Calculate Time and distance and draw a path between two draggable markers in Google maps v2

Need your help!!..I am building an android app using Google API V2. I have managed to place two markers on the map and also get there location. What I mainly want to do now is to calculate their distance and time like we do in the Google maps and draw a path between them. How can I achieve that?
a-) Can I do it without using JSON? I just know JAVA not java script so help please.
b-) Who ever answer it, Please if you can, Elaborate the steps taken in the code comments?
Here is my Maps ACtivity
--
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener,GoogleMap.OnMarkerClickListener, GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener {
private GoogleApiClient mGoogleApiClient;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
private LocationRequest LocationDrop;
// TextView currentloc;
String filterAddress = "";
String DropoffAdress = "";
String DraggedDroppOff= "";
String dragendaddress = "";
// TextView dropOffaddress;
double currentLatitude;
double currentLongitude;
double draglat;
double draglng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// tvLocInfo = (TextView) findViewById(R.id.locinfo);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
// LocationDrop = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10 * 1000).setFastestInterval(1 * 1000);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
// mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Pick Me").snippet(filterAddress));
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
}
else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions optionsA = new MarkerOptions().position(latLng).title("Pick Me").snippet(filterAddress).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMap.addMarker(optionsA).setDraggable(false);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
// mMap.moveCamera(center);
mMap.animateCamera(zoom);
// mMap.setOnMarkerDragListener();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(currentLatitude,currentLongitude,1);
// List<Address> dropaddress = geoCoder.getFromLocation(laterLongitut,laterlatitude,1);
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
filterAddress += addresses.get(0).getAddressLine(i) + " ";
Log.e("My current address is 2", filterAddress );
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
// currentloc = (TextView) findViewById(R.id.txmarker);
// currentloc.setText("Address" + filterAddress);
Log.e("My current address is 1", filterAddress);
// Log.e("My later address is 2", DropoffAdress );
Toast.makeText(getBaseContext(),filterAddress,Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public void onBackPressed(){
Intent intent = new Intent(this,TurnOnGps.class);
startActivity(intent);
setContentView(R.layout.activity_turn_on_gps);
}
#Override
public void onInfoWindowClick(Marker marker) {
marker.setTitle(filterAddress);
}
#Override
public void onMapLongClick(LatLng latLng) {
MarkerOptions options2 = new MarkerOptions();
options2.position(latLng);
options2.title("Drop ME").snippet("Dragg Me ");
options2.draggable(true);
mMap.addMarker(options2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
Toast.makeText(getBaseContext(),"Please Drag Marker to set your Drop OFF",Toast.LENGTH_LONG).show();
// mMap.moveCamera(center);
mMap.animateCamera(zoom);
/* double updateddroplat = latLng.latitude;
double updateddroplng = latLng.longitude;
//Converting the latlngs to a string through geoencoder
LatLng latLng1 = new LatLng(updateddroplat,updateddroplng);
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(updateddroplat,updateddroplng,1);
if(addresses.size() > 0){
for (int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
DropoffAdress += addresses.get(0).getAddressLine(i) + "";
Log.e("My DroppOff Location is" , DropoffAdress);
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
Log.e("My DropOff Location is" , DropoffAdress);
Toast.makeText(getBaseContext(),DropoffAdress,Toast.LENGTH_LONG).show();
*/
}
#Override
public void onMarkerDragStart(Marker marker) {
marker.setSnippet("Please Drag me to set your Drop OFF");
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
DropoffAdress = dragendaddress;
Log.e("My DroppOff Location is" , DraggedDroppOff);
LatLng dragposition = marker.getPosition();
draglat = dragposition.latitude;
draglng = dragposition.longitude;
LatLng latLng1 = new LatLng(draglat, draglng);
marker.getId();
// marker.getSnippet();
marker.setSnippet(dragendaddress);
marker.setTitle("Drop ME");
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(draglat,draglng,1);
if(addresses.size() > 0){
for (int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++){
dragendaddress += addresses.get(0).getAddressLine(i) + "";
Log.e("My DroppOff Location is", dragendaddress);
}
Toast.makeText(getBaseContext(),dragendaddress,Toast.LENGTH_LONG).show();
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
}
#Override
public boolean onMarkerClick(Marker marker ) {
Log.e("am in markerclick event","");
String Title = marker.getTitle();
String Snippet = marker.getSnippet();
Log.e("I am in onMarkerClick", Title);
if(Title.equals("Pick Me")){
marker.setSnippet(filterAddress);
Toast.makeText(getBaseContext(),filterAddress,Toast.LENGTH_LONG).show();
Log.e("I am in onMarkerClick", Title);
}else if(Title.equals("Drop ME")){
marker.setSnippet(dragendaddress);
Toast.makeText(getBaseContext(),dragendaddress,Toast.LENGTH_LONG).show();
}
try {
Polyline polyline = mMap.addPolyline(new PolylineOptions().add(new LatLng(currentLatitude, currentLongitude), new LatLng(draglat, draglng)).width(10).color(Color.RED));
}catch (Exception e){
e.printStackTrace();
}
return false;
}
calculating the distance ::
public float distance (LatLng point1, LatLng point2 )
{
double earthRadius = 3958.75;
double latDiff = Math.toRadians(point2.latitude - point1.latitude);
double lngDiff = Math.toRadians(point2.longitude - point2.longitude);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(point1.latitude)) * Math.cos(Math.toRadians(point2.latitude)) *
Math.sin(lngDiff /2) * Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance).floatValue();
}
and to draw a line add the points to a list then use the polyline function .
Ok Firstly thanks all you guys for being a support. I finally got the solution to my problem with blessings and a bit of my own RND..
http://wptrafficanalyzer.in/blog/route-between-two-locations-with-waypoints-in-google-map-android-api-v2/
This greatly solved the Direction Parsing issue.
And i molded my code and added the methods from the Maps activity and JSON class.
Which solved the problem.
Happy :)
Thanks for taking the time..
+Any one having the same issue can post there problem in the comments i would try to answer it. Through what ever small i have learnt from solving this problem..
You can use code here. In this code distanceText gives distance between two points and timeText gives travelling time.

How to track the distance when user running/ walking

Im currently doing an apps that can track running distance.
My idea is when i click start, i will record the position that i start running, then when i click stop, it will record the position that i end my running. Then calculate the distance between this 2 point.
I don't know why my distance result keep showing me 0km no matter how i run. Please help me see if gt any problems~
package com.example.ifitness;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.SupportMapFragment;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class calorieburn extends ActionBarActivity implements LocationListener{
private GoogleMap map;
private Location startLocation;
private Location endLocation;
private double latA;
private double longA;
private double latB;
private double longB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calorieburn);
SetupMap();
Button start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
latA = startLocation.getLatitude();
longA = startLocation.getLongitude();
TextView distance = (TextView) findViewById(R.id.distance);
distance.setText("0 km");
TextView calorie = (TextView) findViewById(R.id.calorie);
calorie.setText("0 cal");
}
});
Button stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
latB = endLocation.getLatitude();
longB = endLocation.getLongitude();
TextView distance = (TextView) findViewById(R.id.distance);
distance.setText(String.valueOf(distance(latA,longA,latB,longB)+ "km"));
TextView calorie = (TextView) findViewById(R.id.calorie);
calorie.setText(String.valueOf(distance(latA,longA,latB,longB)+ "cal"));
}
});
}
public double calories(double distance){
double calories = 0;
calories = distance * 100;
return calories;
}
public static void distanceBetween(){
}
public double distance(double lat,double lng,double latitude,double longtitude){
Location locA = new Location("locA");
locA.setLatitude(lat);
locA.setLongitude(lng);
Location locB = new Location("locB");
locB.setLatitude(latitude);
locB.setLongitude(longtitude);
double distance = locA.distanceTo(locB);
return distance;
}
private void SetupMap() {
if (map == null){
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// get google map from the fragment
map = mf.getMap();
}
if (map !=null ){
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestprovider = lm.getBestProvider(criteria,false);
String provider = LocationManager.NETWORK_PROVIDER;
if (provider == null){
onProviderDisabled(provider);
}
// Getting Current Location
Location loc = lm.getLastKnownLocation(bestprovider);
if (loc != null){
onLocationChanged(loc);
}
map.setOnMapLongClickListener(onLongClickMapSettings());
}
}
private OnMapLongClickListener onLongClickMapSettings() {
// TODO Auto-generated method stub
return new OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
Log.i(arg0.toString(), "User Long CLicked");
}
};
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(17));
}
private void makeUseOfNewLocation(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}

Putting current location into maps application

I am trying to add a way of viewing my current location to my application and can't figure out how to do it without getting errors. I currently have the two incorrectly stored in separate activities (Markers locations in one activity and my location in other activity) and can't seem to combine them.
Sorry about the poor attempt at describing my problem, hopefully this code will help more.
MainActivity
package com.kieranmaps.v2maps;
import java.util.Hashtable;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.app.ActivityManager;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kieranmaps.v2maps.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.FIFOLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
public class MainActivity extends FragmentActivity {
private GoogleMap googleMap;
private final LatLng OREILLYS = new LatLng(53.348347, -6.254119);
private final LatLng LAGOONA = new LatLng(53.349810, -6.243160);
private final LatLng COPPERS = new LatLng (53.335356, -6.263481);
private final LatLng WRIGHTS = new LatLng (53.445491, -6.223857);
private final LatLng ACADEMY = new LatLng (53.348045,-6.26198);
private final LatLng DICEYS = new LatLng (53.347250, -6.254198);
private final LatLng PYGMALION = new LatLng (53.342183,-6.262358);
private final LatLng FIBBERS = new LatLng (53.352799,-6.260412);
// private final LatLng TEST = new LatLng (5352799,-6.260412);
private Marker marker;
private Hashtable<String, String> markers;
private ImageLoader imageLoader;
private DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
initImageLoader();
markers = new Hashtable<String, String>();
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher) // Display Stub Image
.showImageForEmptyUri(R.drawable.ic_launcher) // If Empty image found
.cacheInMemory()
.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
if ( googleMap != null ) {
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
final Marker oreillys = googleMap.addMarker(new MarkerOptions().position(OREILLYS)
.title("O Reillys"));
markers.put(oreillys.getId(), "http://img.india-forums.com/images/100x100/37525-a-still-image-of-akshay-kumar.jpg");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OREILLYS, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
final Marker coppers = googleMap.addMarker(new MarkerOptions().position(COPPERS)
.title("Coppers"));
markers.put(coppers.getId(), "http://f3.thejournal.ie/media/2011/11/coppers1-390x285.png");
final Marker wrights = googleMap.addMarker(new MarkerOptions().position(WRIGHTS)
.title("The Wright Venue"));
markers.put(wrights.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker lagoona = googleMap.addMarker(new MarkerOptions().position(LAGOONA)
.title("The Lagoona"));
markers.put(lagoona.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker academy = googleMap.addMarker(new MarkerOptions().position(ACADEMY)
.title("The Academy"));
markers.put(academy.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker pygmalion = googleMap.addMarker(new MarkerOptions().position(PYGMALION)
.title("The Pygmalion"));
markers.put(pygmalion.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker fibbers = googleMap.addMarker(new MarkerOptions().position(FIBBERS)
.title("Fibbers"));
markers.put(fibbers.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker diceys = googleMap.addMarker(new MarkerOptions().position(DICEYS)
.title("Dicey's"));
markers.put(diceys.getId(), "https://dublinnow.files.wordpress.com/2012/05/diceys.jpg");
/* final Marker diceys = googleMap.addMarker(new MarkerOptions()
.position(DICEYS)
.title("Diceys")
.snippet("Drink Deal: 3.50. Adm: 5, Performance: Gen"));
Marker marker = GoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Title")
.snippet("Snippet")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker))); */
//marker.showInfoWindow();
}
}
private class CustomInfoWindowAdapter implements InfoWindowAdapter {
private View view;
public CustomInfoWindowAdapter() {
view = getLayoutInflater().inflate(R.layout.custom_info_window,
null);
}
#Override
public View getInfoContents(Marker marker) {
if (MainActivity.this.marker != null
&& MainActivity.this.marker.isInfoWindowShown()) {
MainActivity.this.marker.hideInfoWindow();
MainActivity.this.marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(final Marker marker) {
MainActivity.this.marker = marker;
String url = null;
if (marker.getId() != null && markers != null && markers.size() > 0) {
if ( markers.get(marker.getId()) != null &&
markers.get(marker.getId()) != null) {
url = markers.get(marker.getId());
}
}
final ImageView image = ((ImageView) view.findViewById(R.id.badge));
if (url != null && !url.equalsIgnoreCase("null")
&& !url.equalsIgnoreCase("")) {
imageLoader.displayImage(url, image, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view,
loadedImage);
getInfoContents(marker);
}
});
} else {
image.setImageResource(R.drawable.ic_launcher);
}
//
final String title = marker.getTitle();
final TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
titleUi.setText(title);
} else {
titleUi.setText("");
}
final String snippet = marker.getSnippet();
final TextView snippetUi = ((TextView) view
.findViewById(R.id.snippet));
if (snippet != null) {
snippetUi.setText(snippet);
} else {
snippetUi.setText("");
}
return view;
}
}
private void initImageLoader() {
int memoryCacheSize;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
int memClass = ((ActivityManager)
getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
memoryCacheSize = (memClass / 8) * 1024 * 1024;
} else {
memoryCacheSize = 2 * 1024 * 1024;
}
final ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).threadPoolSize(5)
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(memoryCacheSize)
.memoryCache(new FIFOLimitedMemoryCache(memoryCacheSize-1000000))
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
ImageLoader.getInstance().init(config);
}
}
NewActivity:
package com.kieranmaps.v2maps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class NewActivity extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
private double sourceLatitude, sourceLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
10, 0, mlocListener);
// // Setting onclick event listener for the map
// map.setOnMapClickListener(new OnMapClickListener() {
//
// #Override
// public void onMapClick(LatLng point) {
//
// Toast.makeText(getApplicationContext(), "Clicked !", Toast.LENGTH_SHORT).show();
//
// // Already two locations
// if(markerPoints.size()>1){
// markerPoints.clear();
// map.clear();
// }
//
// // Adding new item to the ArrayList
// markerPoints.add(point);
//
// // Creating MarkerOptions
// MarkerOptions options = new MarkerOptions();
//
// // Setting the position of the marker
// options.position(point);
//
// /**
// * For the start location, the color of marker is GREEN and
// * for the end location, the color of marker is RED.
// */
// if(markerPoints.size()==1){
// options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// }else if(markerPoints.size()==2){
// options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// }
//
//
// // Add new marker to the Google Map Android API V2
// map.addMarker(options);
//
// // Checks, whether start and end locations are captured
// if(markerPoints.size() >= 2){
// LatLng origin = markerPoints.get(0);
// LatLng dest = markerPoints.get(1);
//
// // Getting URL to the Google Directions API
// String url = getDirectionsUrl(origin, dest);
//
// DownloadTask downloadTask = new DownloadTask();
//
// // Start downloading json data from Google Directions API
// downloadTask.execute(url);
// }
//
// }
// });
}
private void sourceTodestination() {
// Source
LatLng point = new LatLng(sourceLatitude, sourceLongitude);
// Destination
double destLatitude = 23.7383;
double destLongitude = 90.3958;
LatLng point1 = new LatLng(destLatitude, destLongitude);
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng((sourceLatitude + destLatitude)/2, (sourceLongitude + destLongitude)/2));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(13);
map.moveCamera(center);
map.animateCamera(zoom);
// Adding new item to the ArrayList
markerPoints.add(point);
markerPoints.add(point1);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
MarkerOptions options1 = new MarkerOptions();
options1.position(point1);
options1.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// Add new marker to the Google Map Android API V2
map.addMarker(options);
map.addMarker(options1);
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
sourceLatitude = loc.getLatitude();
sourceLongitude = loc.getLongitude();
sourceTodestination();
Toast.makeText(getApplicationContext(), sourceLatitude + " - " + sourceLongitude,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
android.util.Log.v("", "Latitud = ");
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
android.util.Log.v("", "status = ");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSON Parser
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Forgive me for my ignorance but I can't figure out how to get it working with both of these. Any tips appreciated! thanks
edit: More details, I can only get this working showing the locations but I can't get it to show my current location and route to those destinations
Your current location is the loc from this method
public void onLocationChanged(Location loc)
apply accuracy to your loc location to get a accurate location. accuracy threshold is up to you. less than 30m is fine.

Android collect and send data

I am working on application where I need to collect accelerometer and location data & send them over web-server. I have to collect the data on sensor changed event. Right now I am trying to collect it when I click on start button, but somehow I don't see that data getting stored in my file. Could anyone help me with this ?
I have to send this data to MySQL database for processing (on web-server). How will I send the data over to server?
Here is what I have tried right now :
package myapp;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import app.AccelLocData;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapViewActivity extends Activity implements LocationListener,
SensorEventListener, OnClickListener {
GoogleMap googleMap;
private boolean started = false;
private ArrayList<AccelLocData> sensorData;
private SensorManager sensorManager;
private Button btnStart, btnStop;
private String provider;
// private Button btnUpload;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorData = new ArrayList<AccelLocData>();
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
googleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : "
+ latLng.longitude);
// Clears the previously touched position
googleMap.clear();
// Animating to the touched position
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
// Placing a marker on the touched position
googleMap.addMarker(markerOptions);
}
});
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locManager.getBestProvider(criteria, true);
Location location = locManager.getLastKnownLocation(provider);
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
AccelLocData data = new AccelLocData(timestamp, x, y, z, latitude,
longitude);
// System.out.println("Accel Data:" + data.toString());
// System.out.println("Latitude:" + latitude);
// System.out.println("Longitude:" + longitude);
sensorData.add(data);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
System.out.println("Latitude:" + latitude + ", Longitude:" + longitude);
// Setting latitude and longitude in the TextView tv_location
// tvLocation.setText("Latitude:" + latitude + ", Longitude:" +
// longitude);
}
#Override
public void onProviderDisabled(String arg0) {
// 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
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
btnStart.setEnabled(false);
btnStop.setEnabled(true);
// btnUpload.setEnabled(false);
// sensorData = new ArrayList<AccelLocData>();
// save prev data if available
started = true;
try {
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myapp");
dir.mkdirs();
File sensorFile = new File(dir, "acc.txt");
// sensorFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(sensorFile);
ObjectOutputStream myOutWriter = new ObjectOutputStream(fOut);
System.out.println("Sensor data size:"+sensorData.size());
for(int i=0;i<sensorData.size();i++){
System.out.println("Sensor Data:" + sensorData.get(i).getX());
}
myOutWriter.writeObject(sensorData);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
Sensor accel = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accel,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
btnStart.setEnabled(true);
btnStop.setEnabled(false);
// btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
// don't need chart
// openChart();
// show data in chart
break;
// case R.id.btnUpload:
// break;
default:
break;
}
}
}
In your activity put this into your OnClick of your Startbutton:
startService(new Intent(this, BackgroundService.class));
and this to your Stopbutton:
stopService(new Intent(this, BackgroundService.class));
Create a new Class for example like the following:
public class BackgroundService extends Service implements LocationListener,
SensorEventListener{
//Hint: there are some methods you need to implement which I forgot to mention but eclipse will add them for you
#Override
public void onCreate() {
//enable networking, look into this: http://www.vogella.com/blog/2012/02/22/android-strictmode-networkonmainthreadexception/
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//do your data collecting-methods and connect to your webserver
}
#Override
public void onDestroy() {
//unregister your sensor listener
}
}
In this method I got this:
#Override
public void onSensorChanged(SensorEvent event) {
sendValuesToYourServer(Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) +","+ Float.toString(event.values[2]));
}

List isn't populating

I'm making an app that will list addresses nearby in a listview, but for some reason the addresses aren't going into the list. Am I missing something with the address collection or?...
It happens within the for loop. I want it to read the list of addresses I get and trim the information I want to only necessary bits, like street numbers and zip codes instead of the big mess of numbers.
Every time I run the app however, the list remains blank.
package com.atonea.ps;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
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.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class PSActivity extends Activity {
protected static final Location Location = null;
/** Called when the activity is first created. */
String location_text="";
String here="";
final ArrayList<String> addressbook = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button goButton = (Button) findViewById(R.id.beginButton);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(crta, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateWithNewLocation(Location location) {
String latLong;
TextView uhoh = (TextView) findViewById(R.id.texty);
ListView listview = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, addressbook);
listview.setAdapter(arrayAdapter);
String addressString = "no address found";
Address fulladdress;
String street;
String zip;
String addresstogether;
if(location!=null) {
double lat = location.getLatitude();
double lon = location.getLongitude();
latLong = "Lat:" + lat + "\nLong:" + lon;
double lattitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this,Locale.getDefault());
try {
List addresses= gc.getFromLocation(lattitude, longitude, 1);
if(addresses.size()>0) {
for (int a = 0; a > 6; a++) {
fulladdress = ((Address) addresses.get(a));
street = fulladdress.getAddressLine(a);
zip = fulladdress.getPostalCode();
addresstogether = street+" "+zip;
addressbook.add(a, addresstogether);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),addresstogether, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
}
} else {
latLong = " NO Location Found ";
}
uhoh.setText("your Current Position is :\n" +latLong + "\n " + addressString );
}
}
for (int a = 0; a > 6; a++) {
You are never going to enter this loop. You start with 0 which is always smaller than 6.
This condition for (int a = 0; a > 6; a++) is not correct.
As you have initialized a with 0 and then checking a > 6 it will always be false and your program will never get in the loop.
It must be for (int a = 0; a < 6; a++).

Categories

Resources