i have a problem with my code, in a fragment i have this code:
public class Logo extends Fragment implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
LocationManager lm;
Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mCurrentLocation;
private TextView Lat;
private TextView Long;
String provider;
public Logo() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Logo newInstance() {
Logo fragment = new Logo();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
View view = inflater.inflate(R.layout.fragment_main, container, false);
Lat = (TextView) view.findViewById(R.id.Latitude);
Long = (TextView) view.findViewById(R.id.Longitude);
TextView Morad = (TextView) view.findViewById(R.id.Morada);
Criteria c=new Criteria();
provider=lm.getBestProvider(c, false);
mLastLocation=lm.getLastKnownLocation(provider);
Lat.setText("A obter");
Long.setText(" dados");
Morad.setText("Aguarde...");
if(mLastLocation!=null)
{
Lat.setText(String.valueOf(mLastLocation.getLatitude()));
Long.setText(String.valueOf(mLastLocation.getLongitude()));
}
else
{
Lat.setText("No connection");
Long.setText(" wait");
}
return view;
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Lat.setText(String.valueOf(mLastLocation.getLatitude()));
Long.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
But never get the Lat and Longitude values, what i missed up.
I only want to return the Latitude and Longitude values and put in the 2 filds.
you need to decide if you are going to use the built in LocationManager or google play services Location APi because you are trying to use both and that will not work.
if you are trying to use the built in one then you never get a location because you dont have a last location and you never request location updates.
if you are trying to use the google play services location API well you need to do more work because you didnt really even implement it. I guess really in both cases you still have more work because you really didnt implement either correctly
Related
In my code, I am getting the user's location using FusedLocationProviderClient. In the callback, I am saving the latitude and longitude of the user on Firebase real time database. Everything works fine even when the user moves from one place to another, the only problem is, every time it saves the coordinates on Firebase, the activity refreshes, how do I stop this automatic refreshing?
I am posting only the onCreate method and the call back method, if more code is needed, I will provide it.
Everything is working fine in my code except the activity refreshes every time new coordinates are saved on Firebase?
Note: My code is in a Fragment
private static final String TAG = "DriverMapFragment";
int LOCATION_REQUEST_CODE = 10001;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
double latitude,longitude;
DatabaseReference databaseReference;
String schoolName, driverPhone, vehicleNumberPlate;
TextView newLat,newLng;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_driver_map, container, false);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
locationRequest = LocationRequest.create();
locationRequest.setInterval(4000);
locationRequest.setFastestInterval(2000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
databaseReference = FirebaseDatabase.getInstance().getReference();
Intent intent = getActivity().getIntent();
schoolName = intent.getStringExtra("SchoolName");
driverPhone = intent.getStringExtra("DriverPhone");
vehicleNumberPlate = intent.getStringExtra("VehicleNumberPlate");
newLat = view.findViewById(R.id.newLat);
newLng = view.findViewById(R.id.newLng);
return view;
}
LocationCallback locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null){
return;
}
for (Location location : locationResult.getLocations()){
Log.d(TAG,"onLocationResult: " + location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("Lat",String.valueOf(latitude));
Log.i("Lng",String.valueOf(longitude));
LocationHelper helper = new LocationHelper(
location.getLongitude(),
location.getLatitude()
);
FirebaseDatabase.getInstance().getReference().child("Schools")
.child(schoolName)
.child("drivers")
.child(vehicleNumberPlate)
.child("driverLocation")
.setValue(helper).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i("Success","Location Saved");
}
else{
Log.i("Failure","Location Not Saved");
}
}
});
}
}
};
Make sure you use addListenerForSingleValueEvent instead of addValueEventListener, otherwise when you update data to Firebase, addValueEventListener will be called again and run the Activity you called in.
Im having problems with my current code, i don't see what i'm doing wrong. i keep getting the error "no suitable method found for requestLocationUpdates(string,int,in,MapsActivity)
public class MapsActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback, View.OnClickListener, DirectionCallback, OnMapClickListener, GoogleApiClient.OnConnectionFailedListener {
private LocationManager locationManager;
private Button btnRequestDirection;
GPSTracker gps;
private GoogleMap googleMap;
private String serverKey = "xxx";
private LatLng camera = new LatLng(54.1111, -1.1111);
private LatLng origin = new LatLng(54.1111, -1.1111);
private LatLng destination = new LatLng(54.11, -1.11);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
gps = new GPSTracker(MapsActivity.this);
long i = 1000;
long x = 10;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,i,x, this);
if (gps.canGetLocation()) {
camera = new LatLng(gps.getLatitude(), gps.getLongitude());
origin = camera;
btnRequestDirection = (Button) findViewById(R.id.btn_request_direction);
btnRequestDirection.setOnClickListener(this);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
} else {
gps.showSettingsAlert();
}
}
Everything i do the event "onLocationChanged()" never triggers, =/
You need to have a locationListener to listen for a location changes. If you are using 'requestLocationUpdates', you must use 'import android.location.LocationListener'. The standard Android location stuffs is 'android.location'. The com.google.android.gms.location stuff is for use with the FusedLocationProviderApi which is part of Google play services.
This is more of a android design question. I am building an application that is going to consist of features such as P2P Connection, Location Receiving/Updates and a few others.
My applications current design is an activity consisting of two fragments in a viewpager and under a toolbar.
My first approach was to write different features all in separate classes (E.g Location receiver in its own class, a Google map generator in another) and then instantiate these objects where I needed them. I started to realize that that method wasn't working.
An idea I had was to implement everything I need in my fragments "onCreateView()" method but that just seems disorderly.
My question is where exactly do we implement certain features?
Here is an example of the fragment consisting of a map.
public class MapFragment extends Fragment implements OnMapReadyCallback{
SupportMapFragment mSupportMapFragment;
int radius = 20;
double mLatitude;
double mLongitude;
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
private GoogleMap maps;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mSupportMapFragment = SupportMapFragment.newInstance();
android.support.v4.app.FragmentManager sfm = getFragmentManager();
mSupportMapFragment.getMapAsync(this);
if(!mSupportMapFragment.isAdded())
sfm.beginTransaction().add(R.id.map_frag,mSupportMapFragment).commit();
else if(mSupportMapFragment.isAdded())
sfm.beginTransaction().hide(mSupportMapFragment).commit();
else
sfm.beginTransaction().show(mSupportMapFragment).commit();
LocationManager mLocationManager;
LocationListener mLocationListener;
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
/*
Updates to our map may need to be taken place here. Need to listen to other devices in the area.
*/
Log.e("Latitude: ", "" + location.getLatitude());
Log.e("Longitude: ", "" + location.getLongitude());
maps.clear(); //Clear the map of any existing markers
mLatitude = location.getLatitude();//Get coordinates stored into local variables
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude,mLongitude);//Create a "LatLng" object consisting of these coordinates
MarkerOptions mp1 = new MarkerOptions();//Instantiate a new "MarkerOptions" where we will be able to define a...
//...marker
mp1.position(new LatLng(location.getLatitude(),//Customizing marker...
location.getLongitude()));
mp1.title("You");
maps.addMarker(mp1);//Finally add the marker to the map
maps.moveCamera(CameraUpdateFactory.newLatLng(latLng));//Move camera to markers location using our "latLng" variable
maps.animateCamera(CameraUpdateFactory.zoomTo(20));// Zoom, (between 2.0 - 21.0) the higher, the more zoomed in
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,120000,radius,mLocationListener);
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onMapReady(GoogleMap map) {
maps = map;
}
}
In this fragment alone I have established location updates and a google map API. Everything seems to be working so far.
My only concern is the design.
Is cramming all these features (and more to come) in a single fragment considered bad practice?
I have a ListFragment and I want to get the my location. In my Manifest I have added this:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and my ListFragment´s code is here, but not works:
public class ListaLugaresFragment extends ListFragment implements LocationListener {
GoogleMap googleMap;
Location location;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v= inflater.inflate(R.layout.lista, container, false);
LocationManager lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
return v;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), location.getLatitude()+""+location.getLongitude(), Toast.LENGTH_LONG).show();
}
First you need to know about GPS, Network Provider, google MAP to know getting location. Below example is for beginner to know how to get location(lanlat value) from the GPS and Network Provider
Follow this link:
Getting location (latlong)
If you want to get a location name then u must know about SHA code and all.
Follow this Link:
Getting location from googlemap
I'm currently trying to include the google maps into my app. The main aim is to move the camera automatically to the current location of the device with a zoom after the map was loaded.
For this I need a location manager. In the below code I'm trying to implement one, but without success. I also tried to pass the context from a fragment class.
But still I'm getting this message from eclipse: The method getSystemService(String) is undefined for the type Navigation
Any ideas what I'm doing wrong?
public class Navigation extends SupportMapFragment {
private GoogleMap map;
private Context mContext;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.activity_navigation, null, false);
getContextFromConfig();
setUpMapIfNeeded();
return v;
}
private void getContextFromConfig()
{
ContextConfig config = new ContextConfig();
mContext = config.getContext();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
} else {
System.out.println("Google Maps is not available.");
}
if (map != null) {
setUpMap();
}
}
private void setUpMap() {
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("snippet"));
// Enable MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
//set map type
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(14));
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
}
}
getSystemService() is a method of Context, not of Fragment. You probably want to do this:
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
or this:
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);