android- requestLocationUpdates() working in ICS but not in android 2.2 - android

When running the application in android 2.2 the GPS is searching for location but doesn't show any location. This application is working perfectly in ICS version. What will be the reason?
Thanks in advance.
This is the complete code :-
package com.example.gps;
import android.app.Activity;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Location;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
import java.io.IOException;
public class GPSmap extends Activity implements LocationListener {
public String mLatLongString = "";
private String mBest;
private TextView myLocationText;
LocationManager mLocManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.activity_gpsmap);
myLocationText = (TextView) findViewById(R.id.myLocationText);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
R.drawable.ic_launcher);
mLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
Criteria mCriteria = new Criteria();
mCriteria.setAccuracy(Criteria.ACCURACY_FINE);
mBest = mLocManager.getBestProvider(mCriteria, true);
if (mLocManager.isProviderEnabled(mBest)) {
}
} catch (NullPointerException e) {
myLocationText = (TextView) findViewById(R.id.myLocationText);
myLocationText.setText("\n\nGPS Tracking: Disabled.");
}
}
private void updateWithNewLocation(Location mLocation) {
myLocationText = (TextView) findViewById(R.id.myLocationText);
if (mLocation != null) {
double mLatitude = mLocation.getLatitude();
double mLongitude = mLocation.getLongitude();
double mLatitudeFormatted = (double) Math.round(mLatitude * 100000) / 100000;
double mLongitudeFormatted = (double) Math
.round(mLongitude * 100000) / 100000;
mLatLongString = mLatitudeFormatted + ", " + mLongitudeFormatted;
myLocationText.setText(mLatLongString);
} else {
mLatLongString = "\n\nNo Location Found.";
myLocationText.setText(mLatLongString);
}
}
/** Function to listen to location change */
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
protected void onResume() {
try {
super.onResume();
mLocManager.removeUpdates((android.location.LocationListener) this);
mLocManager.requestLocationUpdates(mBest, 60000L, 0.0f, this);
} catch (NullPointerException e) {
myLocationText = (TextView) findViewById(R.id.myLocationText);
myLocationText.setText("\n\nGPS Tracking: Disabled.");
}
}
}

Related

GPS Location returns always null

I am trying to access gps location in my activity but always getting null when calling getLastKnownLocation of LocationManager class. I have added following permissions also.My GPS in enabled and I have no internet on the device.Kindly guide me what am i doing wrong
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and also checking in code. below is my code.
public class MainActivity extends AppCompatActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
2);
}
} catch (Exception e) {
e.printStackTrace();
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latituteField.setText(location.getLatitude()+"");
longitudeField.setText(location.getLongitude()+"");
}else{
latituteField.setText("not found");
longitudeField.setText("not found");
}
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
implement this in your build.gradle,
implementation 'com.google.android.gms:play-services-location:17.0.0'
Try this code. It is working fine for me..
package com.example.geolocation;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
public class MainActivity extends AppCompatActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private FusedLocationProviderClient fusedLocationClient;
private String TAG=MainActivity.class.getSimpleName();
LocationCallback mLocationCallback;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
2);
}
} catch (Exception e) {
e.printStackTrace();
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
Log.d(TAG, "onCreate: not enabled gps");
else {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.d(TAG, "locationStatusCheck: onLocationResult null");
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
//TODO: UI updates.
Log.d(TAG, "locationStatusCheck: onLocationResult not null");
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Log.d(TAG, "latitudeField: " + latituteField);
Log.d(TAG, "longitudeField: " + longitudeField);
}
}
}
};
LocationServices.getFusedLocationProviderClient(getApplicationContext()).requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}

Latitude and Longitude showing as 0 in Android

************* TrackGPS.java *****************************
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
/**
* Created by ANQ on 8/8/2016.
*/
public class TrackGPS extends Service implements LocationListener {
private final Context mContext;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public TrackGPS(Context mContext) {
this.mContext = mContext;
getLocation();
}
private Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
catch(SecurityException e){
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}
public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
}
return latitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(TrackGPS.this);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
************* MainActivity.java ****************
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button b_get;
private TrackGPS gps;
double longitude;
double latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_get = (Button)findViewById(R.id.get);
b_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gps = new TrackGPS(MainActivity.this);
if(gps.canGetLocation()){
longitude = gps.getLongitude();
latitude = gps .getLatitude();
Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
}
else
{
gps.showSettingsAlert();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
gps.stopUsingGPS();
}
}
When i am running the application the latitude and longitude is showing as 0.0, i am using android marshmallow to test this application. "http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/" this is the link that i have used to create the application.
Please manage required permission for marshmallow.
First you add this permission in manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
After in your activity First declare two variable like this,
private static final int REQUEST_CODE_PERMISSION = 1;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
After in onCreate method
if(Build.VERSION.SDK_INT>= 23) {
if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{mPermission,
},
REQUEST_CODE_PERMISSION);
return;
}
else
{
*here manage your code if permission already access
}
}
Here is the background service to detect current location at time interval
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
#SuppressWarnings("MissingPermission")
public class LocationBackGroundService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationBackGroundService";
private static final long INTERVAL = 10;
private static final long FASTEST_INTERVAL = 10;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
Context mCOntext;
public void LocationBackGroundService(Context mContext) {
this.mCOntext = mContext;
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mGoogleApiClient.connect();
}
#Override
public void onCreate() {
super.onCreate();
if (!isGooglePlayServicesAvailable()) {
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
return false;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#SuppressLint("LongLogTag")
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"OnConnection Suspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"OnConnection Failed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
if (null != mCurrentLocation) {
mCurrentLocation = location;
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LATITUDE, lat);
ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LONGTITUDE, lng);
System.out.println("First Condition Hit");
System.out.println("Lat::-- " + lat + "\n" + "LONG::--" + lng);
}
System.out.println("Lat::-- " + location.getLatitude() + "\n" + "LONG::--" + location.getLongitude());
}
}
Put this code in seperate java file named LocationBackGroundService.java and call it in your MainActivity like this startService(new Intent(this, LocationBackGroundService.class)); and don't forget to add it in menifest like this <service android:name="LocationBackGroundService"></service>

