Current Location with Geocoder not working for non activities - java

I am currently building an Android app and my main problem is that I have a class that retrieves the current latitude and longitude of my current location.
Whenever I make an activity out of it, it works fine. However, now that I;m trying to make it a class that will just retrieve the latitude and longitude and will set it to a setter, it doesn't work.
Namely, I am using FusedLocationProviderClient and Geocoder in order to retrieve those two elements.
The problem is that both of them won't take the current object as an argument (context, since it's a non activity class), whereas they work just fine with activities. In other words, this doesn't apply whenever I apply this for the context. Below is my class, with the problems that I am facing.
I would appreciate some help here thank you in advance.
public class CurrentLocationFinder {
FusedLocationProviderClient fusedLocationProviderClient;
double lagitudeValue, longitudeValue;
private final static int REQUEST_CODE = 100;
public CurrentLocationFinder() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);//*******doesn't accept 'this' in method
getLastLocation();
}
private void getLastLocation() { //doesn't accept 'this'
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault()); //doesn't accept 'this'
List<Address> addressList = null;
try {
addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
System.out.println("********************" + addressList.get(0).getLatitude());
setLagitude(addressList.get(0).getLatitude());
setLongitude(addressList.get(0).getLongitude());
System.out.println("=====================" + addressList.get(0).getLatitude());
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
//askPermission();
}
}
public double getLagitude() {
return this.lagitudeValue;
}
public double getLongitude() {
return this.longitudeValue;
}
public void setLagitude(double lagitude) {
this.lagitudeValue = lagitude;
}
public void setLongitude(double longitude) {
this.longitudeValue = longitude;
}
}

Related

How mapbox navigation draw(Polyline) user location changed coordinates on Map?

