I am targeting of using Android 2.2 to find distance using GPS however there are some problem in regarding my on Location changed. Previously, I put my code at On click listener and it does not work well. I manage to get the distance only after pressing the start and stop button after a numerous times.
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(originalCoordinates!=null){
coordinates1 = getGPS();
gpsEnd=coordinates1;
double d = distFrom(originalCoordinates[0],originalCoordinates[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
txtViews.setText("" + coordinates1.length + " new counts!!!" + coordinates1[0] + "," + coordinates1[1] );
}
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
txtView.setText("" + coordinates.length + " counts!!!" );
//double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
//totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
gpsOrg=coordinates;
if(originalCoordinates == null){
originalCoordinates = gpsOrg;
coordinates1 = getGPS();
txtView.setText("" + originalCoordinates.length + " original counts!!! " + originalCoordinates[0] + "," + originalCoordinates[1] );
}
//txtView.setText("" + coordinates.length + " counts" );
}
startButton.setEnabled(true);
}
dear do it like this.
Switch on GPS of your device
Wait until it get connected to a satellite.
Make a flag like booelan detecting_position.
Set it true on start button.
OnLocationChange Listner, check if flag is true, then get the
points using location.getLat,and getLong... and save them.
Here you can do a trick, initialize start location variables with
null, and check if startPosition is null then on first iteration of
location listner set long and lat as start location, in further
location change iterations set long and lat to stop_location
variables.
Once you tap the stop button set flag to false.
Now you have both start and end position. Use the distance formula
to calculate distance.
first of all take activity and do like below
public class MainActivity extends Activity implements OnClickListener
{
Button btnStart = null;
Button btnStop = null;
Context context = null;
Button btnTouch = null;
float distance ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
context = this;
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
Intent i = new Intent(context, MyService.class);
if(v.getId() == R.id.btnStart)
{
startService(i);
}
else if(v.getId() == R.id.btnStop)
{
distance = MyService.final_distance;
stopService(i);
}
}
}
then take one service and put our logic for location change in this service.i have use service because service run in background continue and look for location change when location is update.
public class MyService extends Service implements LocationListener
{
public static float final_distance = 0.0f;
private float distance = 0.0f;
private double old_latitude = 0.0;
private double old_longitude = 0.0;
private double new_latitude = 0.0;
private double new_longitude = 0.0;
LocationManager locationManager = null;
float[] result = null;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
result = new float[3];
}
#Override
public void onStart(Intent intent, int startid)
{
}
#Override
public void onDestroy()
{
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
if(old_latitude == 0.0 && old_longitude == 0.0)
{
old_latitude = location.getLatitude();
old_longitude = location.getLongitude();
}
new_latitude = location.getLatitude();
new_longitude = location.getLongitude();
Location.distanceBetween(old_latitude, old_longitude, new_latitude, new_longitude, result);
distance = final_distance +result[0];//distance in meters between two locations
final_distance = distance;
old_latitude = new_latitude;
old_longitude = new_longitude;
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
and also add uses permission android.permission.ACCESS_FINE_LOCATION in android manifest.xml
Hope this may help you
Related
I am working on a project where I want to collect sensor data with coordinates and save them to a csv file.
The app was working perfectly before I started coding for getting the location.
I am using location manager but every time I install this app on my device the application just doesn't seem to work. I disappears after few seconds of installation.
Also note that I am saving the sensor data in every 20 milliseconds so should I collect the coordinate data in the same rate?
Sorry to put the whole code but I need help! Please let me know where should I make changes?
public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener {
private SensorManager sensorManager;
private Sensor magnetic;
//Location
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
// --o
private int counter = 1;
private boolean recording = false;
private boolean counterOn = false;
private float magValues[] = new float[3];
private Context context;
private static final int REQUESTCODE_STORAGE_PERMISSION = 1;
Collection<String[]> magneticData = new ArrayList<>();
private CsvWriter csvWriter = null;
public static DecimalFormat DECIMAL_FORMATTER;
TextView stateText;
EditText fileIDEdit;
//Location
TextView lat;
TextView lon;
//--o
TextView magText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Location
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
//--o
findViewById(R.id.button).setOnClickListener(listenerStartButton);
findViewById(R.id.button2).setOnClickListener(listenerStopButton);
fileIDEdit = (EditText)findViewById(R.id.editText);
magText = (TextView) findViewById(R.id.textView3);
stateText = (TextView) findViewById(R.id.textView);
stateText.setText("Stand by");
context = this;
// Sensor
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
//Location
handler.postDelayed(runLocation, 1000);
}
public Runnable runLocation = new Runnable() {
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
private View.OnClickListener listenerStartButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
recording = true;
stateText.setText("Recording started");
stateText.setTextColor(Color.parseColor("#FF0000"));
}
};
#Override
public void onSensorChanged(SensorEvent event) {
long timeInMillisec = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;
// Some sensor operations
}
//magneticData.add(new String[]{String.valueOf(timeInMillisec), String.valueOf(magValues[0]), String.valueOf(magValues[1]), String.valueOf(magValues[2])});
#SuppressLint("SimpleDateFormat") SimpleDateFormat logLineStamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS", Locale.getDefault());
//logLineStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
magneticData.add(new String[]{logLineStamp.format(new Date(timeInMillisec)), String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(magnitude), String.valueOf(latitude), String.valueOf(longitude)});
counter++;
}
}
// Checks if the the storage permissions are given or not by the user
// It will request the use if not
private static boolean storagePermitted(Activity activity){
// Check read write permission
}
//Check Location
private void getLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// Added Later
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location changed: "+latitude+" "+longitude, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I am trying to get the lat and lng of a users location and pass these as a double to another method. However, I don't know how to do this or is it is possible.
As soon as I exit the inner class the variable's become null again.
public class MainActivity extends AppCompatActivity {
Double lat;
Double lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void onSearch(View v){
String[] requiredPermissions = {
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
boolean ok = true;
for (int i = 0; i < requiredPermissions.length; i++) {
int result = ActivityCompat.checkSelfPermission(this, requiredPermissions[i]);
if (result != PackageManager.PERMISSION_GRANTED) {
ok = false;
}
}
if (!ok) {
ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// that last parameter MUST be >0, or it fails silently
System.exit(0);
} else {
// doStuffThatNeedsPermissions();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
System.out.println("location is : " + lat + lng);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
//System.out.println("location is here is : " + lat + lng);
}
//System.out.println("location is dow here is : " + lat + lng);
}
}
I don't have the permission to leave a comment so that's why answered the question.
As far as I understood.Though there are so many ways.Here is a way how you can use this into your entire class.
private Double lat,lng;
...
#Override
public void onLocationChanged(Location location) {
YourClass.this.lat = location.getLatitude();
YourClass.this.lng = location.getLongitude();
System.out.println("location is : " + this.lat + this.lng);
}
...
System.out.println("location is here is : " + this.lat + this.lng);
I edited my answer. I made a silly mistake.Sorry for that.
I'm newcomer in Android development and I wish someone could help me.
My problem is as follow:
gradle
dependencies {
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.android.gms:play-services-location:15.0.1'
}
MainActivity
[...]
local = (CheckBox) findViewById(R.id.local_checkbox);
local.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DEBUG_INFO","CLICKED");
GPSTracker g = new GPSTracker(MainActivity.this);
if (((CheckBox) v).isChecked()) {
Log.v("DEBUG_INFO","CHECKED");
CheckGpsStatus();
if (GpsStatus == true) {
isLocated = true;
Location l = g.getLocation();
if ((l != null) && (isLocated == true)) {
lat = g.getLocation().getLatitude();
lon = g.getLocation().getLongitude();
Log.v("DEBUG_INFO","DEBUG_INFO:
Latitude: "+ String.valueOf(lat)+ " Longitude: "+
String.valueOf(lon));
}
else if ((l != null) && (isLocated == false)) {
lat = 0.0;
lon = 0.0;
} else {
lat = 0.0;
lon = 0.0;
}
} else {
new AlertDialog.Builder(NovaDenunciaActivity.this, R.style.AlertDialogCustom)
.setTitle("GPS TEXT!")
.setCancelable(false)
.setMessage("PLEASE SET GPS TEXT.")
.setPositiveButton("CLOSE",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
local.toggle();
}
} else {
isLocated = false;
}
}
});
}//onCreate
public void CheckGpsStatus(){
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("CHECKBOX","MARCADO");
}
} //Code end's
GPSTracker.java
[...]
public class GPSTracker extends Activity implements LocationListener {
Context context;
/*variables*/
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public GPSTracker(Context c) {
context = c;
}
/*variables*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} //Oncreate end's?
public Location getLocation() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Permission Text!\nPlease allow
permissions text.", Toast.LENGTH_LONG).show();
return null;
}
//Get the location manager
locationManager = (LocationManager)
context.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.");
Log.v("DEBUG_INFO:", "Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
//longitudeField.setText("Location not available");
Log.v("DEBUG_INFO:", "Latitude: not available");
Log.v("DEBUG_INFO:", "Longitude: not available");
}
return location;
}
#Override
protected void onResume() {
super.onResume();
Log.v("DEBUG_INFO:", "REQUESTING LOCATION UPDATES");
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
Log.v("DEBUG_INFO:","STOP LOCATION UPDATES");
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
//latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
Log.v("DEBUG_INFO:","Latitude: "+String.valueOf(lat));
Log.v("DEBUG_INFO:","Longitude: "+String.valueOf(lng));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(context, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(context, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
But when I click on checkbox the logcat (verbose) shows me the following:
V/DEBUG_INFO:: Latitude: not available
V/DEBUG_INFO:: Longitude: not available
The program should get latitude and longitude, if it does not exist it should call the locationManager.requestLocationUpdates(provider, 0, 0, this);
But I do not know what I'm doing wrong. Can someone help me?
I have a problem with Location variable in my Android app. On this screen GPSLocation works fine, but when I change screen to gpsLocation.getLastKnownLocation() this method always returns null.
First Screen:
public class MainActivity extends ActionBarActivity {
private TextView text;
private GPSLocation gpsLocation;
private Location targetLocation;
private EditText editLatitude;
private EditText editLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.textView);
gpsLocation = new GPSLocation(this);
editLatitude = (EditText)findViewById(R.id.editDlugosc);
editLongitude = (EditText)findViewById(R.id.editSzerokosc);
targetLocation = new Location("Bosch");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void click_rozpocznij(View view) {
targetLocation=gpsLocation.getLastKnownLocation();
text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_end(View view)
{
gpsLocation.stopUsingGPS();
text.setText("Your location:");
}
public void click_pointer(View view) {
if(targetLocation !=null) {
Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
nextScreen.putExtra("location", targetLocation);
startActivity(nextScreen);
}
else
{
targetLocation.setLongitude(0);
targetLocation.setLatitude(0);
Intent nextScreen = new Intent(getApplicationContext(), Pointer.class);
nextScreen.putExtra("location", targetLocation);
startActivity(nextScreen);
}
}
public void click_show(View view) {
gpsLocation.getLastKnownLocation();
text.setText("Your location: \n" + gpsLocation.getLatitude() + "\n" + gpsLocation.getLongitude());
}
public void click_SaveTarget(View view) {
if(targetLocation !=null)
{
try{
targetLocation.setLatitude(Double.parseDouble(editLatitude.getText().toString()));
targetLocation.setLongitude(Double.parseDouble(editLongitude.getText().toString()));
}
catch(Exception e)
{
targetLocation.setLatitude(0);
targetLocation.setLongitude(0);
editLatitude.setText("0");
editLongitude.setText("0");
}
}
}
Second Screen:
public class Pointer extends ActionBarActivity implements SensorEventListener{
private Location cel;
private TextView textLocation;
private TextView textDistance;
private TextView textAngle;
private TextView textAccuracy;
private ImageView obrazek;
private SensorManager sensorManager;
private float[] lastCompass= new float[3];
private float[] lastAccelero = new float[3];
private float[] orientation = new float[3];
private boolean lastCompassSet = false;
private boolean lastAcceleroSet = false;
private float[] rotation = new float[9];
private float degree = 0f;
private Sensor compass;
private Sensor accelerometer;
private GPSLocation gpsLocation;
private Location locationFirst;
private Location locationNow;
private GeomagneticField magneticField;
private float azimuthDegress;
private float azimuthCel;
private Long timeStart;
private Long timeEnd;
private void sprawdzPolozenie()
{
if (gpsLocation.location.distanceTo(locationFirst) > 10000)
{
magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
locationFirst = gpsLocation.getLastKnownLocation();
}
SensorManager.getRotationMatrix(rotation,null,lastAccelero,lastCompass);
SensorManager.getOrientation(rotation,orientation);
float azimuthRadians = orientation[0];
azimuthDegress = (float)(Math.toDegrees(azimuthRadians));
azimuthDegress += magneticField.getDeclination();
azimuthCel= locationNow.bearingTo(cel);
azimuthDegress=azimuthDegress-azimuthCel;
RotateAnimation ra = new RotateAnimation(degree,-azimuthDegress, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
ra.setDuration(400);
ra.setFillAfter(true);
obrazek.startAnimation(ra);
degree=-azimuthDegress;
}
#Override
public void onSensorChanged(SensorEvent event) {
locationNow=gpsLocation.getLastKnownLocation();
if(locationNow!=null) {
if (event.sensor == compass) {
/*event.values[0]=lastCompass[0];
event.values[1]=lastCompass[1];
event.values[2]=lastCompass[2];*/
System.arraycopy(event.values, 0, lastCompass, 0, event.values.length);
lastCompassSet = true;
} else if (event.sensor == accelerometer) {
/*event.values[0]=lastAccelero[0];
event.values[1]=lastAccelero[1];
event.values[2]=lastAccelero[2];*/
System.arraycopy(event.values, 0, lastAccelero, 0, event.values.length);
lastAcceleroSet = true;
}
if (lastCompassSet) {
timeStart = System.currentTimeMillis();
if (timeStart > timeEnd + 500) {
sprawdzPolozenie();
timeEnd = timeStart;
}
}
textDistance.setText("Distanse: " + locationNow.distanceTo(cel));
textAccuracy.setText("Accuracy: " + locationNow.getAccuracy());
textAngle.setText("Angle: " + azimuthDegress);
}
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener(this, compass, SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause(){
super.onPause();
sensorManager.unregisterListener(this,accelerometer);
sensorManager.unregisterListener(this,compass);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gpsLocation = new GPSLocation(this);
locationFirst = new Location("Bosch");
locationNow = new Location("Bosch");
cel = new Location("Bosch");
locationNow=gpsLocation.getLastKnownLocation();
locationFirst= gpsLocation.getLastKnownLocation();
setContentView(R.layout.activity_wskaznik);
timeEnd =System.currentTimeMillis();
sensorManager = (SensorManager)this.getSystemService(Context.SENSOR_SERVICE);
compass = sensorManager.getDefaultSensor(TYPE_MAGNETIC_FIELD);
accelerometer = sensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
obrazek =(ImageView)findViewById(R.id.wskaznik_imageView);
textLocation = (TextView)findViewById(R.id.wskaznikTekstCel);
textDistance = (TextView)findViewById(R.id.wskaznikTekstOdleglosc);
textAngle = (TextView)findViewById(R.id.wskaznikTekstKat);
textAccuracy =(TextView)findViewById(R.id.wskaznikTekstDokladnosc);
Bundle extras = getIntent().getExtras();
magneticField = new GeomagneticField(Double.valueOf(gpsLocation.getLatitude()).floatValue(),Double.valueOf(gpsLocation.getLongitude()).floatValue(),Double.valueOf(gpsLocation.getAltitude()).floatValue(),System.currentTimeMillis());
if(extras!=null)
{
cel = (Location)extras.get("location");
}
textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void click_wroc(View view) {
finish();
}
GPSLocation itself:
public class GPSLocation extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
//czas i dystans pomiedzy pomiarami
private static final long MIN_DISTANCE = 10;
private static final long MIN_TIME = 1000 * 60 * 1;
double latitude;
double longitude;
double altitude;
public Location location;
protected LocationManager locationManager;
public GPSLocation(Context context)
{
this.mContext = context;
getLocation();
}
public void requestLocation() {
//network
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
altitude = location.getAltitude();
}
}
//gps
if(isGPSEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if(locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude = location.getAltitude();
}
}
}
public Location getLastKnownLocation()
{
try
{
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
this.canGetLocation=false;
this.showSettingsAlert();
}
else
{
requestLocation();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
public Location getLocation()
{
try
{
locationManager=(LocationManager)mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
this.canGetLocation=false;
this.showSettingsAlert();
}
else
{
this.canGetLocation=true;
requestLocation();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return location;
}
public double getLatitude()
{
if(location!=null)
{
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
latitude = location.getLatitude();
}
return longitude;
}
public double getAltitude(){
if(location!=null)
{
latitude=location.getAltitude();
}
return altitude;
}
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Przejdź do ustawień");
alertDialog.setMessage("Lokalizacja wyłączona");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
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() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS()
{
if(locationManager!=null)
{
locationManager.removeUpdates(GPSLocation.this);
}
}
#Override
public void onLocationChanged(Location location) {
}
#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;
}
I ran your Pointer Activity code in isolation, and it worked fine for me.
It looks like your main issue is how you're passing the Location through the Intent to the Pointer Activity from MainActivity.
Location implements Parcelable, so you can pass it though the Intent as you are already doing, and retrieve it like this:
if(extras!=null)
{
//cel = (Location)extras.get("location"); //this is not correct
cel = (Location) extras.getParcelable("location");
}
if (cel != null){
textLocation.setText(cel.getLatitude() + "," + cel.getLongitude());
}
Documentation: http://developer.android.com/reference/android/os/Bundle.html#getParcelable(java.lang.String)
http://developer.android.com/reference/android/location/Location.html
Sory for everyone who wanted help me for problem. I solved this by myself.
Problem was in GPSLocation class. I had to add new constructor at start and change way of getting location from locationManager
public GPSLocation(Context context)
{
this.mContext = context;
location = new Location("Bosch");
getLocation();
}
When I use this code location stay nullpointer.
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
But creating copy of location from locationManager solved problem.
location = new Location(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
Maybe locationManager is creating data of location only not Location itself and that was causing creating nullpointer.
I am creating an app that only checks for location when user clicks a button.
here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {
}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
the location service on the device is enabled.
Thanks very much!
getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.
try this pls
mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick()
{
Location myLocation = mGoogleMap.getMyLocation();
onLocationChanged(myLocation);
return false;
}
});