I am working on this android wearable app for my own use and am stuck on how to pass a variable from within a if statement within a method to another method..
#Override
protected void onResume() {
super.onResume();
String myYards = "";
Bundle extras = getIntent().getExtras();
curhole = extras.getInt("hole");
if(curhole == 1){
myYards = "325";
double lat2 = 39.657479;
double lon2 = -121.778788;
}
if(curhole == 2){
myYards = "191";
double lat2 = 39.255478;
double lon2 = -121.125547;
}
TextView holeyard = (TextView) findViewById(R.id.holeYard);
holeyard.setText(String.valueOf(myYards + " yards"));
if(googleApiClient.isConnected()){
requestLocationUpdates();
}
}
#Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
Location loc1 = new Location("");
loc1.setLatitude(myLatitude);
loc1.setLongitude(myLongitude);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
int myDist = (int) (distanceInMeters * 1.0936);
TextView latView = (TextView) findViewById(R.id.yardage);
latView.setText(String.valueOf(myDist));
}
I would like to change the gps coordinates based on the whole number within the if statements in the onStart() method and pass them to the onLocationChanged() method, is this possible? Or am I just going about this wrong as I am new to android..
Thanks!
Just put these variables in your class, then all methods from class have access to them.
for example in class:
double x;
in statematent:
x= ...
Related
So I am using Firebase realtime database where the Nodes go a bit like this.
Company-> Users-> Registered Tutors ->All the data like longitude, latitude, name, dob, gender etc...
The idea behind it is, that when the user searches for the registered tutors, the latitude and longitude values of all registered tutors are retrieved, the latitude and longitude values of current user are also retrieved, and only the distance between them is shown in the search query.
I am using a FirebaseRecyclerAdapter. Sorry I am terrible with words, maybe the code and a few pictures would help.
This is my Activity (section of it)
private FirebaseAuth mAuth;
private DatabaseReference allUsersDatabaseRef, currentUserRefLong, currentUserRef;
allUsersDatabaseRef = FirebaseDatabase.getInstance().getReference().child("oxtuition").child("Users").child("Registered Tutors");
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
currentUserRef = FirebaseDatabase.getInstance().getReference().child("oxtuition").child("Users").child(currentUserID);
SearchResultList = (RecyclerView) findViewById(R.id.search_result_list);
SearchResultList.setHasFixedSize(true);
SearchResultList.setLayoutManager(new LinearLayoutManager(this));
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String searchBoxInput = SearchInputText.getText().toString();
SearchPeopleAndFriends(searchBoxInput);
}
});
}
private void SearchPeopleAndFriends(String searchBoxInput) {
Toast.makeText(this, "Searching....", Toast.LENGTH_LONG).show();
Query searchPeopleAndFriendsQuery = allUsersDatabaseRef.orderByChild("fullname").startAt(searchBoxInput).endAt(searchBoxInput + "\uf8ff");
FirebaseRecyclerAdapter<FindFriends, FindFriendsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<FindFriends, FindFriendsViewHolder>(FindFriends.class,
R.layout.all_tutors_display_layout,
FindFriendsViewHolder.class,
searchPeopleAndFriendsQuery) {
#Override
protected void populateViewHolder(FindFriendsViewHolder findFriendsViewHolder, FindFriends model, int i) {
findFriendsViewHolder.setLocation(model.getLocation());
}
};
SearchResultList.setAdapter(firebaseRecyclerAdapter);
}
public static class FindFriendsViewHolder extends RecyclerView.ViewHolder {
View mView;
public FindFriendsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setLocation(String location) {
TextView mylocation = (TextView) mView.findViewById(R.id.all_users_profile_how_far);
mylocation.setText(location);
}
}
}
Now it's the problem page, the FindFriends.class where the constructor and the setters and getters are.
public class FindFriends
{
public double longitude;
public double latitude, location;
public FindFriends(){
}
public FindFriends(String fullname, String profilimage, String subjects, String addresspostcode, String shortdescription, double longitude, double latitude) {
this.longitude = Double.parseDouble(String.valueOf(longitude));
this.latitude = Double.parseDouble(String.valueOf(latitude));
}
public double getLongitude() {
return longitude; //Longitude Getter
}
public void setLongitude(double longitude) {
this.longitude = longitude; //Longitude Setter
}
public void setLatitude(double latitude) {
this.latitude = latitude; //Latitude Setter
}
public double getLatitude() {
return latitude; //Latitude Getter
}
public String getLocation() {// Location getter doesn't exist in Firebase, it's calculated based upon the latitude and the longitude
final double lon1 = this.longitude;
final double lat1 = this.latitude;
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String CurrentUserID = mAuth.getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("oxtuition").child("Users").child(CurrentUserID);
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lon2S = dataSnapshot.child("longitude").getValue().toString();
String lat2S = dataSnapshot.child("latitude").getValue().toString();
//This is the mathematics behind calculating the distance between two latitude //and longitude values
double lon2 = Double.valueOf(lon2S);
double lat2 = Double.valueOf(lat2S);
System.out.println("Print OK" + lon2 + lat2);
double thetaLong = (lon2 - lon1)*Math.PI/180;
double thetaLat = (lat2 - lat1)*Math.PI/180;
double lat1Rad = lat1*Math.PI/180;
double lat2Rad = lat2*Math.PI/180;
double a = Math.sin(thetaLat/2)*Math.sin(thetaLat/2) + Math.cos(lat1Rad)*Math.cos(lat2Rad)*Math.sin(thetaLong/2)*Math.sin(thetaLong/2);
double c = 2*Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double R = 6371;
double d = (R*c);
location = d; //the double location is the "DISTANCE" calculated //between two latitude and longitude points.
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed");
}
});
return Double.toString(location);
//This returns the location calculated (hopefully, I feel like the problem is here)
}
public void setLocation() {
//don't really think this is even necessary.
}
}
In the end I am returning a calculated location which is sent to the main activity. The problem is:
I am having problems reading the latitude and longitude values from the current user ID. I have tried using arbitary values by simply doing:
double lat1 = 1.234556;
double lon1 = 1.233467;
and i get the correct answer, but I can't do that when reading the current user ID location. Please help, I am really stuck! I get values of 0! That's it for all of them. I can give more information, don't really know what else to include in this thread really.
After this i am hoping I can arrange the results according to the distance. But that's a challenge for the future. I'll be happy if anyone has any inputs on that as well.
Thankyou in Advance!
I'm trying to calculate distance between two locations on Google map. I'm inputting latitude and longitude from EditText,
but the return value is zero meters. What goes wrong in the code, i.e., how to get the real distance?
Here is a picture of my app:
public class Ma`inActivity extends AppCompatActivity implements OnMapReadyCallback {
private TextView source;
private TextView destination;
private EditText sLatitude1;
private EditText sLongtiude1;
private EditText dLatitude2;
private EditText dLongtiude2;
private Button button;
private GoogleMap mMap;
boolean mapReady = false;
MarkerOptions elsedaway;
MarkerOptions Elrob3;
Location location;
static final CameraPosition elfayoum = CameraPosition.builder()
.target(new LatLng(29.309324, 30.842973))
.zoom(1)
.bearing(6)
.tilt(45)
.build();
double lati1;
double longi1;
double lati2;
double longi2;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find text that display distance
textView = (TextView) findViewById(R.id.distance);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// find edit text and text view
source = (TextView) findViewById(R.id.sourc);
destination = (TextView) findViewById(R.id.destination);
sLatitude1 = (EditText) findViewById(R.id.lat1);
sLongtiude1 = (EditText) findViewById(R.id.long1);
dLatitude2 = (EditText) findViewById(R.id.lat2);
dLongtiude2 = (EditText) findViewById(R.id.long2);
// find button
button = (Button) findViewById(R.id.getDistance);
// find string from edittext
String lat1 = sLatitude1.getText().toString();
// parse string to double
lati1 = ParseDouble(lat1);
String lon1 = sLongtiude1.getText().toString();
longi1 = ParseDouble(lon1);
String lat2 = dLatitude2.getText().toString();
lati2 = ParseDouble(lat2);
String lon2 = dLongtiude2.getText().toString();
longi2 = ParseDouble(lon2);
Log.i("**lat", lat2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double xy1 = distanceBetween(new LatLng(lati1, longi1), new LatLng(lati1, longi2));
String distanceis = fmt(xy1) + "meter";
textView.setText(distanceis);
}
});
}
// mehtod to parse double from string
double ParseDouble(String strNumber) {
if (strNumber != null && strNumber.length() > 0) {
try {
return Double.parseDouble(strNumber);
} catch (Exception e) {
return -1; // or some value to mark this field is wrong. or make a function validates field first ...
}
} else return 0;
}
// get distance
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
double vw = SphericalUtil.computeDistanceBetween(point1, point2);
Log.i("distance isby utillib ", String.valueOf(vw));
return vw;
}
public String fmt(double d) {
return String.format("%s", d);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mapReady = true;
mMap = googleMap;
// if(elsedaway!=null){
// mMap.addMarker(elsedaway);};
// mMap.addMarker(Elrob3);
mMap.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(lati1, longi1))
.add(new LatLng(lati2, lati2))
mMap.addCircle(new CircleOptions()
.center(new LatLng(29.291540, 30.601884))
.radius(500044)
.strokeColor(Color.GREEN)
.fillColor(Color.argb(54, 99, 255, 0)));
flyTo(elfayoum);
}
This link might help you to find the distance between 2 lat long points.
Here is java implementation of haversine formula.
Hope this may help
Move this punch of code into your onCLick, and Correct your values, your code should be like :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String lat1 = sLatitude1.getText().toString();
// parse string to double
lati1 = ParseDouble(lat1);
String lon1 = sLongtiude1.getText().toString();
longi1 = ParseDouble(lon1);
String lat2 = dLatitude2.getText().toString();
lati2 = ParseDouble(lat2);
String lon2 = dLongtiude2.getText().toString();
longi2 = ParseDouble(lon2);
double xy1 = distanceBetween(new LatLng(lati1, longi1), new LatLng(lati2, longi2));
String distanceis = fmt(xy1) + "meter";
textView.setText(distanceis);
}
});
For starters, there is a mistake here :
double xy1 = distanceBetween(new LatLng(lati1, longi1), new LatLng(lati1, longi2));
You should be using lati2 instead of lati1 in your second argument.
And also, move the getText() inside the onClick(...) block.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// find string from edittext
String lat1 = sLatitude1.getText().toString();
// parse string to double
lati1 = ParseDouble(lat1);
String lon1 = sLongtiude1.getText().toString();
longi1 = ParseDouble(lon1);
String lat2 = dLatitude2.getText().toString();
lati2 = ParseDouble(lat2);
String lon2 = dLongtiude2.getText().toString();
longi2 = ParseDouble(lon2);
...
}
});
I am trying to display a double from this class in another class..
So here is my code:
public class Calculator extends AppCompatActivity {
Button next;
TextView pPrice;
TextView renovations;
TextView misc2;
TextView util;
TextView rep;
TextView mortage;
TextView misc1;
TextView rent;
public double getStartingCostsResult() {
return startingCostsResult;
}
double startingCostsResult;
double monthlyMinus;
double monthlyPlus;
double monthlyROI;
double yearlyROI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
// Setting these textviews to those in the xml.
pPrice = (TextView) findViewById(R.id.pPrice);
renovations = (TextView) findViewById(R.id.renovations);
misc2 = (TextView) findViewById(R.id.misc2);
util = (TextView) findViewById(R.id.util);
rep = (TextView) findViewById(R.id.rep);
mortage = (TextView) findViewById(R.id.mortage);
misc1 = (TextView) findViewById(R.id.misc);
rent = (TextView) findViewById(R.id.rent);
next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent expense = new Intent(getApplicationContext(), Results.class);
if ((pPrice.getText().length() > 0) && (renovations.getText().length() > 0) && (misc2.getText().length() > 0)) {
double price = Double.parseDouble(pPrice.getText().toString());
// double costs = Double.parseDouble(cCosts.getText().toString());
double reno = Double.parseDouble(renovations.getText().toString());
double misc = Double.parseDouble(misc2.getText().toString());
startingCostsResult = price + reno + misc;
if((util.getText().length()>0) && (rep.getText().length()>0) && (mortage.getText().length()>0) && (misc1.getText().length()>0)){
double utilities = Double.parseDouble(util.getText().toString());
double repairs = Double.parseDouble(rep.getText().toString());
double mort = Double.parseDouble(mortage.getText().toString());
double miscsell = Double.parseDouble(misc1.getText().toString());
monthlyMinus = utilities + repairs + mort + miscsell;
if (rent.getText().length()>0){
double monthlyRent = Double.parseDouble(rent.getText().toString());
monthlyPlus = monthlyRent;
monthlyROI = monthlyPlus - monthlyMinus;
yearlyROI = monthlyROI *12;
startActivity(expense);
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Calculator.this, "Please enter '0' in all boxes that don't apply.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
So I am trying to display the yearlyROI double in another class.
I have tried this:
Calculator calc = new Calculator();
otherClass.setText((int) calc.yearlyROI);
But my app crashes when I click next.
you should put an extra in the expense intent like this.
expense.putExtra("yearlyRoi",yearlyRoi);
then in the nexet activity you can get it like this.
Intent recievedIntent = this.getIntent();
double yearlyRoi = recievedIntent.getDoubleExtra("yearlyRoi", defaultValue);
default value can be 0.0 or anything you want.
as for the crash i think its another problem,you need to give us error log of your app.
If you want to access variables from a different Activity you need to add them to your intent.
In your case:
expense.putExtra("yearlyROI", yearlyROI);
startActivity(expense);
Then in your new Activity:
double yearlyROI = getIntent().getDoubleExtra("yearlyROI");
Hope it helps!
I'm trying to use MyLocation class from here. In code below I need to access variable currentLat and currentLon anywhere inside the class instantiating MyLocation. I don't know how to access value of currentLat and currentLon
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(Location location){
currentLat = location.getLatitude();
currentLon = location.getLongitude();
};
}
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
Suppose I want here
Double x =currentLoc;
how to I get that? Any help would be appreciated
instead of anonymous class use your own that extends/implments LocationResult class/interface and add getter like this
class MyLocationResult extends/implments LocationResult{
double currentLat;
double currentLon;
#Override
public void gotLocation(Location location){
currentLat = location.getLatitude();
currentLon = location.getLongitude();
};
public double getCurrentLat(){
return currentLat;
}
public double getCurrentLon (){
return currentLon ;
}
}
then you can write
MyLocationResult locationResult = new MyLocationResult();
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
and whenever you need currentLat or currentLon you can write
locationResult.getCurrentLat();
You can use static modifiers for your variables and define them globally..
public static double currentLat; // defined globally...
public static double currentLon;
LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(Location location){
currentLat =location.getLatitude(); // assuming getLatitude() returns double or int
currentLon = location.getLongitude();
};
}
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
Now you can access them anywhere
double x =currentLon;
double y =currentLat;
I need some help :) I am assign with a project to come out with the distance / speed and time. I have already come out with the Timer. However, the distance is giving me some problem. The distance does not changed at all from I travel from one place to another.
//GPS
private static Double EARTH_RADIUS = 6371.00; // Radius in Kilometers default
private static final String DEBUG_TAG = "GPS";
private String[] location;
private double[] coordinates;
private double[] gpsOrg;
private double[] gpsEnd;
private LocationManager lm;
private LocationListener locationListener;
private double totalDistanceTravel;
private boolean mPreviewRunning;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waterspill);
/*getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);*/
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
distanceCal=new LocationUtil(EARTH_RADIUS);
totalDistanceTravel=0;
// ---Additional---
//mapView = (MapView) findViewById(R.id.mapview1);
//mc = mapView.getController();
// ----------------
txtTimer = (TextView) findViewById(R.id.Timer);
gpsOnOff = (TextView) findViewById(R.id.gpsOnOff);
disTrav = (TextView) findViewById(R.id.disTrav);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(startButtonClickListener);
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(stopButtonClickListener);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(testButtonClickListener);
startButton.setEnabled(false);
stopButton.setEnabled(false);
getLocation();
}
public void getLocation()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,locationListener);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);
}
private OnClickListener startButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsOrg=coordinates;
totalDistanceTravel=0;
Toast.makeText(getBaseContext(),
"Start Location locked : Lat: " + gpsOrg[0] +
" Lng: " + gpsOrg[1],
Toast.LENGTH_SHORT).show();
if (!isTimerStarted)
{
startTimer();
isTimerStarted = true;
}
stopButton.setEnabled(true);
}
};
private OnClickListener stopButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsEnd=coordinates;
//gpsEnd = new double[2];
//gpsEnd[0]=1.457899;
//gpsEnd[1]=103.828659;
Toast.makeText(getBaseContext(),
"End Location locked : Lat: " + gpsEnd[0] +
" Lng: " + gpsEnd[1],
Toast.LENGTH_SHORT).show();
double d = distFrom(gpsOrg[0],gpsOrg[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
}
};
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return new Float(dist).floatValue();
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
}
startButton.setEnabled(true);
}
private double[] getGPS() {
List<String> providers = lm.getProviders(true);
double[] gps = new double[2];
//Loop over the array backwards, and if you get an accurate location, then break out the loop
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
String s = providers.get(i);
Log.d("LocServ",String.format("provider (%d) is %s",i,s));
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
Log.d("LocServ",String.format("Lat %f, Long %f accuracy=%f",gps[0],gps[1],l.getAccuracy()));
gpsOnOff.setText("On");
}
}
return gps;
}
Is there anything wrong with my codes. Please advice and Thanks a lot for your help :)
Test your formula with this: The distance between {-73.995008, 40.752842}, and {-73.994905, 40.752798} should be 0.011532248670891638 km.