How to get the data from the BroadcastReceiver to another class BroadcastReceiver - android

I am using the BroadcastReceiver in my application ,here i am receiving the current location and place in this class.hence i am getting the current location,hence my question is how to send this location string from this class to another class .i have to load this string data in the listview in another class so how can do this please help thanks in advance. My code is
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
MyTrip trip_method;
double latitude, longitude;
Context context;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
protected LocationManager locationManager;
Location location;
#Override
public void onReceive(Context context, Intent intent) {
trip_method = new MyTrip();
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Find_location();
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
public void Find_location() {
// Location nwLocation;
try {
location = getLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("nwLocation-------" + location);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println("latitude-------" + latitude + "longitude-----" + longitude);
Toast.makeText(
context,
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
// To display the current address in the UI
(new GetAddressTask()).execute(location);
} else {
trip_method.showSettingsAlert("NETWORK");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
/* *//**//*
* Following is a subclass of AsyncTask which has been used to get
* address corresponding to the given latitude & longitude.
*//**//**/
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
/* public GetAddressTask(Context context) {
super();
mContext = context;
}*/
/* *//**//*
* When the task finishes, onPostExecute() displays the address.
*//**//**/
#Override
protected void onPostExecute(String address) {
// Display the current address in the UI
Toast.makeText(context.getApplicationContext(),
"address---" + address,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Location... params) {
String Address = null;
String Location = null;
Geocoder geocoder;
List<android.location.Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2);
Location = addresses.get(0).getAddressLine(2);
System.out.println("Location----" + Location);
//This "Location" value i have to send to another activity
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the text
return Address;
/* } else {
return "No address found";
}*/
}
}// AsyncTask class
}

Use this in your code as appropriate:
In your First class:
Intent intent = new Intent(this, another_activity.class);
intent.putExtra("Location", Location.toString);
startService(intent)
In your Second class:
String Location = getActivity().getIntent.getStringExtra("Location")
Now you have passed string from one class to another. Use the Location variable where you need it.

Related

Get latitude and longitude periodically using alarm manager

I want making an app, get latitude and longitude every 5 minute. I have class to get it. But i can't get the latitude and longitude using alarm manager from receiver class alarm manager .
i have some error
Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
this is my class receiver
public class AlarmReceiver extends BroadcastReceiver {
public static final String TYPE_REPEATING = "RepeatingAlarm";
private final int NOTIF_ID_REPEATING_SEND_DATA = 101;
public static final String EXTRA_TYPE = "type";
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
String type = intent.getStringExtra(EXTRA_TYPE);
String latitude = intent.getStringExtra("LATITUDE");
String longitude = intent.getStringExtra("LONGITUDE");
int notifId = 0;
if (type.equalsIgnoreCase(TYPE_REPEATING)) {
notifId = NOTIF_ID_REPEATING_SEND_DATA;
getLokasiTerkini(mContext);
//sendDataToServer(latitude,longitude);
}
}
private void getLokasiTerkini(Context context) {
GPSTracker gpsTracker = new GPSTracker(context);
gpsTracker.getLocation();
String latitude = String.valueOf(gpsTracker.getLatitude());
String longitude = String.valueOf(gpsTracker.getLongitude());
Log.d("GET_LAT_LONG", "getLokasiTerkini: " + latitude + " " + longitude);
}
private void sendDataToServer(final String latitude, final String longitude) {
String url = "http://192.168.57.121/GetLatLongAndroid/api/addLatLong.php";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("latitude", latitude);
requestParams.put("longitude", longitude);
client.post(url, requestParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
int value = response.getInt("value");
if (value == 1) {
String message = response.getString("message");
Log.d("PESAN", "onSuccess: " + message);
} else {
String message = response.getString("message");
Log.d("PESAN", "onSuccess: " + message);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void setRepeatSendData(Context context, String type, String latitude, String longitude) {
mContext = context;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra(EXTRA_TYPE, type);
intent.putExtra("LATITUDE", latitude);
intent.putExtra("LONGITUDE", longitude);
int requestCode = NOTIF_ID_REPEATING_SEND_DATA;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
1 * 60 * 1000,
pendingIntent);
Toast.makeText(context, "Send Repeat Data Activated", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
int requestcode = NOTIF_ID_REPEATING_SEND_DATA;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestcode, intent, 0);
alarmManager.cancel(pendingIntent);
Toast.makeText(context, "Repeating Alarm Dibatalkan", Toast.LENGTH_SHORT).show();
}
}
This is my GPSTracker class
public class GPSTracker extends Service implements LocationListener {
// Get Class Name
private static String TAG = GPSTracker.class.getName();
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS Tracking is enabled
boolean isGPSTrackingEnabled = false;
Location location;
double latitude;
double longitude;
// How many Geocoder should return our GPSTracker
int geocoderMaxResults = 1;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
public static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
// Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
private String provider_info;
public GPSTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use GPS Service");
/*
* This provider determines location using
* satellites. Depending on conditions, this provider may take a while to return
* a location fix.
*/
provider_info = LocationManager.GPS_PROVIDER;
} else if (isNetworkEnabled) {
this.isGPSTrackingEnabled = true;
Log.d(TAG, "Application use Network State to get GPS coordinates");
/*
* This provider determines location based on
* availability of cell tower and WiFi access points. Results are retrieved
* by means of a network lookup.
*/
provider_info = LocationManager.NETWORK_PROVIDER;
}
if (!provider_info.isEmpty()) {
if (ActivityCompat.checkSelfPermission((Activity)mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mContext, new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION
}, 10);
}
locationManager.requestLocationUpdates(provider_info, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider_info);
updateGPSCoordinates();
}
}
} catch (Exception e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to LocationManager", e);
}
}
/**
* Update GPSTracker latitude and longitude
*/
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* GPSTracker latitude getter and setter
* #return latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
/**
* GPSTracker longitude getter and setter
* #return
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
/**
* GPSTracker isGPSTrackingEnabled getter.
* Check GPS/wifi is enabled
*/
public boolean getIsGPSTrackingEnabled() {
return this.isGPSTrackingEnabled;
}
/**
* Stop using GPS listener
* Calling this method will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.action_refresh, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* #return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
/**
* Geocoder.getFromLocation - Returns an array of Addresses
* that are known to describe the area immediately surrounding the given latitude and longitude.
*/
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);
return addresses;
} catch (IOException e) {
//e.printStackTrace();
Log.e(TAG, "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* #return null or addressLine
*/
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
/**
* Try to get Locality
* #return null or locality
*/
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else {
return null;
}
}
/**
* Try to get Postal Code
* #return null or postalCode
*/
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
/**
* Try to get CountryName
* #return null or postalCode
*/
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
public String getFeaturName(Context context){
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String featureName = address.getFeatureName();
return featureName;
}else {
return null;
}
}
public String getPremises(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String premises = address.getPremises();
return premises;
}else {
return null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
I want my class GPSTracker to access from receiver class.
Not possible to start LocationManager in BroadcastReceiver(You have used GPSTracker class here). So let use service on BroadcastReceiver and in that service you can use GPSTracker class.
write this in onReceive method
Intent serviceIntent = new Intent(context,YourService.class);
context.startService(serviceIntent); //start service for get location

how do I update the latitude and longitude to the textview in android main activity having dependency injection with dagger 2

I am beginner in android. I am now learning dagger 2 dependency injection. I am coding an app which update the latitude and longitude to the textview screen. I don't know, how i would I update the location coordinates to the textview screen as i did the coding of onLocationChanged in the module class and I am injecting the class to the main activity.
I did the coding of getting the location update in LocationManager class.
I can show the updated coordinates using toast, but not able to change textview, is there any way to do this ?
The code in the main activity
public class MainActivity extends AppCompatActivity {
#Inject
LocationManager locationManager;
#InjectView(R.id.textView2)
TextView addressLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
MyApplication.inject(this);
locationManager.GetLocation();
}
}
I like to update the addressLocation textview with the coordinates that i am getting from LocationListener.
package com.test.xyz.daggersample1.service.impl;
public class LocationManager {
Geocoder geocoder;
List<Address> addresses;
private double lattitude = 0;
private double longitude = 0;
private Context context;
public LocationManager(Context context) {
this.context = context;
}
public String GetLocation() {
final String[] address = new String[1];
android.location.LocationManager locationManager = (android.location.LocationManager) context.getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return "";
}
geocoder = new Geocoder(context, Locale.getDefault());
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
lattitude = location.getLatitude();
// dialog.dismiss();
Toast.makeText(context, "Got the Longitude as " + longitude + " Lattitude as " + lattitude, Toast.LENGTH_SHORT).show();
**I like to pass these location values to the textview in the main activity**
try {
addresses = geocoder.getFromLocation(lattitude, longitude, 1);
address[0] = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(context, "Got the Longitude as " + longitude + " Lattitude as " + lattitude, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(i);
}
};
locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 2000, 10, listener);
return address[0];
}
}
My project folder

