java.lang.RuntimeException: Unable to instantiate activity ComponentInfo Application Crashes upon launch - java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnShowLocation=null;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.btnshowloc);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
This is My main activty claass
package com.example.locateus;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// 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();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
After running the application , the application crashes upon start up, i have checked the liabaries and checking for correct build java path for the project properties , still i cannot find the solution to this . Please help me.

This code will crash:
// btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnShowLocation.setOnClickListener(new View.OnClickListener() {
The variable btnShowLocation will not have a value, and you must give it one.
Uncomment the line and make sure that R.id.btnShowLocation has a valid value.

Related

android location coordinates retrives 0

i have a problem, about gps coordinates in my android application
to get a coordinates I used GPSTracker service:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
//noinspection MissingPermission
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
//noinspection MissingPermission
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(Dialog
Interface 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();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I need to add this coordinates into database, here is an implementation:
GPSTracker gpstracker = new GPSTracker(this);
if (gpstracker.canGetLocation) {
double locationLng = gpstracker.getLongitude();
double locationLat = gpstracker.getLatitude();
databaseReference.child("lng").setValue(locationLng);
databaseReference.child("lat").setValue(locationLat);
} else
gpstracker.showSettingsAlert();
but only 23, 24, 25 api working well, under it always retrieve 0((((
when I add a debugger, on this stage I get a 0, I don't know why:
`public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}`
GPSTracker gpstracker = new GPSTracker(this);
if (gpstracker.canGetLocation) {
double locationLng = gpstracker.getLongitude(gpstracker);
double locationLat = gpstracker.getLatitude(gpstracker);
databaseReference.child("lng").setValue(locationLng);
databaseReference.child("lat").setValue(locationLat);
}
//pass GPSTracker
public double getLatitude(GPSTracker gpsTracker){
Location location = gpsTracker.getLocation();
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(GPSTracker gpsTracker){
Location location = gpsTracker.getLocation();
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}`

Android - Get and Set Mock Location (as system app) without enabling it in settings

I have been trying to create an Android App which is able to get and set Mock Location, without enabling Mock Location in Developer Settings.
I have been able to achieve that to an extent, using different questions over SO, but am now stuck over the issue that it only changes the location once, and not after that.
My Code:
//onCreate()
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gps = new GPSTracker(this);
public void updateCoordinates(DIRECTIONS direction ) // DIRECTIONS is an enum
{
double tempLatitude, tempLongitude;
tempLatitude = gps.getLatitude();
tempLongitude = gps.getLongitude();
if(direction == DIRECTIONS.UP)
{
tempLatitude = gps.getLatitude() + 1;
tempLongitude = gps.getLongitude();
}
if(direction == DIRECTIONS.DOWN)
{
tempLatitude = gps.getLatitude() - 1;
tempLongitude = gps.getLongitude();
}
if(direction == DIRECTIONS.LEFT)
{
tempLatitude = gps.getLatitude();
tempLongitude = gps.getLongitude() + 1;
}
if(direction == DIRECTIONS.RIGHT)
{
tempLatitude = gps.getLatitude() - 1;
tempLongitude = gps.getLongitude();
}
Location tempLocation = new Location(provider);
tempLocation.setLatitude(tempLatitude);
tempLocation.setLongitude(tempLongitude);
tempLocation.setAccuracy(500);
tempLocation.setAltitude(0D);
tempLocation.setTime(System.currentTimeMillis());
tempLocation.setBearing(0F);
tempLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
setCoordinates(tempLocation);
}
enum DIRECTIONS
{
UP,
DOWN,
LEFT,
RIGHT
}
public void getCoordinates(View v)
{
String latitude, longitude;
gps.getLocation();
if(gps.canGetLocation())
{
latitude = String.valueOf(gps.getLatitude());
longitude = String.valueOf(gps.getLongitude());
coordinates.setText(latitude + "," + longitude);
}
else if(!gps.canGetLocation())
{
coordinates.setText("ERROR");
}
}
public void initializeGPS(boolean state) //Used to add and remove provider in onCreate() and onDestroy()
{
int value = setMockLocationSettings();
try{
if(state)
{
mLocationManager.removeTestProvider(provider);
mLocationManager.addTestProvider(provider, false, true, false, false, true, true, false, 0, 5);
mLocationManager.setTestProviderEnabled(provider, true);
mLocationManager.setTestProviderLocation(provider, gps.getLocation());
}
if(!state)
{
mLocationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, false);
mLocationManager.clearTestProviderEnabled(LocationManager.GPS_PROVIDER);
mLocationManager.clearTestProviderLocation(LocationManager.GPS_PROVIDER);
mLocationManager.removeTestProvider(LocationManager.GPS_PROVIDER);
}
}
catch (Exception e) {}
finally {
restoreMockLocationSettings(value);
}
}
public void setCoordinates(Location fake_location)
{
int value = setMockLocationSettings();//toggle ALLOW_MOCK_LOCATION on
try {
mLocationManager.setTestProviderLocation(provider, fake_location);
} catch (SecurityException e) {
e.printStackTrace();
} finally {
restoreMockLocationSettings(value);//toggle ALLOW_MOCK_LOCATION off
}
}
private int setMockLocationSettings() {
int value = 1;
try {
value = Settings.Secure.getInt(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION);
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION, 1);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
private void restoreMockLocationSettings(int restore_value) {
try {
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.ALLOW_MOCK_LOCATION, restore_value);
} catch (Exception e) {
e.printStackTrace();
}
}
To get the GPS Coordinates, I use a class named GPSTracker
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// 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();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I guess the problem is with the provider I set, because it used to give a lot of errors, before I added the initializeGPS()

Can't Get address using Longitude & Latitude Android

I am trying to get address from longitude and latitude but unable to get the address. I am getting Longi. and lati. value but when I pass it to the function of getAddress it stop working Kindly help me if you guys can.
Here is my Code
MainActivity.java File
package com.example.mygps;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnGet;
GPS_Class gps;
TextView adr,cty,ctry;
double longi, lati;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGet = (Button)findViewById(R.id.btnGo);
adr = (TextView)findViewById(R.id.adr);
cty = (TextView)findViewById(R.id.cty);
ctry = (TextView)findViewById(R.id.ctry);
btnGet.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
gps = new GPS_Class(MainActivity.this);
if(gps.canGetLocation())
{
longi = gps.getLongitude();
lati = gps.getLatitude();
Toast.makeText(MainActivity.this, "Longitude is:"+longi+"Latidute is:"+lati, Toast.LENGTH_LONG).show();
getAddress(longi, lati);
}
else
{
gps.showSettingsAlert();
}
}
});
}
public void getAddress(double longitude, double latitude)
{
double long1,lati1;
long1 = longitude;
lati1 = latitude;
if(lati>0 && long1>0)
{
Geocoder geocode = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocode.getFromLocation(latitude,longitude, 1);
String Addres_ = addresses.get(0).getAddressLine(0);
String Country = addresses.get(0).getCountryName();
String City = addresses.get(0).getLocality();
adr.setText(Addres_);
cty.setText(City);
ctry.setText(Country);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//if closing. . .
else
{
Toast.makeText(this, "No Vlaue", Toast.LENGTH_LONG).show();
}
}
}
My GPS_Class.java File Code
package com.example.mygps;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPS_Class extends Service implements LocationListener{
//To Get Context of the class...
Context context;
//Declaring Variable to use. . .
double lattitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
boolean isGPSEnabled = false;
boolean isNetWorkEnabled = false;
boolean canGetLocation = false;
//Declaring objects of different classes...
Location location;
LocationManager locationmanager;
public GPS_Class(Context context) {
this.context = context;
GetLocation();
}
//Self Coded Function to perform all location works . . .
private Location GetLocation()
{
locationmanager = (LocationManager)context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetWorkEnabled = locationmanager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isNetWorkEnabled)
{
canGetLocation = true;
locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
if(locationmanager !=null)
{
location = locationmanager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
lattitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled)
{
canGetLocation = true;
if(location == null)
{
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
if(locationmanager != null)
{
location = locationmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null)
{
lattitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
return location;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// 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);
context.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public double getLatitude(){
if(location != null){
lattitude = location.getLatitude();
}
// return latitude
return lattitude;
}
public double getLongitude()
{
if(location !=null)
{
longitude =location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#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
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Got Solution
The Above mention posted code is fine It can get the current location.
If you will try to run it on emulator it will show you error because "Geocoder" class is not compatible with Emulator.
Run it on Device it is Working fine.
Try with changing this with MainActivity.this in getAddress method:
Geocoder geocode = new Geocoder(MainActivity.this, Locale.getDefault());
getFromLocation method Throws. So check your latitude value. It is not in correct range:
IllegalArgumentException if latitude is less than -90 or greater than 90
IllegalArgumentException if longitude is less than -180 or greater than 180
IOException if the network is unavailable or any other I/O problem occurs
The actual function is getFromLocation(double latitude, double longitude, int maxResults). You are passing longitude in place of latitude and latitude in place of longitude. Try changing this line:
addresses = geocode.getFromLocation(longitude, latitude, 1);
to this:
addresses = geocode.getFromLocation(latitude, longitude, 1);
And also add null and size check to array before accessing it to avoid NullPointerException and IndexOutOfBoundException as the documentation says it can return null array
if (addresses != null && addresses.size() > 0) {
String Addres_ = addresses.get(0).getAddressLine(0);
String Country = addresses.get(0).getCountryName();
String City = addresses.get(0).getLocality();
adr.setText(Addres_);
cty.setText(City);
ctry.setText(Country);
} else {
// Reset fields here
}

Java (Android) - How to get the Location?

I used that solution to obtain my location, but I don't know how to get the location outside to use location.getLatitude() & location.getLongitude() later.
Is there any solution to access location from the outside?
I don't completely under stand your question but if you want to get your gps coordinates you can create a new class GPSTracker.
GPSTracker :
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the 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 the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
And to get the coordinates use this in your activity:
GPSTracker gps;
double latitude;
double longitude;
gps = new GPSTracker(your context);
gps.getLocation();
// Check if GPS enabled
if(gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}

Pause code execution while acquiring informations

Have a working application which collects GPS coordinates over GPS.
The application will use the those coordinates after the collection.
But because the acquiring of the coordinates can take 10-15 or more sec.
The app starts acquiring, moves forward in code takes the cords ( usually lastknowlocation ) and uses the coordinates which are not last.
So often I get GPS cords as 0,0 0,0 or lastknowlocation
I need somehow to pause execution of code until the new cords are acquired.
For any ideas or help I would be thankful
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
Location location_1; // location
Location zadnja; // location
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 10 * 1; // 10 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location 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);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
location = null ;
locationManager = null;
this.canGetLocation= false ;
canGetLocation = false ;
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// 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();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
You need to delegate the GPS collection to a separate thread, and let the main code monitor it. That way the management of what is happening is in one thread, and the slow stuff is in another. The two threads need to communicate using classical state-machine techniques (synchronized code sections, semaphores etc).
Why don't you acquire the location in an AsyncTask and set a variable of the class foundLocation=true in PostExecute of the AsycTask, and pause your main thread with a
while(!foundLocation){
// do something like a loading bar or something
}

Categories