how to update a global variable in java from an anonymous class - java

I am trying to get the lat and lng of a users location and pass these as a double to another method. However, I don't know how to do this or is it is possible.
As soon as I exit the inner class the variable's become null again.
public class MainActivity extends AppCompatActivity {
Double lat;
Double lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void onSearch(View v){
String[] requiredPermissions = {
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
boolean ok = true;
for (int i = 0; i < requiredPermissions.length; i++) {
int result = ActivityCompat.checkSelfPermission(this, requiredPermissions[i]);
if (result != PackageManager.PERMISSION_GRANTED) {
ok = false;
}
}
if (!ok) {
ActivityCompat.requestPermissions(this, requiredPermissions, 1);
// that last parameter MUST be >0, or it fails silently
System.exit(0);
} else {
// doStuffThatNeedsPermissions();
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
System.out.println("location is : " + lat + lng);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});
//System.out.println("location is here is : " + lat + lng);
}
//System.out.println("location is dow here is : " + lat + lng);
}
}

I don't have the permission to leave a comment so that's why answered the question.
As far as I understood.Though there are so many ways.Here is a way how you can use this into your entire class.
private Double lat,lng;
...
#Override
public void onLocationChanged(Location location) {
YourClass.this.lat = location.getLatitude();
YourClass.this.lng = location.getLongitude();
System.out.println("location is : " + this.lat + this.lng);
}
...
System.out.println("location is here is : " + this.lat + this.lng);
I edited my answer. I made a silly mistake.Sorry for that.

Related

Location Class returning empty location

