Reputation: 185
My app fetches the users coordinates. Now I try to get the name of the city where the coordinates belong to. I searched the other threads, but I didn‘t find something helpful or new about it. My textView that should show the address name just stays empty, or is it a wrong way to fetch an address?
My code:
public class MainActivity extends AppCompatActivity {
double lat;
double lon;
Button btnLoc;
TextView textView7;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView7 = (TextView) findViewById(R.id.textView7);
btnLoc = (Button) findViewById(R.id.btnGetLoc);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
btnLoc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
GPSTracker gt = new GPSTracker(getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
Toast.makeText(getApplicationContext(), "GPS unable to get Value", Toast.LENGTH_SHORT).show();
} else {
double lat = location.getLatitude();
double lon = location.getLongitude();
TextView textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText(String.valueOf(lat));
TextView textView6 = (TextView) findViewById(R.id.textView6);
textView6.setText(String.valueOf(lon));
}
}
});
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
if (addresses.size() > 0)
textView7.setText(addresses.get(0).getLocality());
} catch (IOException e) {
}
}
}
Upvotes: 1
Views: 498
Reputation: 96
A few things I noticed.
You are not initializing the lat and long that you defined in your activity scope.
double lat; double lon;
These will remain null when you pass them into your function
List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);
So you may want to try removing the types from your lat/long variables inside your click function.
- double lat = location.getLatitude();
- double lon = location.getLongitude();
+ lat = location.getLatitude();
+ lon = location.getLongitude();
If that doesn't work take a look at this short helpful guide https://www.kerstner.at/2013/08/convert-gps-coordinates-to-address-using-google-geocoding-api-in-java/
Cheers
Upvotes: 1