private static class LocationChangeListeningActivityLocationCallback
implements LocationEngineCallback<LocationEngineResult> {
private final WeakReference<MapMatchingActivity> activityWeakReference;
LocationChangeListeningActivityLocationCallback(MapMatchingActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
#Override
public void onSuccess(LocationEngineResult result) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Location location = result.getLastLocation();
Feature feature = Feature.fromGeometry(Point.fromLngLat(result.getLastLocation().getLongitude(),result.getLastLocation().getLatitude()));
if (location == null) {
return;
}
Log.e("Coords", String.valueOf(result.getLastLocation().getLatitude() +" " + result.getLastLocation().getLongitude()));
String[] latlong = (result.getLastLocation().getLatitude() +"," + result.getLastLocation().getLongitude()).split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);
latLngList.add(new LatLng(longitude,latitude));
// activity.drawMarker();
}
}
#Override
public void onFailure(#NonNull Exception exception) {
MapMatchingActivity activity = activityWeakReference.get();
if (activity != null) {
Toast.makeText(activity, exception.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The above code where I am getting user location coordinates, I got to know that MapBox updated SDK, and PolylineOptions is now Deprecated, I have drawn lines using LineOptions but still have No idea how to update based on user location Please check below code.
private void getDirection(List<LatLng> coordinates,LatLng latLng){
List<LatLng> latLngs = new ArrayList<>();
latLngs.add(new LatLng(21.23504447 ,72.81109308));
latLngs.add(new LatLng( 21.23471482921968, 72.81101793050766));
latLngs.add(new LatLng(21.23425981047001, 72.81080335378647));
LineOptions lineOptions = new LineOptions()
.withLatLngs(latLngs)
.withLineColor(ColorUtils.colorToRgbaString(Color.BLACK))
.withLineWidth(5.0f);
lineManager.create(lineOptions);
}

java.lang.NullPointerException Can't set text from class to activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I'm rather new to coding and my long term goal is to create an android weather app. I've created the main activity and a class, plus I'm using Weatherlib to make things a bit easier.
The main activity asks for permission and grabs the location using GPS. Those coords are sent to the getweather method which grabs the information using OpenWeatherMap. When the data is retrieved, in this case, cloud percentage, what I want it to do is pass that to the main activity to setText for the TextView clouds. My issue is that it's throwing a NullPointerException when I try to do that from onWeatherRetrieved.
public class MainActivity extends AppCompatActivity {
private double latitude;
private double longitude;
private FusedLocationProviderClient fusedLocationClient;
private String response;
private TextView clouds;
private Context context;
private Context x;
private WeatherOWM weatherOWM;
//Get location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clouds = findViewById(R.id.clouds);
x = this;
context = getApplicationContext();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
requestPermissions();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}
fusedLocationClient.getLastLocation().addOnSuccessListener (this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
System.out.println(latitude + " " + longitude);
WeatherOWM loc = new WeatherOWM(latitude, longitude, context);
loc.getWeather();
}
}
});
}
public void setClouds(Integer cloud) {
clouds.setText(cloud);
}
private void requestPermissions(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
public class WeatherOWM{
private double latitude;
private double longitude;
private Context ma;
WeatherConfig config = new WeatherConfig();
private Object WeatherConfig;
private Object hourForecast;
private Object MainActivity;
private MainActivity mainActivity;
public WeatherOWM(double latitude, double longitude, Context ma){
this.latitude = latitude;
this.longitude = longitude;
this.ma = ma;
}
public void getWeather() {
TextView clouds = new TextView(ma);
//Init client
WeatherClient client = null;
config.ApiKey = "REDACTED";
try {
client = (new WeatherClient.ClientBuilder()).attach(ma)
.httpClient(WeatherDefaultClient.class)
.provider(new OpenweathermapProviderType())
.config(config)
.build();
} catch (WeatherProviderInstantiationException e) {
e.printStackTrace();
}
client.getHourForecastWeather(new WeatherRequest(latitude, longitude), new WeatherClient.HourForecastWeatherEventListener() {
#Override
public void onWeatherRetrieved(WeatherHourForecast weatherHourForecast) {
List<HourForecast> hourList = weatherHourForecast.getHourForecast();
for (HourForecast hourForecast: hourList) {
Weather weather = hourForecast.weather;
long timestamp = hourForecast.timestamp;
mainActivity.setClouds(hourForecast.weather.clouds.getPerc());
System.out.println(hourForecast.weather.clouds.getPerc());
}
}
#Override
public void onWeatherError(WeatherLibException wle) {
System.out.println("ERROR");
}
#Override
public void onConnectionError(Throwable t) {
System.out.println("ERROR");
}
});
}
}
In the WeatherOWM class , you have created an instance of MainActivity as here :
private MainActivity mainActivity;
and in the method , you have written :
mainActivity.setClouds(hourForecast.weather.clouds.getPerc());
the problem is that the variable "mainActivity" has no value and is empty so you have to give value to it.
so in the WeatherOWM class , write this code :
mainActivity = new MainActivity();
please reply is solved your problem

Instantiating a class return null values

I'm making an app that needs to get the results in my MainActivity, when I call getData() I get the data from my instantiation, but when i try to calculate the position it returns null.
This is my Location.class
public class Location implements GoogleApiClient.OnConnectionFailedListener {
private List<Integer> mTypeList;
private ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
LatLng mLatLang;
private PlaceLikelihood pl;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
public Location(Context context) {
this.listItems = new ArrayList<>();
this.mTypeList = new ArrayList<>();
mContext = context;
buildGoogleApiClient();
connect();
getData();
}
public void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient
.Builder(mContext)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
public void connect() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
public void getData() {
if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_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;
}
final PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
.getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(#NonNull PlaceLikelihoodBuffer placeLikelihoods) {
pl = placeLikelihoods.get(0);
Log.e("singleplacetype", "onResult: "+pl.getPlace().getPlaceTypes());
Log.e("singleliketype2", "onResult: "+pl.getLikelihood());
Log.e("singleliketype3", "onResult: "+pl.getPlace().getName());
mTypeList = pl.getPlace().getPlaceTypes();
//Latitude and longitude
mLatLang = pl.getPlace().getLatLng();
String latlongshrink = mLatLang.toString();
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(latlongshrink);
while (m.find()) {
Log.e("Test", "" + m.group(1));
latlongshrink = m.group(1);
}
for (int i = 0; i < mTypeList.size(); i++) {
try {
nearestPlaces(latlongshrink, getPlaceTypeForValue(mTypeList.get(i)));
} catch (Exception e) {
e.printStackTrace();
}
try {
listItems.add(pl.getPlace().getName() + " " + pl.getLikelihood() + " " + mTypeList + " " + getPlaceTypeForValue(mTipoList.get(i)));
Log.e("singleList", "onResult: "+listItems );
} catch (Exception e) {
e.printStackTrace();
}
}
placeLikelihoods.release();
}
});
}
public Integer getTypes(int posicion) {
Log.e("listType", "getTypes: "+mTypeList);
int type;
if(mTypeList.size()>0){
type = mTypeList.get(posicion);
}else{
return null;
}
return type;
}
Now, that's my Location.class, I call that class in my MainActivity like this
Location loc = new Location(getApplicationContext());
I have another class that calculates some values with the first class, so after I instantiate the Location.class I can succefull see that getData() is executed as it returns to me some places.
json.class
private Integer getPosition(Location loc) {
return loc.getTypes(0);
}
so, now again into my MainActivity i'm trying to fetch te values from Location.class but from json.class, since getPosition does something else before it is beign executed
MainActivity.class
Json json = new Json(getApplicationContext());
Log.e("jsonClassData", "onCreate: "+json.getPosition(loc));
now, this line is returning null , but I dont know why since getData() have been created but getTypes have inside mTypeList that is returning 0 as size and returning null since mTypeList.size is 0
Also if in MainActivity.class I call this line it returns null too
Location loc = new Location(getApplicationContext());
loc.getType(0);
it seems getData() is not saving the values inside mTypeList
Why is this happening ?
thanks
Location loc = new Location(getApplicationContext());
You are not supposed to create an activity with the new operator.
You should use an intent for that.
And so do away with all those public member functions.
The problem was that getData() is an asynchronous operation that is waiting for the results. Now, if I don't wait for that data to be done, getTypes does not have any value on it. Now, thanks to Mike M. I just solved the problem using a simple interface.
I created an interface called PlaceSuccessListener
public interface PlaceSuccessListener {
void onPlaceFound(int placeFound);
}
called it at the last of my pendingResult
private PlaceSuccessListener mPlaceSuccessListener;
getData();
.....
placeLikelihoods.release();
mPlaceSuccessListener.onPlaceFound(200);
}
And then in my MainActivity I just waited for the result to be done in order to access my data. I implemented PlaceSuccessListener and attached the setInterface(this)
#Override
public void onPlaceFound(int placeFound) {
if(placeFound==200){
Log.e("jsonClassData", "onCreate: "+json.getPosition(loc));
}
}

