Android collect and send data - java

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]));
}

Related

How to send map long and lat with more details to firebase?

In this code, I need to send name and number to the location database with the map's long and lat. Marker's long and lat sending to the firebase without any issue but name and number not sending to the firebase. I cannot find the issue of the code because in the logcat there are not showing any issue. Can you please help me to fix this.
package com.example.policeemergencysystem;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import android.os.Build;
import android.os.Bundle;
import com.example.policeemergencysystem.Prevelant.Prevelant;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.policeemergencysystem.Model.AdminOrders;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
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.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.policeemergencysystem.Prevelant.Prevelant;
import com.google.firebase.database.ValueEventListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
private GoogleMap mMap;
private Button doneBtn;
TextView backBtn;
Marker myMarker;
LocationManager locationManager;
private static final String TAG = "MainActivity";
private String name;
private String userID = "", userNAME = "", userPHONE = "";
DatabaseReference ordersRef = FirebaseDatabase.getInstance().getReference()
.child("Location")
.child(Prevelant.currentOnlineUser.getUsername());
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
doneBtn = (Button) findViewById(R.id.doneBtn);
backBtn = (TextView) findViewById(R.id.backBtn);
userID = getIntent().getStringExtra("uid");
userNAME = getIntent().getStringExtra("uname");
userPHONE = getIntent().getStringExtra("uphone");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10);
mLocationRequest.setSmallestDisplacement(10);
mLocationRequest.setFastestInterval(10);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new
LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
Task<LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());
task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
// All location settings are satisfied. The client can initialize location
// requests here.
} catch (ApiException exception) {
switch (exception.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the
// user a dialog.
try {
// Cast to a resolvable exception.
ResolvableApiException resolvable = (ResolvableApiException) exception;
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
resolvable.startResolutionForResult(
MapsActivity.this,
101);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
} catch (ClassCastException e) {
// Ignore, should be an impossible error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
}
});
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//Check whether the network provider is enabled
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Get the Latitude
double latitude = location.getLatitude();
//Get the Longitude
double longitude = location.getLongitude();
//Instantiate the class, LatLng
LatLng latLng = new LatLng(latitude, longitude);
//Instantiate the class, GeoCoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality()+",";
str += addressList.get(0).getCountryName()+",";
str += addressList.get(0).getPostalCode();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.0f));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Get the Latitude
double latitude = location.getLatitude();
//Get the Longitude
double longitude = location.getLongitude();
//Instantiate the class, LatLng
LatLng latLng = new LatLng(latitude, longitude);
String name = new String(Prevelant.currentOnlineUser.getUsername());
//Instantiate the class, GeoCoder
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getLocality()+",";
str += addressList.get(0).getCountryName()+",";
str += addressList.get(0).getPostalCode();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng)
.zoom(17).build();
//Zoom in and animate the camera.
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case 101:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
Toast.makeText(MapsActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(MapsActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Please be patience until we find your current location...", Toast.LENGTH_SHORT).show();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
// First check if myMarker is null
if (myMarker == null) {
// Marker was not set yet. Add marker:
myMarker = googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Accidnet Location")
.snippet("Put the marker to your accident location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
doneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MapsActivity.this, "Your location has been placed!", Toast.LENGTH_SHORT).show();
HashMap<String, Object> userMap = new HashMap<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Location").child(Prevelant.currentOnlineUser.getUsername());
myRef.child("name").setValue(userNAME);
myRef.child("phone").setValue(userPHONE);
myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(userMap);
finish();
Intent intent = new Intent(MapsActivity.this, LoginActivity.class);
startActivity(intent);
}
});
} else {
// Marker already exists, just update it's position
myMarker.setPosition(latLng);
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude);
}
HashMap<String, Object> adminMap = new HashMap<>();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Location").child(Prevelant.currentOnlineUser.getUsername());
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude);
myRef.child("latitude").setValue(myLatLng.latitude);
myRef.child("longitude").setValue(myLatLng.longitude);
myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(adminMap);
}
});
}
}

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
}
}

Android App Crash with NullPointerException

