kunle oladepo
kunle oladepo

Reputation: 9

Android TextBox

I want to return the value of latitude and longitude into my EditTexts, I ve been able to do it using a Toast but not achieved it through the EditText. Kindly help

       // EditText latEditText = (EditText)findViewById(R.id.lat);
//EditText lngEditText = (EditText)findViewById(R.id.lng);

protected void showCurrentLocation(){
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null){
        String message = String.format(
                                   "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                                   location.getLongitude(), location.getLatitude()
                           );
                           Toast.makeText(LayActivity.this, message,
                                   Toast.LENGTH_LONG).show();
        //latEditText.setText(nf.format(location.getLatitude()).toString());
        //lngEditText.setText(nf.format(location.getLongitude()).toString());
    }
}

private class MyLocationListener implements LocationListener{

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        String message = String.format(
                  "New Location \n Longitude: %1$s \n Latitude:  %2$s",
                  location.getLongitude(), location.getLatitude()
                  );
               Toast.makeText(LayActivity.this, message, Toast.LENGTH_LONG).show();


        //latEditText.setText((int) location.getLatitude());
        //lngEditText.setText((int) location.getLongitude());

    }

Upvotes: 0

Views: 389

Answers (1)

Sam
Sam

Reputation: 86958

As long as the latEditText and lngEditText variables have a class wide scope, you can simply have your Activity implement a LocationListener:

public class Example extends Activity implements LocationListener

And then this works:

public void onCreate(Bundle savedInstanceState) {
    ...
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if(location != null)
        displayLocation(location);
}

public void onLocationChanged(Location location) {
    if(location != null) 
        displayLocation(location);
}

public void displayLocation(Location location) {
        latEditText.setText(location.getLatitude() + "");
        lngEditText.setText(location.getLongitude() + "");
    }
}

As Requested

Soxxeh pointed out that your commented-out code was passing setText() an integer, doing this references a resource (like the unique id to a string in your strings.xml). You want to pass setText() the actual String like the method above or with setText(String.valueOf(location.getLatitude())).

Hope that helps.

Upvotes: 1

Related Questions