How to get city information in android by longitude and latitude - java

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

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 make the mapview get from current location?

As title, how to make the mapview zoom into the current location? By the way, I can get the current Log and Lon in getLocation(). Just don't know how to implement into the map. Thanks in advance someone who can help me.. I'm new to the android studio. This problem have make me confuse few day already.
package com.example.edward.neweventmanagementsystem;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class StaffAttendanceCheckIn extends AppCompatActivity {
private TextView mtxtTime, mtxtDate, txtDisplayName;
private Spinner eventSpinner;
private static final int REQUEST_LOCATION = 1;
TextView textLocation;
LocationManager locationManager;
String latitude,longitude;
MapView mapview;
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staff_attendance_check_in);
mtxtDate = (TextView) findViewById(R.id.txtCurrentDate);
mtxtTime = (TextView) findViewById(R.id.txtCurrentTime);
txtDisplayName = (TextView) findViewById(R.id.txtDisplayName);
eventSpinner = (Spinner) findViewById(R.id.eventSpinner);
mapview = (MapView) findViewById(R.id.mapview);
mapview.onCreate(savedInstanceState);
SimpleDateFormat date = new SimpleDateFormat("EEEE dd MMM yyyy", Locale.ENGLISH);
String currentDate = date.format(new Date());
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
String currentTime = time.format(new Date());
mtxtDate.setText(currentDate);
mtxtTime.setText(currentTime);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
txtDisplayName.setText(currentFirebaseUser.getDisplayName());
/**
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("EventName");
System.out.println("Test Script: " + myRef); */
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
textLocation = (TextView)findViewById(R.id.location);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLocation();
}
}
// #Override
// public void onClick(View view) {
//
// }
private void getLocation() {
if (ActivityCompat.checkSelfPermission(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(com.example.edward.neweventmanagementsystem.StaffAttendanceCheckIn.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location2 = locationManager.getLastKnownLocation(LocationManager. PASSIVE_PROVIDER);
if (location != null) {
double latti = location.getLatitude();
double longi = location.getLongitude();
latitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
float ZOOM_MAP = 17.0f;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
map.animateCamera(myLocation);
// CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(latLng, ZOOM_MAP);
// System.out.println("Test Script" + myLocation);
// map.animateCamera(myLocation);
} else if (location1 != null) {
double latti = location1.getLatitude();
double longi = location1.getLongitude();
latitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
} else if (location2 != null) {
double latti = location2.getLatitude();
double longi = location2.getLongitude();
latitude = String.valueOf(latti);
longitude = String.valueOf(longi);
textLocation.setText("Lat = " + latitude + "\n" + "Lon = " + longitude);
}else{
Toast.makeText(this,"Unble to Trace your location",Toast.LENGTH_SHORT).show();
}
}
}
protected void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please Turn ON your GPS Connection")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
protected void onDestroy(){
super.onDestroy();
mapview.onDestroy();
}
#Override
public void onLowMemory(){
super.onLowMemory();
mapview.onLowMemory();
}
#Override
protected void onPause(){
super.onPause();
mapview.onPause();
}
#Override
protected void onResume(){
super.onResume();
mapview.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapview.onSaveInstanceState(outState);
}
}
It's very easy you just need to do like:
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
mMap.animateCamera(myLocation);
ZOOM_MAP its float
Update ----
mapview.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(yourLatLng, ZOOM_MAP);
googleMap.animateCamera(myLocation);
}
});

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
}

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

Not getting user location using GPS_PROVIDER / NETWORK_PROVIDER

I am trying to implement a simple location app that will show the user location from GPS (if GPS on) on a button click and the user location from NETWORK_PROVIDER on another button click. What I am trying to do is given below-
AppLocationService.java
package com.android.imran.userlocation;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class AppLocationService extends Service implements LocationListener{
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if(locationManager.isProviderEnabled(provider))
{
locationManager.requestLocationUpdates(provider,MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#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;
}
}
MainActivity.java
package com.android.imran.userlocation;
import android.location.Location;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView showLocation;
Button getLocationGPS;
Button getLocationNW;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showLocation=(TextView)findViewById(R.id.showLocation);
getLocationGPS=(Button)findViewById(R.id.getLocationGPS);
getLocationNW=(Button)findViewById(R.id.getLocationNW);
getLocationGPS.setOnClickListener(this);
getLocationNW.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.getLocationGPS:
Location gpsLocation = new AppLocationService(getApplicationContext()).getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
showLocation.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
Toast.makeText(getApplicationContext(), "Mobile Location (GPS): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
break;
case R.id.getLocationNW:
Location nwLocation = new AppLocationService(getApplicationContext()).getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
showLocation.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
Toast.makeText(getApplicationContext(), "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
break;
}
}
}
This app doesn't show any output.
You can get the location from onLocationChanged method that you override
#Override
public void onLocationChanged(Location location) {
// Listen for location
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), "Mobile Location (GPS): \nLatitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_LONG).show();
}
EDIT :
Simple code sample of how I got the location -
MainActivity.java
private LocationManager locationManager;
private double longitudeGPS, latitudeGPS;
private TextView locationView;
private final LocationListener locationListenerGPS = new LocationListener() {
public void onLocationChanged(Location location) {
longitudeGPS = location.getLongitude();
latitudeGPS = location.getLatitude();
runOnUiThread(new Runnable() {
#Override
public void run() {
String loc = longitudeGPS + " , " + latitudeGPS;
locationView.setText(loc);
Toast.makeText(NewComplaintActivity.this, "GPS Provider update", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationView = (TextView) findViewById(R.id.location_view);
if (!checkLocation()){
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000 * 60, 10, locationListenerGPS);
}
}
private boolean checkLocation() {
if (!isLocationEnabled())
// ask user to enable location
return isLocationEnabled();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
Don't forget to add
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Categories