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

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

Related

com.google.android.gms.location.LocationListener's LocationChanged not called

I am creating a service in which I request for locationUpdate .But
LocationChanged callback is called only when the service first started after that is not called.Location changed should be invoked on 2km changed .Is I am doing something wrong
package com.example.qwerty;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import android.os.IBinder;
//Location Callback
public class LocationService extends Service implements ConnectionCallbacks,OnConnectionFailedListener {
private class locationListener implements LocationListener {
public void addLocation(String loc){
SharedPreferences pref= getSharedPreferences(Contant.MYPREFERENCE, MODE_PRIVATE);
Editor edit = pref.edit();
String s ="";
if(pref.contains("location")){
s = pref.getString("location", "");
}
s = s + loc;
edit.putString("location",s).commit();
}
public void getAddress( final double latitude , final double longitude){
new AsyncTask<Double, Void, String>() {
#Override
protected String doInBackground(Double...params){
Geocoder geocoder = new Geocoder(LocationService.this,Locale.getDefault());
String result ="";
List<Address> addressList =null;
try {
addressList = geocoder.getFromLocation(
params[0], params[1], 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
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());
result = sb.toString();
}
}
catch (Exception e) {
result =e.toString();
result = result + " " + latitude + " "+ longitude;
}
return result;
}
#Override
protected void onPostExecute(String result) {
addLocation(result);
}
}.execute(latitude , longitude);
}
#Override
public void onLocationChanged(Location location) {
if(NetworkState.isNetConnected(LocationService.this)) {
getAddress(location.getLatitude(), location.getLongitude());
}else{
addLocation(" lat " + location.getLatitude()+ " long " + location.getLongitude());
}
}
}
GoogleApiClient client = null;
public LocationService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences pref= getSharedPreferences(Contant.MYPREFERENCE, MODE_PRIVATE);
client = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
client.connect();
return START_STICKY;
}
#Override
public void onDestroy() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle arg0) {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(420000);
mLocationRequest.setSmallestDisplacement(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(client, mLocationRequest , new locationListener());
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
}
I got another solution that work for me.may be it helps other in near future.
Set up alaram for n minutes
On this alaram set a broadcast.When you receive broadcast start a service which will get the current location.
After getting location stop that service.
The same thing goes on and on.

Trouble in reverse Geo-coding while converting co-ordinates to address using getFromLocation

I am having trouble reversing Geo-coding using getFromLocation.
I am using Android Studio and passing the Coordinates via the Device Monitor.
The coordinates show alright, but the address remains empty.
I have tried a number of solutions posted here on StackOverflow, even known none crashes, I still can't get the address.
Here is the snippet of the code. I am using.
#Override
public void onLocationChanged(Location location){
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
//Get address base on location
try{
Geocoder geo = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geo.getFromLocation(lat, lng, 1);
if (addresses.isEmpty()) {
endereco.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
On the Geocoder line, I have tried this aswell
Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault());
And if needed here is the code of the entire activity
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.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Locale;
/**
* Created by Usuário on 05/02/2015.
*/
public class GPSActivity extends Activity implements LocationListener {
private static final String TAG = null;
private TextView latituteField;
private TextView longitudeField;
private TextView endereco;
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.gps);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
endereco = (TextView) findViewById(R.id.Endereco);
//Get the Location Manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Define the criteria how to select location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null){
System.out.println("Provider " + provider + " has been selected");
onLocationChanged(location);
}else{
latituteField.setText("Locação não disponível");
longitudeField.setText("Locação não disponível");
}
}
/**
* Request updates at startup
*/
#Override
protected void onResume(){
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/**
* Remove the LocationListener updates when Activity is paused
*/
#Override
protected void onPause(){
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location){
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
//Get address base on location
try{
Geocoder geo = new Geocoder(GPSActivity.this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(lat, lng, 1);
if (addresses.isEmpty()) {
endereco.setText("Waiting for Location");
}
else {
if (addresses.size() > 0) {
Log.d(TAG,addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() +", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
//TODO Auto-generated method tub
}
#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();
}
}
I made a couple of changes in the code and manage to get it to work.
The thing that solved the problem is the bit.
char[] buffer = new char[2048];
Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
while (true) {
int n = reader.read(buffer);
if (n < 0) {
break;
}
stringBuilder.append(buffer, 0, n);
}
But since I changed a lot of stuff, I will post the complete code bellow.
package br.com.agenciaeisberg.qm;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Created by Usuário on 05/02/2015.
*/
public class GPSActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView endereco;
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.gps);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
endereco = (TextView) findViewById(R.id.Endereco);
//Get the Location Manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Define the criteria how to select location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria,false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null){
System.out.println("Provider " + provider + " has been selected");
onLocationChanged(location);
}else{
latituteField.setText("Locação não disponível");
longitudeField.setText("Locação não disponível");
}
}
/**
* Request updates at startup
*/
#Override
protected void onResume(){
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/**
* Remove the LocationListener updates when Activity is paused
*/
#Override
protected void onPause(){
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location){
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
// Encontrando Endereço
new EncontrarEndereco().execute();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
//TODO Auto-generated method tub
}
#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();
}
class EncontrarEndereco extends AsyncTask<String, String, JSONObject> {
ProgressDialog pDialog = new ProgressDialog(GPSActivity.this);
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.setMessage("Aguarde, enquanto buscamos seu endereço");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
double lat = -19.971864410192393;
double lng = -43.97544760674483;
HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true&language=pt&region=BR&output=xml&oe=utf8");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
protected JSONObject doInBackground (String... args){
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
char[] buffer = new char[2048];
Reader reader = new InputStreamReader(entity.getContent(), "UTF-8");
while (true) {
int n = reader.read(buffer);
if (n < 0) {
break;
}
stringBuilder.append(buffer, 0, n);
}
int b;
while ((b = reader.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
protected void onPostExecute(final JSONObject jsonObject) {
// Dismiss a caixa de dialogo depois de buscar todos os items
String numero;
String rua;
String bairro;
String cidade;
String estado;
String pais;
String endereco_compelto;
pDialog.dismiss();
Log.i("JSON string =>", jsonObject.toString());
try {
String status = jsonObject.getString("status");
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObject.getJSONArray("results");
JSONObject r = results.getJSONObject(0);
JSONArray addressComponentsArray = r.getJSONArray("address_components");
JSONObject addressComponents = addressComponentsArray.getJSONObject(0);
numero = addressComponents.getString("short_name");
Log.i("Número", numero);
JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1);
rua = addressComponents1.getString("long_name");
Log.i("Rua", rua);
JSONObject addressComponents2 = addressComponentsArray.getJSONObject(2);
bairro = addressComponents2.getString("long_name");
Log.i("Bairro ", bairro);
JSONObject addressComponents3 = addressComponentsArray.getJSONObject(3);
cidade = addressComponents3.getString("long_name");
Log.i("Cidade ", cidade);
JSONObject addressComponents5 = addressComponentsArray.getJSONObject(5);
estado = addressComponents5.getString("short_name");
Log.i("Estado ", estado);
JSONObject addressComponents6 = addressComponentsArray.getJSONObject(6);
pais = addressComponents6.getString("long_name");
Log.i("Pais ", pais);
endereco_compelto = rua + ", " + numero + " - " + bairro + ", " + cidade + " - " + estado + ", " + pais;
endereco.setText(endereco_compelto);
}
}catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
}
}
}

Using AsyncTask to get location information

I'm trying to get user's current location coordinates and address using reverse geocoding.
As This process takes some time, I want to show a progress bar during that time, so I'm using AsyncTask. So, what basically I'm doing is, from one activity's onClick event I start the AsyncTask which finds me the location informations and then from that AsyncTask I start another activity which uses that Information.
This is my First Activity where onClick event starts the AsyncTask:
public void onClickGirl(View view)
{
(new MyAsyncTask(MainActivity.this)).execute();
}
This is the AsyncTask:
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context.getApplicationContext();
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(null, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
Location location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
onLocationChanged(location);
} else {
Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
This is the Second Activity which run after AsyncTask:`
Intent ixx = getIntent();
elat = Double.parseDouble(ixx.getStringExtra("calculated_Lat"));
elon = Double.parseDouble(ixx.getStringExtra("calculated_Lon"));
eAddress1 = ixx.getStringExtra("calculated_address");
And This is the LogCat:
02-01 17:15:26.734: E/AndroidRuntime(2587): java.lang.IllegalStateException: Could not execute method of the activity
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View$1.onClick(View.java:3814)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.view.View.performClick(View.java:4424)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.handleCallback(Handler.java:733)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 17:15:26.734: E/AndroidRuntime(2587): at android.os.Looper.loop(Looper.java:137)
I have spent hours after this but can't find the problem. Can anyone please help me finding out what I'm missing??
Please find the updated code and test it at your end and let me know in case you have any query:
package com.example.tabhost;
import java.util.List;
import java.util.Locale;
import android.app.Dialog;
import android.app.ProgressDialog;
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.os.Bundle;
import android.text.Html;
import android.util.Log;
public class MyAsyncTask extends AsyncTask<Void, Void, Void> implements LocationListener {
private Context ContextAsync;
public MyAsyncTask (Context context){
this.ContextAsync = context;
}
Dialog progress;
private String providerAsync;
private LocationManager locationManagerAsync;
double latAsync=0.0;
double lonAsync=0.0;
String thikanaAsync="Scan sms for location";
String AddressAsync="";
Geocoder GeocoderAsync;
Location location;
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = ProgressDialog.show(ContextAsync, "Loading data", "Please wait...");
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
locationManagerAsync = (LocationManager) ContextAsync.getSystemService(ContextAsync.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
providerAsync = locationManagerAsync.getBestProvider(criteria, false);
if (locationManagerAsync.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
providerAsync = LocationManager.GPS_PROVIDER;
} else if (locationManagerAsync.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
providerAsync = LocationManager.NETWORK_PROVIDER;
/*AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("GPS is disabled in the settings!");
alert.setMessage("It is recomended that you turn on your device's GPS and restart the app so the app can determine your location more accurately!");
alert.setPositiveButton("OK", null);
alert.show();*/
} else if (locationManagerAsync.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
providerAsync = LocationManager.PASSIVE_PROVIDER;
//Toast.makeText(ContextAsync, "Switch On Data Connection!!!!", Toast.LENGTH_LONG).show();
}
location = locationManagerAsync.getLastKnownLocation(providerAsync);
// Initialize the location fields
if (location != null) {
// System.out.println("Provider " + provider + " has been selected.");
latAsync = location.getLatitude();
lonAsync = location.getLongitude();
} else {
//Toast.makeText(ContextAsync, " Locationnot available", Toast.LENGTH_SHORT).show();
}
List<Address> addresses = null;
GeocoderAsync = new Geocoder(ContextAsync, Locale.getDefault());
try {
addresses = GeocoderAsync.getFromLocation(latAsync, lonAsync, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getCountryName();
AddressAsync = Html.fromHtml(
address + ", " + city + ",<br>" + country).toString();
} catch (Exception e) {
e.printStackTrace();
AddressAsync = "Refresh for the address";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progress.dismiss();
onLocationChanged(location);
Log.v("latAsync_lonAsync",latAsync+"_"+lonAsync);
Intent intentAsync = new Intent(ContextAsync,Emerg.class);
intentAsync.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentAsync.putExtra("calculated_Lat", latAsync);
intentAsync.putExtra("calculated_Lon", lonAsync);
intentAsync.putExtra("calculated_address", AddressAsync);
ContextAsync.startActivity(intentAsync);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
locationManagerAsync.requestLocationUpdates(providerAsync, 0, 0, this);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
instead of using this.ContextAsync = context.getApplicationContext();
ContextAsync should have Activity instance, no ApplicationContext so use this.ContextAsync = context

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?

Location not updating

I have succeed in making a map that shows nearby locations but its not updating the locations...Is there something wrong with the code..coz i m not finding anythin wrong...any help wud be appreciated..thanks in advance
package com.example.travelplanner;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class NearbyPlacesActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
}
}
}
//location listener functions
#Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces(location);
}
#Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
#Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(Location givenlocation){
//get location manager
double lat = givenlocation.getLatitude();
double lng = givenlocation.getLongitude();
Toast.makeText(getApplicationContext(), lat+","+lng, Toast.LENGTH_LONG).show();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
#SuppressWarnings("deprecation")
String encodedstr = URLEncoder.encode("food|bar|movie_theater|museum|bank");
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=7000&sensor=true"+
"&types="+encodedstr+
"&key=AIzaSyBqDgqbxFenOtooTivY5YSsJ2JrwBK42hw";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("food")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("bar")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("movie_theater")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
#Override
protected void onResume() {
super.onResume();
if(theMap!=null){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
updatePlaces(lastLoc);
}
}
#Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
Please try to use this class.
public class LocationListenerClass {
private static LocationListenerClass instance;
private static Context context;
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private static Double latitude = 0d;
private static Double longitude = 0d;
public static LocationListenerClass getInstance(Context context) {
LocationListenerClass.context = context;
if (null == instance) {
instance = new LocationListenerClass();
}
return instance;
}
public void getCurrentLocation() {
try {
myLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 30000, 100,
myLocationListener);
Location location;
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 30000, 100,
myLocationListener);
location = myLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
try {
latitude = location.getLatitude();
Data.CURENT_LATITUDE = latitude;
Log.v(ConstantLib.LOG, " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = longitude;
Log.v(ConstantLib.LOG, " longitude : "
+ Data.CURENT_LONGITUDE);
} catch (Exception e) {
}
}
} catch (Exception e) {
}
}
public void removeLocationUpdates() {
try {
if (myLocationManager != null) {
myLocationManager.removeUpdates(myLocationListener);
}
} catch (Exception e) {
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
try {
if (location != null) {
Data.CURENT_LATITUDE = location.getLatitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = location.getLongitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " longitude : "
+ Data.CURENT_LONGITUDE);
}
} catch (Exception e) {
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

Categories

Resources