requestLocationUpdates throws error

sorry, I know such questions happened here, but I cannot action them in my code, I am a beginner...
So, I am trying to get a GPS coordinates read from LocationManager and my code is throwing a "Can't create handler inside thread that has not called Looper.prepare()".
So my code works this way. I used a Timer and Timertask classes to create a scheduled task from which my coordinates are being read.
This is a timer class:
public class GeoLocationTimer extends Timer {
private List coords;
private Context context;
public GeoLocationTimer(Context context){
this.context = context;
this.coords = new ArrayList<Double>();
//Log.e("cont timer","content" + context);
}
public void addPosition(Double pos) {
this.coords.add(pos);
}
public void scheduleTasks(long interval) {
//Log.e("z schedule","cont"+context);
this.schedule(new GeoLocationTask(this, context), 0, interval);
}
public void cancelTasks() {
this.cancel();
}
public List getList(){
return coords;
}
This is task:
public class GeoLocationTask extends TimerTask{
private final GeoLocationTimer timerContext;
private final Context context;
private Pair<Double, Double> coordsSet;
public GeoLocationTask(GeoLocationTimer timerContext, Context context){
this.timerContext = timerContext;
this.context = context;
}
#Override
public void run() {
// TODO Auto-generated method stub
GeoActivity tracker = new GeoActivity(context);
coordsSet = tracker.getLocation();
Log.e("first","timertask");
if (coordsSet != null){
Log.e("first","a tu wartosc" + coordsSet.first);
Log.e("second","a tu wartosc" + coordsSet.second);
timerContext.addPosition(coordsSet.first);
timerContext.addPosition(coordsSet.second);
//context.addPosition(tracker.getLocationNow().get(1));
}
}
public boolean cancel() {
return false;
}
}
Here is context from which I am trying to run this task:
package com.example.gpstracking;
public class GeoActivity extends ContextWrapper {
Context context;
public GeoActivity(Context base) {
super(base);
this.context = base;
}
public Pair<Double, Double> getLocation(){
Tracking track = new Tracking(context);
return track.getLocation();
}
And tracking now:
public class Tracking extends Service implements LocationListener{
private final Context mContext;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// 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
private static final long MIN_TIME_BW_UPDATES = 1000 * 30 * 1; // 0.5 minute
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
protected LocationManager locationManager;
public Tracking(Context context) {
this.mContext = context;
}
public Pair<Double, Double> getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
Log.e("no provider","turn it on man!");
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
Log.e("Network", "Network");
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("latitude","latitude"+latitude);
Log.e("longitude","longitude"+longitude);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
return new Pair(latitude,longitude);
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
Log.e("GPS", "GPS");
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
return new Pair(latitude,longitude);
}
}
} catch (Exception e) {
Log.e("excepton:","exp" + e.getMessage());
e.printStackTrace();
e.getMessage();
}
return new Pair(0.0,0.0);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
So, sorry for being stupid. Could someone help me with this?
Cheers
A
I probably found the issue: I really should not call requestlocationupdates in here, as I am calling for updates in the timer class. Need to go and test it outside :)
Cheers!