I'm newcomer in Android development and I wish someone could help me.
My problem is as follow:
gradle
dependencies {
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.android.gms:play-services-location:15.0.1'
}
MainActivity
[...]
local = (CheckBox) findViewById(R.id.local_checkbox);
local.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DEBUG_INFO","CLICKED");
GPSTracker g = new GPSTracker(MainActivity.this);
if (((CheckBox) v).isChecked()) {
Log.v("DEBUG_INFO","CHECKED");
CheckGpsStatus();
if (GpsStatus == true) {
isLocated = true;
Location l = g.getLocation();
if ((l != null) && (isLocated == true)) {
lat = g.getLocation().getLatitude();
lon = g.getLocation().getLongitude();
Log.v("DEBUG_INFO","DEBUG_INFO:
Latitude: "+ String.valueOf(lat)+ " Longitude: "+
String.valueOf(lon));
}
else if ((l != null) && (isLocated == false)) {
lat = 0.0;
lon = 0.0;
} else {
lat = 0.0;
lon = 0.0;
}
} else {
new AlertDialog.Builder(NovaDenunciaActivity.this, R.style.AlertDialogCustom)
.setTitle("GPS TEXT!")
.setCancelable(false)
.setMessage("PLEASE SET GPS TEXT.")
.setPositiveButton("CLOSE",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
local.toggle();
}
} else {
isLocated = false;
}
}
});
}//onCreate
public void CheckGpsStatus(){
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("CHECKBOX","MARCADO");
}
} //Code end's
GPSTracker.java
[...]
public class GPSTracker extends Activity implements LocationListener {
Context context;
/*variables*/
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public GPSTracker(Context c) {
context = c;
}
/*variables*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} //Oncreate end's?
public Location getLocation() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Permission Text!\nPlease allow
permissions text.", Toast.LENGTH_LONG).show();
return null;
}
//Get the location manager
locationManager = (LocationManager)
context.getSystemService(context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin 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.");
Log.v("DEBUG_INFO:", "Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
//longitudeField.setText("Location not available");
Log.v("DEBUG_INFO:", "Latitude: not available");
Log.v("DEBUG_INFO:", "Longitude: not available");
}
return location;
}
#Override
protected void onResume() {
super.onResume();
Log.v("DEBUG_INFO:", "REQUESTING LOCATION UPDATES");
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
Log.v("DEBUG_INFO:","STOP LOCATION UPDATES");
}
#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));
Log.v("DEBUG_INFO:","Latitude: "+String.valueOf(lat));
Log.v("DEBUG_INFO:","Longitude: "+String.valueOf(lng));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(context, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(context, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
But when I click on checkbox the logcat (verbose) shows me the following:
V/DEBUG_INFO:: Latitude: not available
V/DEBUG_INFO:: Longitude: not available
The program should get latitude and longitude, if it does not exist it should call the locationManager.requestLocationUpdates(provider, 0, 0, this);
But I do not know what I'm doing wrong. Can someone help me?

get Latitude and Longitude values from locationManager

I'm trying to use Lat & Lon values for a function I created, but I can't find a way how to get this values from the class "Locationer" to the MainActivity.
I have created a new method called getLat(), but I need a location variable in order to get the latitude value with this method.
I have no idea how to get this "location" and where it comes from in the class.
I've am testing it on my own device.
The Locationer class:
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
public class Locationer extends Activity implements LocationListener {
#Override
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
String myLocation = "Latitude = " + location.getLatitude() + " Longitude = " + location.getLongitude();
//I make a log to see the results
Log.e("MY CURRENT LOCATION", myLocation);
}
public double getLat(Location location)
{
return location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
the code in my MainAcitivity.java:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Locationer locationListener = new Locationer();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
lat = **NEED YOUR HELP TO GET THIS VALUE**
lon = **NEED YOUR HELP TO GET THIS VALUE**
queryBooks(lat, lon);
You will have no latitude or longitude directly after setting the LocationManager. The onLocationChanged() will be called when it find a location. See here.
You can do the queryBooks(lat, lon); in the onLocationChanged().
Or you can use getLastKnownLocation(LocationManager.GPS_PROVIDER); but it will be less accurate and can provide you an old location.
Here what you can do in you MainActivity :
private LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
private LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
queryBooks(location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
protected void onResume() {
super.onResume();
//every second
int minTime = 1000;
//minDistance between two update
int minDistance = 10;
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, mLocationListener);
};
#Override
protected void onPause() {
mLocationManager.removeUpdates(mLocationListener);
super.onPause();
}

Android requestLocationUpdates doesn't call never to onLocationChanged in some terminals

I'm working on an app that uses the network location, but i've recived some users feedback that says that they never pass this block of code, i'm assuming that the problem is that location changed is never called, but it only happens in a few diveces, and i cant force the failure in mine.
Is there any chance to solve it or control it? showing a toast saying that is unable to find location, will work for me...
I know that if the user reboot his phone, the location will work, but that it's not a solution for the users
I left the code right here...
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
Location net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
final LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
// SOME STUFF
myTask task = new myTask();
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
} else {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
I've tried with the next idea, i think it could work, at least to get a location and not keep the user waiting.
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
LocationListener locationListenerNetwork = null;
// Constructor
class MyThread implements Runnable {
LocationListener locationListenerNetwork;
public MyThread(LocationListener lln) {
locationListenerNetwork = lln;
}
public void run() {
}
}
final Handler myHandler = new Handler();
//Here's a runnable/handler combo
final Runnable MyRunnable = new MyThread(locationListenerNetwork)
{
#Override
public void run() {
if (locationListenerNetwork != null)
lm.removeUpdates(locationListenerNetwork);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
else
{
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
}
};
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
myHandler.removeCallbacks(MyRunnable);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
myHandler.postDelayed(MyRunnable, 10 * 1000);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0,locationListenerNetwork);
} else {
// MORE STUFF
opinions?

Using GPS to two location (Position 1 to 2) , OnLocation Changed

I am targeting of using Android 2.2 to find distance using GPS however there are some problem in regarding my on Location changed. Previously, I put my code at On click listener and it does not work well. I manage to get the distance only after pressing the start and stop button after a numerous times.
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(originalCoordinates!=null){
coordinates1 = getGPS();
gpsEnd=coordinates1;
double d = distFrom(originalCoordinates[0],originalCoordinates[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
txtViews.setText("" + coordinates1.length + " new counts!!!" + coordinates1[0] + "," + coordinates1[1] );
}
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
txtView.setText("" + coordinates.length + " counts!!!" );
//double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
//totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
gpsOrg=coordinates;
if(originalCoordinates == null){
originalCoordinates = gpsOrg;
coordinates1 = getGPS();
txtView.setText("" + originalCoordinates.length + " original counts!!! " + originalCoordinates[0] + "," + originalCoordinates[1] );
}
//txtView.setText("" + coordinates.length + " counts" );
}
startButton.setEnabled(true);
}
dear do it like this.
Switch on GPS of your device
Wait until it get connected to a satellite.
Make a flag like booelan detecting_position.
Set it true on start button.
OnLocationChange Listner, check if flag is true, then get the
points using location.getLat,and getLong... and save them.
Here you can do a trick, initialize start location variables with
null, and check if startPosition is null then on first iteration of
location listner set long and lat as start location, in further
location change iterations set long and lat to stop_location
variables.
Once you tap the stop button set flag to false.
Now you have both start and end position. Use the distance formula
to calculate distance.
first of all take activity and do like below
public class MainActivity extends Activity implements OnClickListener
{
Button btnStart = null;
Button btnStop = null;
Context context = null;
Button btnTouch = null;
float distance ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
context = this;
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
Intent i = new Intent(context, MyService.class);
if(v.getId() == R.id.btnStart)
{
startService(i);
}
else if(v.getId() == R.id.btnStop)
{
distance = MyService.final_distance;
stopService(i);
}
}
}
then take one service and put our logic for location change in this service.i have use service because service run in background continue and look for location change when location is update.
public class MyService extends Service implements LocationListener
{
public static float final_distance = 0.0f;
private float distance = 0.0f;
private double old_latitude = 0.0;
private double old_longitude = 0.0;
private double new_latitude = 0.0;
private double new_longitude = 0.0;
LocationManager locationManager = null;
float[] result = null;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
result = new float[3];
}
#Override
public void onStart(Intent intent, int startid)
{
}
#Override
public void onDestroy()
{
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
if(old_latitude == 0.0 && old_longitude == 0.0)
{
old_latitude = location.getLatitude();
old_longitude = location.getLongitude();
}
new_latitude = location.getLatitude();
new_longitude = location.getLongitude();
Location.distanceBetween(old_latitude, old_longitude, new_latitude, new_longitude, result);
distance = final_distance +result[0];//distance in meters between two locations
final_distance = distance;
old_latitude = new_latitude;
old_longitude = new_longitude;
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
and also add uses permission android.permission.ACCESS_FINE_LOCATION in android manifest.xml
Hope this may help you

User location cannot be found

I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#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) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}

Categories

Resources