How to get Current Location(Street,City, etc,..) using gps in Android

I want to create a app to Track the Users who installed my App, So i have a following code for tracking, This code working good but it will return only CITY NAME. But i need full details like street name, city, like wise .
public class GetCurrentLocation extends Activity
implements OnClickListener {
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to" +
" see the changes in coordinates." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#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
}
}
}
Try this :
public void setCurrentLocation() {
if (UtilityMethods.isGPSEnabled(mContext)) {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
// return;
} else {
getCurrentAddress();
}
} else {
alertbox("Gps Status", "Your Device's GPS is Disable", mContext);
}
}
Using LocationManager
public void getCurrentAddress() {
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
try {
if (Build.VERSION.SDK_INT >= 23 && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (Exception ex) {
Log.i("msg", "fail to request location update, ignore", ex);
}
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String locality = addresses.get(0).getLocality();
String subLocality = addresses.get(0).getSubLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
if (subLocality != null) {
currentLocation = locality + "," + subLocality;
} else {
currentLocation = locality;
}
current_locality = locality;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(HomeActivity.this, Constants.ToastConstatnts.ERROR_FETCHING_LOCATION, Toast.LENGTH_SHORT).show();
}
}
}
Use fused Location Provider to get current device latitude and longitude.
With the help of latitude and longitude, you can get city name and address.
To get full street name, use getMaxAddressLineIndex().
In onLocationChanged, check whether you are getting current location or not.
Edit:
String strAdd = "";
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(TabClubActivity.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (!addresses.isEmpty()) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append(" ");
}
strAdd = strReturnedAddress.toString();
textview.setText(strAdd);
Log.e("MyCurrentLoctionAddress", "" + strReturnedAddress.toString());
cityName=addresses.get(0).getLocality();
} else {
// Log.e("MyCurrentLoctionAddress", "No Address returned!");
}
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
I tried the Geocoder however the results are unreliable. So better go for the nearbysearch googleapi for the result. It provides the city name directly. Here's the version of my implementation.
interface Api{
String BASE_URL = "https://maps.googleapis.com";
#GET("/maps/api/place/nearbysearch/json")
Call<List<ResultDO>> getPlaceDetailByLatLong(#Query("location") String type,#Query("radius") String radius,#Query("key")String key);
}
And in the main activity or fragment.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
API service = retrofit.create(API.class);
service.getCityResults(types, input, location, radius, key).enqueue(new Callback<List<ResultDO>>() {
#Override
public void onResponse(Call<List<ResultDO>> call, Response<List<ResultDO>> response) {
tvCity.setText(response.body().get(0).getVicinity());// first object gives me the city name
}
#Override
public void onFailure(Call<List<ResultDO>> call, Throwable t) {
}
});
You can get address (street name, city, country, etc) by converting Geographic Location (e.g Latitude, longitude) to address. This process called Reverse Geocoding this doc.
You can use FusedLocationProviderApi(), but it has been deprecated (here). The alternative, You can use FusedLocationProviderClient() to get LastKnownLocation, from LastKnownLocation object (contain latitude and longitude), so we can use to get address like street name, city, country, etc using Geocoder. The sample doc do synchronously. But here i am doing Asynchronously using AsyncTask. Hope this Help.
To get Current Location:
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.tasks.OnCompleteListener;
public class MainActivity extends AppCompatActivity{
//before public class MainActivity extends AppCompatActivity implements LocationListener,...,...
private static final String TAG = "MainActivity";
public static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
private FusedLocationProviderClient mFusedLocationClient;
private Location mGetedLocation;
private double currentLat, currentLng;
private void getLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
return;
}
mFusedLocationClient.getLastLocation()
.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mGetedLocation = task.getResult();
//currentLat = mGetedLocation.getLatitude();
//currentLng = mGetedLocation.getLongitude();
//start reverse geocoding
//little different with the doc
(new GetAddressTask(this)).execute(mGetedLocation);
}else{
Log.e(TAG, "no location detected");
Log.w(TAG, "getLastLocation:exception", task.getException());
}
}
});
}
To Get Address from LastKnownLocation
//sorry, I forgot where I got this asyncTask code. So I did not mention the source.
//If anyone feels that making this code please comment.
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
GetAddressTask(Context context) {
super();
mContext = context;
}
#Override
protected String doInBackground(Location... params) {
Geocoder geocoder =
new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments " +
Double.toString(loc.getLatitude()) +
" , " +
Double.toString(loc.getLongitude()) +
" passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
/*
address.getLocality(),
address.getCountryName());
*/
return address.getLocality();
} else {
return "No address found";
}
}
#Override
protected void onPostExecute(String address) {
if (address != null)
mtextView.setText(address);//=============================> GOT THIS
}
}
In the Activity Class makes a customized method :
private void getTheUserPermission() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationGetter locationGetter = new LocationGetter(FreshMenuSearchActivity.this, REQUEST_LOCATION, locationManager);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationGetter.OnGPS();
} else {
locationGetter.getLocation();
}
}
Make a UserDefined Class name LocationGetter:-
public class LocationGetter {
private int REQUEST_LOCATION;
private FreshMenuSearchActivity mContext;
private LocationManager locationManager;
private Geocoder geocoder;
public LocationGetter(FreshMenuSearchActivity mContext, int requestLocation, LocationManager locationManager) {
this.mContext = mContext;
this.locationManager = locationManager;
this.REQUEST_LOCATION = requestLocation;
}
public void getLocation() {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mContext, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location LocationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location LocationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location LocationPassive = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (LocationGps != null) {
double lat = LocationGps.getLatitude();
double longi = LocationGps.getLongitude();
getTheAddress(lat, longi);
} else if (LocationNetwork != null) {
double lat = LocationNetwork.getLatitude();
double longi = LocationNetwork.getLongitude();
getTheAddress(lat, longi);
} else if (LocationPassive != null) {
double lat = LocationPassive.getLatitude();
double longi = LocationPassive.getLongitude();
getTheAddress(lat, longi);
} else {
Toast.makeText(mContext, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
}
}
private void getTheAddress(double latitude, double longitude) {
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
Log.d("neel", address);
} catch (IOException e) {
e.printStackTrace();
}
}
public void OnGPS() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mContext.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}