Android Asynctask return value in onCreate of Activity

Here in for loop i want to call Async return value. i want to call that value in snippet after title.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_full_map);
Intent i = getIntent();
lat = i.getStringArrayListExtra("L");
longi = i.getStringArrayListExtra("Longitude");
len=lat.size();
for(;j<len;j++){
LatLng location = new LatLng(Double.valueOf(lat.get(j)).doubleValue(),
Double.valueOf(longi.get(j)).doubleValue()) ;
new ReverseGeocodingTask(getBaseContext()).execute(location);
googlemap.addMarker(new MarkerOptions()
.title(plat.get(j).toString())
.snippet(snippet)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.position(location)
);
}
}
Here Below is my AsyncTask code where i am returning the values. please some take a look and explain me my silly mistake....
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>
{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
#Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
} catch (IOException e) {
e.printStackTrace();
}
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
return addressText;
}
#Override
protected void onPostExecute(String addressResult) {
// Setting the title for the marker.
// This will be displayed on taping the marker
snippet = addressResult;
super.onPostExecute(snippet);
//Toast.makeText(Show_full_map.this,addressText,Toast.LENGTH_LONG).show();
}
}
I guess you want snippet immediately after calling execute. This is not how AsyncTask works. You can pass location in constructor of AsyncTask and access it from onPostExecute().
Just move the following code from your for loop to onPostExecute():
#Override
protected void onPostExecute(String snippet) {
super.onPostExecute(snippet);
googlemap.addMarker(new MarkerOptions()
.title(plat.get(j).toString())
.snippet(snippet)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.position(location)
);
}

Categories

Resources