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

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?

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

Android:reverse geocoding-how to save the address for later use?

I am building a project which needs users current location.I am using reverse geocoding to get the exact address of the user.I am using asynctask to run the thread finding the exact address in background.This is my code:
package com.prince.geolocationtest;
import android.content.Context;
import android.content.Intent;
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.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView text, text2, text3;
LocationManager location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String bestProvider = location.getBestProvider(criteria, true);
try {
location.requestLocationUpdates(bestProvider, 0, 0, this);
} catch (SecurityException e) {
Log.e("Permission_Exception", "Permission Not granted");
}
// text=(TextView)findViewById(R.id.textView);
text2 = (TextView) findViewById(R.id.textView2);
Toast.makeText(getApplicationContext(), "Provider=" + bestProvider, Toast.LENGTH_SHORT).show();
}
public void AddDisp(String add) {
text3 = (TextView) findViewById(R.id.textView3);
text3.setText(add);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
AsyncTry obj = new AsyncTry(this);
obj.execute(lat, lon);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case 0:
Toast.makeText(getApplicationContext(), "Out Of Service", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "Temporarily Unavailable", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Available", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS is off", 3).show();
Intent GPSIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(GPSIntent);
}
public class AsyncTry extends AsyncTask<Double, Integer, String> {
Context context;
String add;
public AsyncTry(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Double... params) {
try {
StringBuilder str = new StringBuilder();
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
str.append("Latitude:" + params[0] + "\nLongitude:" + params[1] + "\n");
if (geocoder.isPresent()) {
List<Address> addresses = geocoder.getFromLocation(params[0], params[1], 1);
// str.append("Address:"+addresses.get(0).getLocality());
// str.append("\n"+addresses.get(0).getAdminArea());
// //String zip = addresses.get(0).getPostalCode();
// str.append("\n"+addresses.get(0).getCountryName());
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
str.append(fetchedAddress.getAddressLine(i)).append("\n");
}
}
add = str.toString();
//str.toString();
} else {
add = "Geocoder implementation doesnt exists";
}
} catch (Exception e) {
Log.d("Exception:", e.toString());
}
MainActivity.this.runOnUiThread(new Runnable() {
Location loc;
#Override
public void run() {
// TODO Auto-generated method stub
text2.setText(add);
}
});
return add;
}
protected void onpostExecute(String result) {
// super.onPostExecute(result);
if (result != null) {
text = (TextView) findViewById(R.id.textView);
text.setText(result);
AddDisp(result);
// Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Though the program returns the address and displays it in the main thread using runOnUiThread, I am not able to send the address to onPostExecute method of asyncTask. I need to use the address for later use rather than just displaying it.. how can I do that? I am using android studio IDE.
Use SharedPreferences:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
.putString("ADDRESS", add)
.apply();
To get it from SharedPreferences:
String address = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("ADDRESS", "");
You declared onPostExecute incorrectly. It should be like this:
#Override
protected void onPostExecute (String result);
Just rewrote your AsyncTask a little bit. You should pass the TexView you want to display the address to the AsyncTask. Does it work now ?
public class AsyncTry extends AsyncTask<Double, Integer, String> {
Context context;
TextView textView;
String add;
public AsyncTry(Context context, TextView textView) {
this.context = context;
this.textView = textView;
}
#Override
protected String doInBackground(Double... params) {
try {
StringBuilder str = new StringBuilder();
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
str.append("Latitude:" + params[0] + "\nLongitude:" + params[1] + "\n");
if (geocoder.isPresent()) {
List<Address> addresses = geocoder.getFromLocation(params[0], params[1], 1);
if (addresses != null) {
Address fetchedAddress = addresses.get(0);
for (int i = 0; i < fetchedAddress.getMaxAddressLineIndex(); i++) {
str.append(fetchedAddress.getAddressLine(i)).append("\n");
}
}
add = str.toString();
} else {
add = "Geocoder implementation doesnt exists";
}
} catch (Exception e) {
Log.d("Exception:", e.toString());
}
return add;
}
protected void onPostExecute(String result) {
if (result != null) {
textView.setText(result);
}
}
}

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

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

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

location problem

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"/>

Categories

Resources