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) {}
};
Related
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?
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.");
}
}
}
I'm new on android programation and I have a problem with my aplication.
My Gps just doesn't search for location, or anything else.
And yes, my GPS is tunned on.
The manifest cointains the permitions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Could somebody help me?
public class LocationTest extends Activity implements
LocationListener {
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
"high" };
private static final String[] S = { "out of service",
"temporarily unavailable", "available" };
private LocationManager mgr;
private TextView output;
private String best;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
log("Location providers:");
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
log("\nBest provider is: " + best);
log("\nLocations (starting with last known):");
if (best != null) {
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
}
}
#Override
protected void onResume() {
super.onResume();
// Start updates (doc recommends delay >= 60000 ms)
if (best != null) {
mgr.requestLocationUpdates(best, 15000, 1, this);
}
}
#Override
protected void onPause() {
super.onPause();
// Stop updates to save power while app paused
mgr.removeUpdates(this);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
log("\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider) {
log("\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
log("\nProvider status changed: " + provider + ", status="
+ S[status] + ", extras=" + extras);
}
/** Write a string to the output window */
private void log(String string) {
output.append(string + "\n");
}
/** Write information from all location providers */
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String provider : providers) {
dumpProvider(provider);
}
}
/** Write information from a single location provider */
private void dumpProvider(String provider) {
LocationProvider info = mgr.getProvider(provider);
StringBuilder builder = new StringBuilder();
builder.append("LocationProvider[")
.append("name=")
.append(info.getName())
.append(",enabled=")
.append(mgr.isProviderEnabled(provider))
.append(",getAccuracy=")
.append(A[info.getAccuracy() + 1])
.append(",getPowerRequirement=")
.append(P[info.getPowerRequirement() + 1])
.append(",hasMonetaryCost=")
.append(info.hasMonetaryCost())
.append(",requiresCell=")
.append(info.requiresCell())
.append(",requiresNetwork=")
.append(info.requiresNetwork())
.append(",requiresSatellite=")
.append(info.requiresSatellite())
.append(",supportsAltitude=")
.append(info.supportsAltitude())
.append(",supportsBearing=")
.append(info.supportsBearing())
.append(",supportsSpeed=")
.append(info.supportsSpeed())
.append("]");
log(builder.toString());
}
/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
if (location == null)
log("\nLocation[unknown]");
else
log("\n" + location.toString());
}
}
I normally don't do this, but I almost have to go.
This is the code I use, it works. (just put this in a new project).
I didn't clean it, because I ripped it from my other project, but it does work, when you make a new project and just copy/paste this.:
import java.util.Timer;
import java.util.TimerTask;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
Timer timer1;
LocationManager lm;
boolean gps_loc = false;
boolean gps_enabled=false;
boolean network_enabled=false;
double lat;
double lng;
String gps_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
lat = location.getLatitude();
lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat + " " + sLng;
Toast.makeText(getBaseContext(), "We got gps location!",
Toast.LENGTH_LONG).show();
System.out.println("We got gps");
System.out.println("lat = "+lat);
System.out.println("lng = "+lng);
}
} catch (Exception e) {
}
}
};
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 35000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Also add this in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
No time to explain now, maybe tomorrow if you still need it.
It prints the latitude and longitude in your logcat.
my following coding for getting current address means location is failed if i try to set address to the TextBox but when i put that code inside a onClick event of Button that works properly
This is Coding is Working When it is inside a onCLick event
import java.io.IOException;
import java.util.*;
import android.widget.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.location.*;
import android.content.*;
public class location extends Activity {
Button addressButton;
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
addressText = (TextView)findViewById(R.id.addressText);
addressButton = (Button)findViewById(R.id.addressButton);
this.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);
this.addressButton.setOnClickListener(new OnClickListener() {
public void onClick(View v){
try{
Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
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());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
});
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}}
This is Coding not Working here i dont want to use Button when i open this activity it must display direct address means it should be Set to the Textview
public class location extends Activity {
Button addressButton;
TextView addressText;
Location currentLocation;
double currentLatitude;
double currentLongitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
addressText = (TextView)findViewById(R.id.addressText);
addressButton = (Button)findViewById(R.id.addressButton);
this.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);
try{
Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
List<Address> addresses =
gcd.getFromLocation(currentLatitude, currentLongitude,100);
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());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
}
void updateLocation(Location location){
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
}}
Here i just made a small change but not working
I have updated your code and it is working correct now :
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); //added by me
// Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
try{
// Geocoder gcd = new Geocoder(location.this, Locale.getDefault());
//List<Address> addresses =
// gcd.getFromLocation(currentLatitude, currentLongitude,100);
List<Address> addresses = new Geocoder(location.this,Locale.getDefault()).getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1); // changed
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());
}
catch(IOException ex){
addressText.setText(ex.getMessage().toString());
}
Hi to all im new to android and i have a small problem and i would really appreciate if someone can help me
first im trying to show all available location providers and its not working and 2nd when ever i run the it i don't get any location information from the best available provider (i have my wifi and network providers on)
thanks in advance
package com.paad.whereami;
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;
public class WhereAmI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
boolean enabledOnly = true;
List<String> providers = locationManager.getProviders(enabledOnly);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setSpeedRequired(true);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 1,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
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){ }
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString + "\n" + addressString);
}
}
I had also same problem before, after searching a lot...came to solution and makes it possibale to get instant location of device through following code...actuallu we can not have gps responce instantly so we can have our location on the basis of cell-tower or wifi. so enable one of them to get instant location of your device..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leopard_screen);
FindLocation(this);
}
public void FindLocation(Context context) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
Log.i("########## Network provider is enabled", "Network Provider");
} else {
Toast.makeText(LeopardScreen.this,
"Network provider is not enabled", 2000);
}
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListenerGPS);
Log.i("########## GPS provider is enabled", "GPS Provider");
} else {
Toast.makeText(LeopardScreen.this, "GPS provider is not enabled",
2000);
}
if(!network_enabled && !gps_enabled) {
currentLocation = getMyLastKnownLocation();
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
Log.i("######## Both location provider disabled",
"getMylastKnownLocation = "+String.valueOf(currentLatitude)
+ " : " + String.valueOf(currentLongitude));
Toast.makeText(LeopardScreen.this,"LastKnownLocation\n"+String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 3000).show();
Intent intent = new Intent(LeopardScreen.this, mainActivity.class);
startActivity(intent);
}
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
handler.removeCallbacks(runnable);
Log.i("######## Inside FindLocation", "Inside FindLocation");
Toast.makeText(
LeopardScreen.this,"Network Location \n"+
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocation(location);
Log.i("########## Inside onLocationChangedGPS", String
.valueOf(currentLatitude)
+ " : " + String.valueOf(currentLongitude));
Toast.makeText(
LeopardScreen.this,
"GPS Location \n" + String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
public Location getMyLastKnownLocation () {
Location locNetwrok = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location locGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(locNetwrok != null)
return locNetwrok;
else if(locGPS != null)
return locGPS;
return null;
}
void updateLocation(Location location) {
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
Log.i("######## Inside LeopardScreen locationChanged",
"locationChanged");
}
Don't Forgot to add in Menifeast
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>