Im trying to get realtime location with pointing on the Google Map. Currently i successfully get the latitude and longitude in realtime and it will update everytime to a getter, setter class called sosrecord.getLatitude() and sosrecord.getLongitude(). I want to point the google map based on the updated latitude and longitude. But everytime when i put the getter on the LatLng latLng = new LatLng(sosrecord.getLatitude(), sosrecord.getLongitude()); it will return me Null and eventually crash the app due to java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference It should point the current location when user click on a button. Sorry if the code sample below is messy, hope someone could help me with this issue. Thanks.
Main.java
public class MainActivity extends FragmentActivity{
private Handler mHandler = new Handler();
DatabaseReference reff;
SosRecords sosrecords;
boolean startclicked =true;
String selectedOfficer = "Police";
private static final String TAG = "MainActivity";
int LOCATION_REQUEST_CODE = 1001;
SupportMapFragment smf;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult <------This function will get the lat and long and set the value to sosrecordlocationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
double lat = location.getLatitude();
double lon = location.getLongitude();
sosrecords.setLatitude(lat);
sosrecords.setLongitude(lon);
}
}
};
private void showOptionDialog() {
String[] officers = {"Police", "Hospital", "Bomba"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose SOS types");
builder.setSingleChoiceItems(officers, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedOfficer = officers[which];
}
});
builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
sosrecords.setCallFor(selectedOfficer);{
onStart();
startclicked= false;
//GET ALL INFORMATION FROM FIRESTORE AND SEND TO REALTIME DATABASE
if(FirebaseAuth.getInstance().getCurrentUser()!= null){
DocumentReference df = FirebaseFirestore.getInstance().collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid());
df.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.getString("FullName")!= null){
String id = reff.push().getKey();
Log.d(TAG, "asdasd"+id);
SosRecords sosRecords = new SosRecords(documentSnapshot.getString("FullName"), (documentSnapshot.getString("PhoneNumber")), (documentSnapshot.getString("UserEmail") ),sosrecords.getLatitude(),sosrecords.getLongitude(),sosrecords.getCallFor() );
reff.child(id).setValue(sosRecords);
sosrecords.setRecordID(id);
btnStartSOS.setEnabled(false);
btnStopSOS.setEnabled(true);
Toast.makeText(MainActivity.this, "You're are now activating SOS request !", Toast.LENGTH_SHORT).show();
LatLonLoop.run();
smf.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(sosrecords.getLatitude(),sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Here");
googleMap.addMarker(markerOptions);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),Login.class));
finish();
}
});
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
checkSettingsAndStartLocationUpdates();
}else{
askLocationPermission();
}
}
dialog.dismiss();
}
});
My get/set class
package com.example.sossystem;
public class SosRecords {
String RecordID;
String FullName;
String PhoneNumber;
String EmailAddress;
Double Latitude;
Double Longitude;
String CallFor;
public SosRecords(){
}
public SosRecords(String fullName, String phoneNumber, String userEmail, Double latitude, Double longitude, String callFor) {
FullName = fullName;
PhoneNumber = phoneNumber;
EmailAddress = userEmail;
Latitude = latitude;
Longitude = longitude;
CallFor = callFor;
}
public String getRecordID() {
return RecordID;
}
public void setRecordID(String recordID) {
RecordID = recordID;
}
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
PhoneNumber = phoneNumber;
}
public String getEmailAddress() {
return EmailAddress;
}
public void setEmailAddress(String emailAddress) {
EmailAddress = emailAddress;
}
public Double getLatitude() {
return Latitude;
}
public void setLatitude(Double latitude) {
Latitude = latitude;
}
public Double getLongitude() {
return Longitude;
}
public void setLongitude(Double longitude) {
Longitude = longitude;
}
public String getCallFor() {
return CallFor;
}
public boolean setCallFor(String callFor) {
CallFor = callFor;
return false;
}
}
The thing is that when you open MainActiity that time onMapReady() called first automatically before LocationCallback. Eventually, it will return null latitude and Longitude.
However, your problem is that you haven't assigned your map fragment.
first of all, you need to assign in onLocationResult() below the for loop.
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(MapsActivity.this);
Secondly, remove smf.getMapAsync() from onMapReady().
Instead of,
smf.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(sosrecords.getLatitude()
,sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().
position(latLng).title("Here");
googleMap.addMarker(markerOptions);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});
Replace,
// declare googlemap as a globally
private GoogleMap mMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(sosrecords.getLatitude()
,sosrecords.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().
position(latLng).title("Here");
googleMap.addMarker(markerOptions);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
});
Related
I have a Firebase Realtime database, where I store Google Maps Marker data. It looks like this: Firebase Database
My application has the option to add your own marker to the database, my problem is that my application only reads the info from Studio 1 and T1, not from the random key added by .push(). when i add a marker via the app. Any ideas on how to get it to read the marker info that is under the random key? My code looks as follows:
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mProfileRef = firebaseDatabase.getReference("Studios");
ChildEventListener mChildEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Button addAStudio = (Button) findViewById(R.id.addAStudio);
addAStudio.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapsActivity.this, Rent.class);
startActivity(intent);
}
});
}
#Override
public void onMapReady(GoogleMap googleMap){
googleMap.setOnMarkerClickListener(this);
LatLng Copenhagen = new LatLng(55.67, 12.56);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Copenhagen, 18));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//get marker info from Firebase Database and add to map
addMarkersToMap(googleMap);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
}
#Override
public void onStop(){
if(mChildEventListener != null)
mProfileRef.removeEventListener(mChildEventListener);
super.onStop();
}
private void addMarkersToMap(final GoogleMap map){
mChildEventListener = mProfileRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FirebaseMarker marker = dataSnapshot.getValue(FirebaseMarker.class);
String StudioName = marker.getStudioName();
String StudioAdress = marker.getStudioAddress();
String StudioDescription = marker.getStudioDescription();
double latitude = marker.getLatitude();
double longitude = marker.getLongitude();
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(location)
.title(StudioName)
.snippet(StudioAdress)
.snippet(StudioDescription))
.showInfoWindow();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
And
public class FirebaseMarker {
public String studioName;
public String studioDescription;
public String studioAddress;
public double latitude;
public double longitude;
//required empty constructor
public FirebaseMarker() {
}
public FirebaseMarker(String studioName, String studioDescription, String studioAdress, double latitude, double longitude) {
this.studioName = studioName;
this.studioDescription = studioDescription;
this.studioAddress = studioAdress;
this.latitude = latitude;
this.longitude = longitude;
}
public String getStudioName() {
return studioName;
}
public void setStudioName(String studioName) {
this.studioName = studioName;
}
public String getStudioDescription() {
return studioDescription;
}
public void setStudioDescription(String studioDescription) {
this.studioDescription = studioDescription;
}
public String getStudioAddress() {
return studioAddress;
}
public void setStudioAddress(String studioAddress) {
this.studioAddress = studioAddress;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
}
and finally where add a new marker to the database:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rent);
saveStudio = findViewById(R.id.saveStudio);
studioNameTextField = findViewById(R.id.studioNameTextField);
studioInfoTextField = findViewById(R.id.studioInfoTextField);
studioAdressTextField = findViewById(R.id.studioAdressTextField);
mDatabase = FirebaseDatabase.getInstance();
mDataBaseRef = mDatabase.getReference("Studios");
saveStudio = findViewById(R.id.saveStudio);
saveStudio.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Map<String, FirebaseMarker> newStudioAdd = new HashMap<>();
newStudioAdd.put(studioNameTextField.getText().toString(),
new FirebaseMarker(
studioNameTextField.getText().toString(),
studioInfoTextField.getText().toString(),
studioAdressTextField.getText().toString(),
53.669115, 12.560311
)
);
mDataBaseRef.push().setValue(newStudioAdd);
Intent intent = new Intent(Rent.this, MapsActivity.class);
startActivity(intent);
}
});
}
as of now the latitude and longitude are hardcoded, as i want it to read the markers before i continue.
This is happening because Studio 1 and T1 have different paths than the T2. As I see in your database schema, your T2 as an extra child (-LH-3 ... GbsF) which is generated by the push() method. In order to display all those objects correctly, you need to have the same paths for all objects. So you can achieve this, either by adding Studio 1 and T1 in the same way, using the push() method or by adding the T2 without using the push() method.
FirebaseMarker firebaseMarker = new FirebaseMarker(
studioNameTextField.getText().toString(),
studioInfoTextField.getText().toString(),
studioAdressTextField.getText().toString(),
53.669115, 12.560311);
mDataBaseRef.push().setValue(firebaseMarker);
Assuming that the Studios node is a direct child of your Firebase database, here is how you can add the markers on the map:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studiosRef = rootRef.child("Studios");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
FirebaseMarker marker = dataSnapshot.getValue(FirebaseMarker.class);
String StudioName = marker.getStudioName();
String StudioAdress = marker.getStudioAddress();
String StudioDescription = marker.getStudioDescription();
double latitude = marker.getLatitude();
double longitude = marker.getLongitude();
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(location)
.title(StudioName)
.snippet(StudioAdress)
.snippet(StudioDescription))
.showInfoWindow();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
studiosRef.addListenerForSingleValueEvent(valueEventListener);
This has been bugging me for a while now. For some reason, the markers from the firebase is not showing in the map. I have been searching for a while now and I almost looked into different answered questions here. Its either not applicable to my application, or it really doesn't work.
I tried to add static, hardcoded latlongs for markers. Added a bunch, and the app complies. It shows all the static, hardcoded markers. Unfortunately, together with the firebase call for loop code to create markers still doesn't show.
MapsActivity.java
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener, GoogleMap.OnMarkerClickListener, GoogleMap.OnMyLocationButtonClickListener, GoogleMap.OnMyLocationClickListener, GoogleMap.OnInfoWindowClickListener {
private GoogleMap mMap;
private UiSettings mUiSettings;
static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private DatabaseReference mBlog;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
Marker marker;
List<Blogzone> mapList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initDrawer();
mapList = new ArrayList<Marker>();
mBlog = FirebaseDatabase.getInstance().getReference().child("Blogzone");
mBlog.push().setValue(marker);
//Firebase Auth
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (mAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(MapsActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mAuth.addAuthStateListener(mAuthListener);
mMap = googleMap;
mUiSettings = mMap.getUiSettings();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
mMap.setMyLocationEnabled(true);
// UI Settings state
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setMyLocationButtonEnabled(true);
//Post Markers
mMap.setOnMarkerClickListener(this);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setOnInfoWindowClickListener(this);
mMap.clear();
final LatLng PH = new LatLng(16.566233,121.262634);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(PH, 6));
mBlog.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()){
Blogzone here = s.getValue(Blogzone.class);
double latitude = Double.parseDouble(here.latitude);
double longitude = Double.parseDouble(here.longitude);
mapList.add(here);
for (int i = 0; i < mapList.size(); i++)
{
LatLng LOC = new LatLng(latitude,longitude);
if (mMap != null) {
Log.d("the locations", "Get location: " + latitude + ", " + longitude + " at " + here.title);
marker = mMap.addMarker(new MarkerOptions().position(LOC).title(here.title));
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Blogzone.class
public class Blogzone {
public String title, desc, imageUrl, username;
public String latitude, longitude;
public Blogzone(String title, String desc, String imageUrl, String username, String latitude, String longitude) {
this.title = title;
this.desc = desc;
this.imageUrl=imageUrl;
this.username = username;
this.latitude = latitude;
this.longitude = longitude;
}
public Blogzone() {
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public void setUsername(String username) {
this.username = username;
}
public void setTitle(String title) {
this.title = title;
}
public void setDesc(String desc) { this.desc = desc; }
public void setlatitude(String latitude) { this.latitude = latitude; }
public void setLongitude(String longitude) { this.longitude = longitude; }
public String getUsername() {
return username;
}
public String getImageUrl() {
return imageUrl;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
edit:
Here's the logs.
there are some null string error but I think it doesn't affect the problem
Note that this is just a project app and I just learned from different tutorials and demos around the web. I just started coding Java last year.
I hope someone could help me soon.
I want to place a marker on a specific location. At first, I thought this would be simple to do but somehow I'm getting confused and I haven't found something that actually gives me what I need. I've tried to base my activity on whats it's done in this video https://www.youtube.com/watch?v=HD48FBwY9U0
My activity starts by receiving an object information on a getIntent() which I then extract the information. In that object (in this case, a car), there is a lot of properties and 2 of them, are the latitude and longitude. The previous are in Double values.
The problem that I am facing is that I don't know how to input the information that I got from the object into the program. I'm placing the code below. Any suggestions?
public class Geolocalizcao extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
public static int REQUEST_ERROR_CODE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geolocalizcao);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
Intent i = getIntent();
CarDataset cardata = (CarDataset) i.getExtras().getParcelable("select");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
return;
}
}
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Here!");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(3));
if(client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);
}
return false;
}
else
return false;
}
#Override
// When connection is lost...
public void onConnectionSuspended(int i)
{
Toast.makeText(this, "Lost connection. Trying to reconnect...", Toast.LENGTH_SHORT);
client.connect();
}
#Override
// Called when the API client doesnt sucessufly connect
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
if (!connectionResult.hasResolution())
{
GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), 0).show();
return;
}
try
{
connectionResult.startResolutionForResult(this, REQUEST_ERROR_CODE );
} catch (IntentSender.SendIntentException e)
{
Log.e("LOG", "Exception:", e);
}
}
Here's the class CarDataset that I use:
public class CarDataset implements Parcelable
{
int vehicleID;
String model;
String licencePlate;
String brand;
Double latitude;
Double longitude;
public CarDataset(Integer nVehicleID, String nModel, String nLicencePlate, String nBrand, Double nLatitude, Double nLongitude)
{
this.vehicleID = nVehicleID;
this.model = nModel;
this.licencePlate = nLicencePlate;
this.brand = nBrand;
this.latitude = nLatitude;
this.longitude = nLongitude;
}
public int getVehicleID() {
return vehicleID;
}
public void setVehicleID(int vehicleID) {
this.vehicleID = vehicleID;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getLicencePlate() {
return licencePlate;
}
public void setLicencePlate(String licencePlate) {
this.licencePlate = licencePlate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeInt(vehicleID);
dest.writeString(model);
dest.writeString(licencePlate);
dest.writeString(brand);
dest.writeDouble(latitude);
dest.writeDouble(longitude);
}
public static final Parcelable.Creator<CarDataset> CREATOR
= new Parcelable.Creator<CarDataset>()
{
public CarDataset createFromParcel(Parcel input)
{
return new CarDataset(input);
}
public CarDataset[] newArray(int size)
{
return new CarDataset[size];
}
};
private CarDataset(Parcel input)
{
vehicleID = input.readInt();
model = input.readString();
licencePlate = input.readString();
brand = input.readString();
latitude = input.readDouble();
longitude = input.readDouble();
}
}
All you need to do is create a LatLng object with the latitude and longitude from the CarDataset object that you get from the Intent.
Marker carMarker;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (cardata != null) {
LatLng latLngCar = new LatLng(cardata.latitude, cardata.longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLngCar);
markerOptions.title("Car");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
carMarker = mMap.addMarker(markerOptions);
}
//.............
}
You will also need to modify onCreate() so that cardata is an instance variable:
CarDataset cardata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geolocalizcao);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
Intent i = getIntent();
//use instance variable:
cardata = (CarDataset) i.getExtras().getParcelable("select");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(3));
mMap.addMarker(new MarkerOptions()
.title("Here!")
.icon(BitmapDescriptorFactory.defaultMarker())
.position(latlng_object));
i have two simple classes. Main and some kind of gps helper. I'm trying to reach distance when gps posiotion has change (on Location change). It works and Toast good but when i try to save variable dis using setter, and reach it in my MainActivity(last method called ObliczanieOdl) a allways have 0.0. Why? Any suggestions?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
#BindView(R.id.butStop)
Button butStop;
#BindView(R.id.butWynik)
Button butKoniec;
private GoogleMap mMap;
private String dlugosc;
private String szerokosc;
private LatLng StartP, StopP;
private Date czasS;
private DatabaseHelper mDatabaseHelper;
private String adres;
private int Dystans;
private boolean oneStop = false;
private GPStracker gpStracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ButterKnife.bind(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
Intent intent = getIntent();
gpStracker = new GPStracker(getApplicationContext());
dlugosc = intent.getStringExtra("dlugosc");
szerokosc = intent.getStringExtra("szerokosc");
StartP = new LatLng(Double.parseDouble(szerokosc), Double.parseDouble(dlugosc));
czasS = new Date();
mDatabaseHelper = new DatabaseHelper(this);
mDatabaseHelper.setStartP(getAdres(StartP));//wyciągnięcie adresu rozpoczęcia podróży
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
addMarker(StartP);
}
private void addMarker(LatLng pozycja) {
mMap.addMarker(new MarkerOptions().position(pozycja));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(pozycja)
.zoom(10).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#OnClick(R.id.butStop)
public void butStop() {
if (oneStop == false) {
oneStop = true;
Location location = gpStracker.getlocation();
if (location != null) {
StopP = new LatLng(location.getLatitude(), location.getLongitude());
}
addMarker(StopP);
mDatabaseHelper.setKoniecP(getAdres(StopP)); //wyciągnięcie adresu zakonczenia podróży
//wyciągnięcie odległości i czasu podróży
mDatabaseHelper.setCzasP(String.valueOf(ObliczanieOdl(StartP, StopP)) + " KM " + "w czasie: " + WyliczCzas());
boolean insertData = mDatabaseHelper.addData();
} else {
toastMessage("Twoja podróż została zakończona");
}
}
#OnClick(R.id.butWynik)
public void butKoniec() {
if (oneStop == false) {
toastMessage("Musisz zakończyć podróż wciskając STOP");
} else {
Intent intent = new Intent(MapsActivity.this, ListDataActivity.class);
startActivity(intent);
}
}
public double ObliczanieOdl() {
Double metry = gpStracker.getDis();
return metry;
}
}
and second as a GPS Helper:
public class GPStracker implements LocationListener {
Context context;
double plat;
double plon;
double clat;
double clon;
public double dis;
public GPStracker(Context c) {
context = c;
}
public Location getlocation() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Uprawnienia nie przyznane", Toast.LENGTH_SHORT).show();
}
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGPSenabled;
isGPSenabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSenabled) {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, this);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return location;
} else {
Toast.makeText(context, "Proszę włączyć GPS", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
public void onLocationChanged(Location location) {
clat = location.getLatitude();
clon = location.getLongitude();
if (clat != plat || clon != plon) {
dis += getDistance(plat, plon, clat, clon);
plat = clat;
plon = clon;
setDis(dis);
}
Toast.makeText(context, String.valueOf(dis), Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public double getDistance(double lat1, double lon1, double lat2, double lon2) {
double latA = Math.toRadians(lat1);
double lonA = Math.toRadians(lon1);
double latB = Math.toRadians(lat2);
double lonB = Math.toRadians(lon2);
double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB - lonA)) +
(Math.sin(latA) * Math.sin(latB));
double ang = Math.acos(cosAng);
double dist = ang * 6371;
return dist;
}
public double getDis() {
return dis;
}
public void setDis(double dis) {
this.dis = dis;
}
}
I have two classes.. First.java and Second.java,
In the First class.. latitude, longitude, and address show correctly in TextView.
But in Second class, latitude and longitude become 0.0 , address becomes null.
Can anyone help me why?
Here's the code for First.java
public class First extends Activity {
private Context context=null;
AppLocationService appLocationService;
String address;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_location);
context=this;
appLocationService = new AppLocationService(First.this);
btngetLocation=(Button)findViewById(R.id.button_getLocation);
btngetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// getting GPS status
boolean isGPSEnabled = appLocationService
.getStatus(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = appLocationService
.getStatus(LocationManager.NETWORK_PROVIDER);
if( isGPSEnabled==false && isNetworkEnabled==false){
showSettingsAlert("Location Service");
}
else {
Toast.makeText(
getApplicationContext(),
"Attempt to get location...Please Wait.. ",
Toast.LENGTH_LONG).show();
if( isNetworkEnabled ==true ){
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation == null){
Toast.makeText(
getApplicationContext(),
"Network bermasalah.. Pastikan Anda terkoneksi Internet, dan coba get Location lagi",
Toast.LENGTH_LONG).show();
}
else {
latitude = nwLocation.getLatitude();
longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
}
}
else {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation == null){
Toast.makeText(
getApplicationContext(),
"GPS bermasalah.. Silahkan di ruangan terbuka atau aktifkan network provider Anda, dan coba get Location lagi",
Toast.LENGTH_LONG).show();
}
else {
latitude = gpsLocation.getLatitude();
longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
}
}
}
}
});
}
public class AppLocationService extends Service implements LocationListener{
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10; //10 meter
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 3; //3 menit
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public boolean getStatus(String provider){
return locationManager.isProviderEnabled(provider); /
}
public Location getLocation(String provider) {
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
locationManager.removeUpdates(this);
return location;
}
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
public String getAddress(Context ctx, double latitude, double longitude) {
// StringBuilder result = new StringBuilder();
String alamat=null;
try {
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
String jalan = (address.getAddressLine(0));
String locality=address.getLocality();
String country=address.getCountryName();
String country_code=address.getCountryCode();
String zipcode=address.getPostalCode();
alamat = jalan +", "+ locality +", "+ country+", " + country_code+", " + zipcode;
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return alamat;
}
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
public String getAlamat(){
return address;
}
Here's Second. java
public class Second extends Activity{
AddLocation data_dr_location;
Double latitude;
Double longitude;
String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_description);
data_dr_location = new AddLocation();
address= data_dr_location.getAlamat();
latitude = data_dr_location.getLatitude();
longitude = data_dr_location.getLongitude(); }
In your first java, there is only getter method and no setter method!
private double latitude;
private double longitude;
private String address;
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
public String getAlamat(){
return address;
}
/* THE BELOW SETTER METHODS ARE MISSING IN YOUR CODE.*/
public void setLatitude(double latitude){
this.latitude = latitude;
}
public void setLongitude(double longitude){
this.longitude=longitude;
}
public setAlamat(String address){
this.address=address;
}
At appropriate location (say whereever you get lat/long/address), add these lines.
latitude = nwLocation.getLatitude();
setLatitude (latitude);
longitude = nwLocation.getLongitude();
setLongitude (longitude);
your are only getting value.means you have written getter mehtod. you have not set value using setter method. please try that and check.
public void setLatitude(double latitude){
this.latitude = latitude;
}
public void setLongitude(double longitude){
this.longitude=longitude;
}
public setAlamat(String address){
this.address=address;
}