I am getting weather info in my app and had it working. Now I am getting a null pointer exception and I'm not sure why, especially since it was working and I haven't changed any of this code.
package com.kentuckyfarmbureau.kyfb;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class WeatherLocation extends Activity
{
EditText locationText;
TextView label;
Button getWeather;
String enteredText;
String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=%s&format=json&num_of_days=5&key=37a5fj42xpyptvjgkhrx5rwu";
String newURL;
String currentLocationText;
LocationManager lm;
Location location;
double longitude;
double latitude;
String longString;
String latString;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.weatherlocation);
locationText = (EditText) findViewById(R.id.locationTextView);
label = (TextView) findViewById(R.id.label);
getWeather = (Button) findViewById(R.id.showWeather);
locationText.setText("Current Location");
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
longString = String.valueOf(longitude);
latString = String.valueOf(latitude);
currentLocationText = (latString + "+" + longString);
enteredText = currentLocationText;
newURL = String.format(url, enteredText);
locationText.setOnEditorActionListener(new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE)
{
if(locationText.getText().toString().equals("Current Location"))
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
longString = String.valueOf(longitude);
latString = String.valueOf(latitude);
currentLocationText = (latString + "+" + longString);
enteredText = currentLocationText;
}
else
{
enteredText = locationText.getText().toString();
enteredText = enteredText.replaceAll(" ", "+");
}
System.out.println(enteredText);
// hide the virtual keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.RESULT_UNCHANGED_SHOWN);
newURL = String.format(url, enteredText);
System.out.println("Formatted URL: " + newURL);
handled = true;
}
return handled;
}
});
// Get Weather button
getWeather.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent weather = new Intent(WeatherLocation.this, Weather.class);
weather.putExtra("INTENT_KEY_URL", newURL);
weather.putExtra("CURRENT_LOCATION", locationText.getText().toString());
startActivity(weather);
}
});
}
}
The problem seems to be line 48, longitude = location.getLongitude();
If line 48 is causing the issues, then most likely your
location is null. This can be null if you call getLastKnownLocation() while the provider is disabled as noted in the android documentation.
I fixed this by adding a location listener.
final LocationListener locationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location currentLocation)
{
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
And adding:
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener);

How to Disable Android LocationListener when application is closed

I have a class which handle a location service called MyLocationManager.java
this is the code :
package com.syariati.childzone;
import java.util.List;
import java.util.Locale;
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.widget.Toast;
public class MyLocationManager {
private Context context;
private double myLat = 0.0;
private double myLon = 0.0;
private LocationManager locationManager = null;
private Location location = null;
private Criteria criteria;
private String locationName = null;
public MyLocationManager(Context ctx) {
this.context = ctx;
}
private String setCriteria() {
this.criteria = new Criteria();
this.criteria.setAccuracy(Criteria.ACCURACY_FINE);
this.criteria.setAltitudeRequired(false);
this.criteria.setBearingRequired(false);
this.criteria.setCostAllowed(true);
this.criteria.setPowerRequirement(Criteria.POWER_LOW);
return locationManager.getBestProvider(criteria, true);
}
public double getMyLatitude() {
return this.myLat;
}
public double getMyLongitude() {
return this.myLon;
}
public String getLocation() {
return this.locationName;
}
public void onLocationUpdate() {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
String provider = setCriteria();
location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 1000, 0,
new MyLocationListener());
}
private void updateWithNewLocation(Location location) {
if (location != null) {
this.myLat = location.getLatitude();
this.myLon = location.getLongitude();
// Toast.makeText(this.context,
// "Lokasi Anda:\n" + this.myLat + "\n" + this.myLon,
// Toast.LENGTH_LONG).show();
getLocationName(this.myLat, this.myLon);
} else {
Toast.makeText(this.context, "Lokasi Anda Tidak Diketahui",
Toast.LENGTH_SHORT).show();
}
}
private void getLocationName(double lat, double lon) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> adresses = geocoder.getFromLocation(lat, lon, 1);
StringBuilder sb = new StringBuilder();
if (adresses.size() > 0) {
Address address = adresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getCountryName()).append("\n");
}
this.locationName = sb.toString();
// Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location newLocation) {
// TODO Auto-generated method stub
myLat = newLocation.getLatitude();
myLon = newLocation.getLongitude();
getLocationName(myLat, myLon);
Toast.makeText(context,
"Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
which has an Inner class that implements location listener on it. So far, it works. It listen the location with no problem. However, when I exit my apps, it doesn't completely stop the listen the location. As you see from this code :
#Override
public void onLocationChanged(Location newLocation) {
// TODO Auto-generated method stub
myLat = newLocation.getLatitude();
myLon = newLocation.getLongitude();
getLocationName(myLat, myLon);
Toast.makeText(context,
"Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
Toast.LENGTH_SHORT).show();
}
while the location is updated, the toast will be shown, and it still appear when the location is updated. Even when I've closed the application.
How to stop the location listener completely in my case.
This one helped me to stop the updat :
android how to stop gps
You may call removeUpdates on your LocationManager.
public void removeUpdates (PendingIntent intent)
Removes any current registration for location updates of the current
activity with the given PendingIntent. Following this call, updates
will no longer occur for this intent.
Parameters:
intent {#link PendingIntent} object that no longer needs location
updates
Throws:
IllegalArgumentException if intent is null
See here: http://developer.android.com/reference/android/location/LocationManager.html#removeUpdates(android.app.PendingIntent)
Updated:
In this case, you may change this line:
locationManager.requestLocationUpdates(provider, 1000, 0,
new MyLocationListener());
to:
MyLocationListener myLL = new MyLocationListener();
locationManager.requestLocationUpdates(provider, 1000, 0,
myLL);
When you want to remove your listener call as below:
locationManager.removeUpdates(myLL);

Categories

Resources