got some errors when using "requesLocationUpdates()" - java

I have an app which shows users current coordinates and update it as every 5 meters.
but i have problem in the line which i call for "requestLocationUpdates" which is in this line:
Location location1 = locationManager.requestLocationUpdates(GpsProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
.
if i place Context as last parameter i will get an error which tells(note that "GpsTracker" is my Main Activity) :
"Cannot resolve method 'requestLocationUpdates(java.lang.String, int, long, com.project.gpstrackerr.GpsTracker)'"
and if i place my locationlistener i will get an error which tells:
Incompatible types.
Required:android.location.Location
Found:void
here is my Full code of my GpsTracker Activity(which is my Main Activity)
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GpsTracker extends Activity
{
public static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 20;
boolean isGPSEnabled = false, isNetworkEnabled = false;
boolean isGPSEnabled2 = false, isNetworkEnabled2 = false;
DatabaseTable cn;
DatabaseManager db = new DatabaseManager(this);
HttpClass JSONSaver = new HttpClass();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
Context context = GpsTracker.this;
LocationManager locationManager, locationManagerCHECK;
TextView ET_Coordinates, ET_NU;
ListView listView;
//for Coordinates details in Location Listener
double latitude;
double longitude;
String Date;
//for Getting Coordinates details
String strLat, strLong, strDate;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Show Last Known Location
ShowLastKnownLocation();
String NetworkProvider = LocationManager.NETWORK_PROVIDER;
String GpsProvider = LocationManager.GPS_PROVIDER;
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled2 = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled2 = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public LocationListener mylocationListener = new LocationListener()
{
#Override
public void onLocationChanged(Location location)
{
Date date = new Date();
Date = dateFormat.format(date);
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText(GpsTracker.this, "Provide Status Changed" + "\n"
+ "Provider: " + provider + "\n"
+ "Status: " + status + "\n"
+ "Extras: " + extras + ".",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText(GpsTracker.this,
"Provider Turned ON!", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText(GpsTracker.this,
"Provider is OFF!", Toast.LENGTH_SHORT).show();
}
};
protected void showUpdatedLocation(boolean checkGPSEnabled, boolean checkNetworkEnabled, String NetworkProvider, String GpsProvider, LocationManager locationManager)
{
if (checkGPSEnabled)
{
//I have problem in this Line
Location location1 = locationManager.requestLocationUpdates(GpsProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
if (location1 != null)
{
Date = dateFormat.format(date);
latitude = location1.getLatitude();
longitude = location1.getLongitude();
db.addContact(new DatabaseTable(Date, latitude, longitude));
JSONSaver.writeJSON(Date, latitude, longitude);
showOnTextView(Date, latitude, longitude);
}
}
else if (isNetworkEnabled2)
{
Location location1 = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location1 != null)
{
//I have problem in this Line
Location location1 = locationManager.requestLocationUpdates(NetworkProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
Date = dateFormat.format(date);
latitude = location1.getLatitude();
longitude = location1.getLongitude();
db.addContact(new DatabaseTable(Date, latitude, longitude));
JSONSaver.writeJSON(Date, latitude, longitude);
showOnTextView(Date, latitude, longitude);
}
}
}
}
I want to know where is my problem and how can i solve it and which of them(Context or LocationListener) is better to be used for doing my job.
It's my first time that i ask a question in Stackoverflow so if explanations have some lacks or i was not very clear or any other problems,
feel free to ask for more information in comments I will try to be as much as clear i can.
and beside of that I'm Kind of New to Programming so if you find something Stupid in my codes Don't get Surprised :D.
Thanks for Further Helps!

Error: incompatible types: void cannot be converted to Location. This the actuall error you should get when you run above code.
You are expecting location in the place where void is returning. requestLocationUpdates uses LocationListener object of LocationManager class to receive periodic updates about the geoposition.
//Implement LocationListener to your class and implement callback methods
//use the below code at onCreate
//[Changes starts here]
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
//[Changes ends here]
//onLocationChanged method you'll get the updated locatioin
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
Source: http://www.vogella.com/tutorials/AndroidLocationAPI/article.html

Thanks for all people who helped me! the problem was for the package i used that was:
import android.location.LocationListener;
I used next package instead of first package:
import com.google.android.gms.location.LocationListener;
using this package in #chiru 's script will work fine for me!
Thanks A Lot Again!

You have an error at this line of code :
...requestLocationUpdates(NetworkProvider, 0, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mylocationListener);
The method requestLocationUpdates has the parameters: String provider, long minTime, float minDistance, LocationListener listener
This is what you put in:
NetworkProvider provider, long minTime, float minDistance, LocationListener listener
The only reason I'd see of the compiler giving an error is because NetworkProvider isn't a String. Otherwise, your locationManager simply doesn't have requestLocationUpdates(..).

Related

Displaying location (address) in another activity class in android studio

I am trying to display user's location in another class from my location class.
Here's my location class that is getting location and resolving address of the user. Please notice the getAddressLine method in the following class as I wanna display the address line in another class.
MyLocation.Java
package miniandroid.com.services;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import miniandroid.com.R;
/**
* Create this Class from tutorial :
* http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
*
* For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
*
*/
public class MyLocation extends Service implements LocationListener {
// Get Class Name
private static String TAG = MyLocation.class.getName();
private Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
public double latitude;
public double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 300; // 300 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2; // 3 hours
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public MyLocation(Context context) {
this.mContext = context;
getLocation();
}
public MyLocation()
{
}
/**
* Try to get my current location by GPS or Network Provider
*/
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Try to get location if you GPS Service is enabled
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
// Application can use GPS or Network Provider
if (!provider_info.isEmpty()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(
provider_info,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
} catch (Exception e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
String location = latitude + "," + longitude;
SharedPreferences prefsy = getSharedPreferences("emood_veriif", MODE_PRIVATE);
SharedPreferences.Editor editor = prefsy.edit();
editor.putString("MapFirst", location);
editor.commit();
}
}
/**
* GPSTracker latitude getter and setter
* #return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* #return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.removeUpdates(MyLocation.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle("Location access");
//Setting Dialog Message
alertDialog.setMessage("Select settings to enable location access.");
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
#Override
public void onLocationChanged(Location location) {
startService(new Intent(this,TrackMeService.class));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
However, I am trying to class this in my HomeActivity.Java.
package miniandroid.com.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
import miniandroid.com.R;
import miniandroid.com.helpers.UserPreference;
import miniandroid.com.services.LocationService;
import miniandroid.com.services.MyLocation;
public class HomeActivity extends Activity {
private static TextView hometext;
UserPreference userPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
hometext = (TextView) findViewById(R.id.homepagetxt);
userPreference = new UserPreference(this);
setTitle("sMood - " + userPreference.getUserName());
hometext.setText("Hello " + userPreference.getUserName() + "!" + "\nYour current location is:" + "I wanna display address here" );
MyLocation gpsTracker = new MyLocation(this);
if (gpsTracker.getIsGPSTrackingEnabled()) {
String stringLongitude = String.valueOf(gpsTracker.longitude);
String stringLatitude = String.valueOf(gpsTracker.latitude);
String location = stringLatitude + "," + stringLongitude;
SharedPreferences prefsy = getSharedPreferences("emood_veriif", MODE_PRIVATE);
SharedPreferences.Editor editor = prefsy.edit();
editor.putString("MapFirst", location);
editor.commit();
} else {
gpsTracker.showSettingsAlert();
}
startService(new Intent(this, LocationService.class));
}
}
I have been trying to just get the getAddressLine method from the MyLocation.Java, but it is not working for me.
any help or input is highly appreciate, I have been working on this from days.

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.

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

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

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