Can't Get address using Longitude & Latitude Android - java

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
}

Related

GeoCoder Does not show contryName

I am making an android application.In my application I want to get the Country name of my location using my LocationTracker Class I created , but I cant get the Country name using GeoCoder
Here is my LocationTracker Class
package com.farzin.locationmap.Location;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.farzin.locationmap.R;
import java.util.List;
public class LocationTracker extends Service implements LocationListener {
Location location;
LocationManager locationManager;
Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = true;
boolean canGetLocation;
double longitude;
double latitude;
static final long MIN_DISTANCE = 10;
static final long MIN_TIME = 1000 * 60;
public LocationTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation(){
locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE);
//gps check
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//network check
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isNetworkEnabled && !isGPSEnabled){
canGetLocation = false;
}else {
canGetLocation = true;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME,MIN_DISTANCE,this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
if (isGPSEnabled){
if (location == null){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME,MIN_DISTANCE,this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
}
}
}
return location;
}
public double getLongitude() {
return longitude;
}
public double getLatitude() {
return latitude;
}
public boolean hasLocation(){
return canGetLocation;
}
public void showAlertSettings(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(R.string.warning);
alertDialog.setMessage(R.string.gps_warning_massage);
alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
}
Here is my Main Activity Where im trying to create for Toast the Country Name For testing
locationTracker = new LocationTracker(getApplicationContext());
if (locationTracker.hasLocation()){
lat = locationTracker.getLatitude();
lon = locationTracker.getLongitude();
Geocoder geocoder = new Geocoder(getApplicationContext(),new Locale("fa"));
try {
List<Address> addressList = geocoder.getFromLocation(lat, lon, 1);
Address address = addressList.get(0);
String countryName = address.getCountryName();
Toast.makeText(this, countryName, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}else {
locationTracker.showAlertSettings();
}
I'm new to this, so what seems to be the problem here?
plus ignore the part where I didnt ask for permissions from the user this is only for testing purposes...
There are two cases that came into my mind.
First case:
Geocoder does not reteieve any data if the device is in a region that Google denies requests coming from it. (such as Crimea, Cuba, the so-called Donetsk People's Republic and Luhansk People's Republic, Iran, North Korea, and Syria.)
You may want to try using a VPN that would change your IP, and try to see if you get data in the response.
Second case:
You may want to try different location and see if there is data retrived in the response. If another location did retreive data, then that's most probably could mean that Geocoder actually did not get any data from the previously provided location.
Try this
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(requireActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String country = addresses.get(0).getCountryName();
}catch (IOException e)
{
e.printStackTrace();
}

How to get city information in android by longitude and latitude

I am making android app now. I got some problem about getting locations.
In my code, I made my app get longitude and latitude by GPS. However, I have continued to fail to get city name by longitude and latitude. I don't know why my code goes to Exception even though there are no wrong things in my code.
Here is my code for getting city name
ackage org.androidtown.getcurrentlocation;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class GetCurrentLocation extends AppCompatActivity implements View.OnClickListener {
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_current_location);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates.\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
else{
alertbox("GPS Status!!", "Your GPS is : OFF");
}
}
private Boolean displayGpsStatus(){
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if(gpsStatus){
return true;
}
else{
return false;
}
}
protected void alertbox(String title, String mymessage){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable").setCancelable(false).setTitle("**GPS Status**").setPositiveButton("Gps On", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent myIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(), "Location changed : Lat " + loc.getLatitude() +"Lng: "+loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longtitude = "Longtitude: "+loc.getLongitude();
Log.v(TAG, longtitude);
String latitude = "Latitude: "+loc.getLatitude();
Log.v(TAG, latitude);
String cityName = "default";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
// addresses
try{
List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if(addresses.size()>0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
}catch(IOException e){
e.printStackTrace();
}
String s = longtitude + "\n" + latitude +
"\n\nMy Current City is : "+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider){
}
#Override
public void onProviderEnabled(String provider){
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
}
On the above code, this part is main code to get city name by longitude and latitude. There is no problem to get longitude and latitude. The only problem is to get city name.
String cityName = "default";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
// addresses
try{
List<Address> addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if(addresses.size()>0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
}catch(IOException e){
e.printStackTrace();
}
String s = longtitude + "\n" + latitude +
"\n\nMy Current City is : "+ cityName;
editLocation.setText(s);
}
Thank you for reading my question. Have a great day(?) midnight.
First thing you shouldn't call getFromLocation from main thread as this method is synchronous and may take a long time to do its work, so you should not call it from the main, user interface (UI) thread of your app. you should use Intent service class.
Here is code for it:
public class GetAddressService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
protected ResultReceiver mReceiver;
//protected DataEntry.AddressResultReceiver mReceiver;
private static final String TAG = "GetAddressService";
public GetAddressService() {
super("GetAddressService");
}
#Override
protected void onHandleIntent(Intent intent) {
mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
Log.e(TAG,"mReceiver"+mReceiver);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
String errorMessage = "";
// Get the location passed to this service through an extra.
Location mCurrentLocation = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
try {
addresses = geocoder.getFromLocation(mCurrentLocation.getLatitude(),
mCurrentLocation.getLongitude(), 1);
} catch (IOException e) {
errorMessage = "Service error: ";
Log.e(TAG, errorMessage, e);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used";
Log.e(TAG, errorMessage + ". " +
"Latitude = " + mCurrentLocation.getLatitude() +
", Longitude = " +
mCurrentLocation.getLongitude(), illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "no_address_found";
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT,errorMessage);
}else {
String cityName = addresses.get(0).getLocality();
String countryName = addresses.get(0).getCountryName();
String rLocation = cityName + "," + countryName;
Log.e(TAG, "location: " + rLocation);
deliverResultToReceiver(Constants.SUCCESS_RESULT,rLocation);
}
}
//To deliver the result back to the activity which started the service
private void deliverResultToReceiver(int resultCode, String message) {
//mReceiver = new ResultReceiver(this);
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
mReceiver.send(resultCode, bundle);
Log.e(TAG,"Delivering result"+message);
}
}
//Constant class to store all constants in one place
public final class Constants {
public static final int SUCCESS_RESULT = 0;
public static final int FAILURE_RESULT = 1;
public static final String PACKAGE_NAME =
"your package name";
public static final String RECEIVER = PACKAGE_NAME + ".RECEIVER";
public static final String RESULT_DATA_KEY = PACKAGE_NAME +
".RESULT_DATA_KEY";
public static final String LOCATION_DATA_EXTRA = PACKAGE_NAME +
".LOCATION_DATA_EXTRA";
}
//call this GetAddressService from your activity
private AddressResultReceiver mResultReceiver;
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
Intent intent = new Intent(this,GetAddressService.class);
intent.putExtra(Constants.RECEIVER,mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA,loc);
startService(intent);
}
//class to receive the address back from the service
class AddressResultReceiver extends ResultReceiver{
/**
* Create a new ResultReceive to receive results. Your
* {#link #onReceiveResult} method will be called from the thread running
* <var>handler</var> if given, or from an arbitrary thread if null.
*
* #param handler
*/
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
Log.e(TAG,"Address is:"+mAddressOutput);
}
}

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

Latitude and Longitude are null

I'm working on an app getting user's current location and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code
#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));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception
01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main
Process: io.xgear.geotag, PID: 29286
java.lang.NullPointerException
at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
this is the piece of code for getting latitude and longitude to send
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
and this is the full code
package io.xgear.geotag;
import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;
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.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
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
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
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;
}
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
btnGeoTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#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));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#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 boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
UPDATE
I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because
if( location != null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
is giving me errors .
The lines I have added
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
Location location;
void onCreate() {
....
location = locationManager.getLastKnownLocation(provider);
....
}
}
Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
...
}
inside GeoTagTask location object is different one and also doesn't initilized.
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());

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

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.

Categories