Android geocoding api can't return addressess

I'm having some trouble geocoding locations, i guess i've implemented everything. I've registered a google api, i've recieved a working google Api key, i also turned on google maps and geocoding services, but i can't get any locations associated with some hardcoded longitudes and latitudes.
Here's the code:
My AppLocationService
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
My LocationAddress class
public class LocationAddress {
private static final String TAG = "LocationAddress";
public static void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 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 (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude +
"\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
Somewhere deep in my mainActivity:
appLocationService = new AppLocationService(
ServerInterface.this);
Location location = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
double latitude = 47.162494;
double longitude = 19.503304;
LocationAddress locationAddress = new LocationAddress();
LocationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeocoderHandler());
}
Thanks,
I think you can take look at this. I tried and it worked.
Hope it hopes.

Trouble calling and getting location in oncreate method from location listener android

i need your help regarding the location update in android. Following is my code for getting location update and it is working fine. But it returns invalid message body when i get the stored variable with location in oncreate method of main class. After thorough research it seems that the variable i called in oncreate method is empty. Can you please tell me how to get the address as it appears in onlocationChanged Method. Thank you!
Calling class with oncreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
String address1= listener.getAddress();
{
sendSms(phone, message, false);
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
location class:
class Mylocation implements LocationListener{
double lat, lon;
static final String address="";
public void onLocationChanged(Location location)
{
//...
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address); //working here
}
public String getAddress(){ //not returning the address
return address;
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Make sure your variables are initialized properly. I don't see evidence of this in the question so I am just checking.
// Instantiation
Mylocation listener;
String phone;
String message;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
listener = new Mylocation(this);
phone = "";
message = "";
// These two lines aren't really necessary,
// this should be in your MyLocation class
//locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
// Add this line, we are going to initialize this class
// and make sure that address gets set
listener = new Mylocation();
String address1 = listener.getAddress();
try {
// If neither phone nor message is empty lets sendSms()
if (!phone.isEmpty() || !message.isEmpty()) {
sendSms(phone, message, false);
}
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
Change the String address to private and in the getter try return this.address;
class Mylocation implements LocationListener {
double lat, lon;
// Let's make this private so it can't be accessed directly,
// since you have the setter and getter.
private String address = "";
// Make sure you are overriding this method
#Override
public void onLocationChanged(Location location) {
/** ... */
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address);
}
public String getAddress(){
return (address.isEmpty()) ? "Address not set" : this.address;
}
public String GetAddressDetail(Double lat2, Double lon2) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Edit
I made changes to your code in my answer above, check the comments. I am also going to suggest additional methods for your MyLocation class:
class Mylocation implements LocationListener {
protected LocationManager locationManager;
private Context activityContext;
// The initializing method, this fires off first
// when a new instance of the class is created
public MyLocation(Context context) {
this.activityContext = context;
locationManager = (LocationManager) activityContext.getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);) {
locationManager.requestLocationUpdates(
NETWORK_PROVIDER,
MIN_TIME,
MIN_DISTANCE,
this
);
}
getLocation();
}
private double lat;
private double lon;
public double getLat() {
return this.lat;
}
public double getLng() {
return this.lng;
}
public void getLocation() {
if (location == null) {
locationManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);
if (location != null) {
// Set the coordinate variables
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("Network", "Lat: " + latitude + " / Lng: " + longitude);
}
}
}
}
}
You are calling getAdress directly after you set the locationmanager to probe for a location. The onLocationChanged method probably hasn't been called yet when you call getAddress this way. I would recommend changing it to something like below to make sure it has been called:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//...
long lat = location.getLatitude();
long lon = location.getLongitude();
String address = GetAddressDetail(lat, lon);
//Do whatever you want to do with the address here, maybe add them to the message or something like that.
sendSms(phone, message, false);
}
});
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}

Categories

Resources