how I can get the city name of my current position?

I'm working with android studio and in a popup dialog I want that users can get their position but all I know to do is get my latitude and longitude.
This is the code
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
in the MainActivity.Can you help me?
I've added this in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
but it still says "Location not available".
You need the GeoCoder class to get Address from a given Lat/Long. try the following:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault()); //it is Geocoder
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
} catch (IOException e) {}
catch (NullPointerException e) {}
Code below should work for you: (Check the inline comments regarding your code)
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05); //Make sure you add this to activity_main
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {
// Handle IOException
} catch (NullPointerException e) {
// Handle NullPointerException
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
You need to execute the Geocoder in a AsyncTask (or in a Thread not in the same ThreadGroup as the UI Thread)!
public void getCityName(final Location location, final OnGeocoderFinishedListener listener) {
new AsyncTask<Void, Integer, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... arg0) {
Geocoder coder = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> results = null;
try {
results = coder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
// nothing
}
return results;
}
#Override
protected void onPostExecute(List<Address> results) {
if (results != null && listener != null) {
listener.onFinished(results);
}
}
}.execute();
}
With this abstract Listener
public abstract class OnGeocoderFinishedListener {
public abstract void onFinished(List<Address> results);
}
Now call the method like this:
getCityName(location, new OnGeocoderFinishedListener() {
#Override
public void onFinished(List<Address> results) {
// do something with the result
}
});
Hope this will help some of you!
You can use google api to get current location address. Check out my answer in this post go get your city.
How to get city name from latitude and longitude coordinates in Google Maps?

Getting longitude and latitude works in emulator but not on device?

I've been trying to work GPS coordinates but it's been a lot tougher than I thought. After a few hours of trial and error, I've managed to output the latitude and longitude (mocked) for my emulator. Below are the 2 ways I've done it:
First way:
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String text = "";
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
showMyAddress(location);
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
showMyAddress(location);
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, locationListener);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.i(TAG, "longitude: " + longitude);
Log.i(TAG, "latitude: " + latitude);
text = "longitude: " + longitude + ", " + "latitude: " + latitude;
TextView textView = (TextView) findViewById(R.id.txtvwMain);
textView.setText(text);
}
private void showMyAddress(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> myList;
try {
myList = myLocation.getFromLocation(latitude, longitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Second way:
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity implements LocationListener
{
private LocationManager lm;
private TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.txtvwMain);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
Location location = lm.getLastKnownLocation(lm.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
tv.setText("latitude="+latitude+", longitude="+longitude);
}
#Override
public void onLocationChanged(Location arg0) {
String lat = String.valueOf(arg0.getLatitude());
String lon = String.valueOf(arg0.getLongitude());
Log.e("GPS", "location changed: lat="+lat+", lon="+lon);
tv.setText("lat="+lat+", lon="+lon);
}
public void onProviderDisabled(String arg0) {
Log.e("GPS", "provider disabled " + arg0);
}
public void onProviderEnabled(String arg0) {
Log.e("GPS", "provider enabled " + arg0);
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
Log.e("GPS", "status changed to " + arg0 + " [" + arg1 + "]");
}
}
Both ways above work and print out the mock latitude and longitude onto a TextView in the emulator (running Android 4.2.2). However, when I upload the .apk file onto my device (tablet running Android 4.0.4), it just crashes. I don't know what's wrong because I can't see any error messages. What is the source of the problem and how may I go about solving it? Thanks.

NullPointerException When Trying To Fetch Current Location

I am trying to Set Location but getting NullPointerException , i have Provided android.permission.ACCESS_COARSE_LOCATION , android.permission.ACCESS_FINE_LOCATION
In manifest file my Source code is as Follow , i am getting Null pointer on
List<Address> addresses = new Geocoder(LocationDemo.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
My Coding is As Follow
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class LocationDemo extends Activity {
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
String store;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addressText = (TextView)findViewById(R.id.addressText);
addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try{
List<Address> addresses = new Geocoder(LocationDemo.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
store = addressText.getText().toString();
}
catch(IOException ex)
{
addressText.setText(ex.getMessage().toString());
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}
}
i am importing this code in application that extends Service that is trying to obtain Address on startup of service
Might be you are getting current location as null. as it takes some time to calculate the location .if this is the case , try this
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class LocationDemo extends Activity {
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
String store;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addressText = (TextView)findViewById(R.id.addressText);
addressText.setText("ready");
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
setAddress(location)
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void setAddress(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
try{
List<Address> addresses = new Geocoder(LocationDemo.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
StringBuilder result = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
result.append(address.getAddressLine(x));
//result.append(",");
}
}
addressText.setText(result.toString());
Intent send_add = new Intent();
send_add.putExtra("address",result.toString());
store = addressText.getText().toString();
}
catch(IOException ex)
{
addressText.setText(ex.getMessage().toString());
}
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER) };
try this code in your Location Listener.
Of course you're getting a null pointer because currentLocation is null till onLocationChanged is called. Thus you have to put your code there:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// put your code here once you have the location
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};

Categories

Resources