Devarsh bhatt
Devarsh bhatt

Reputation: 1

How to retrieve latitude and longitude from firebase database to android map application

I'm working on a bus tracking application, which contain Driver application and Student application. So i can store the co-ordinates from driver application to firebase realtime database. but when i tried to retrieve the co-ordinates and tries to show them on map with marker, the application crash right away. I don't know why this is happening, and I'm currently following a youtube video course for this.

Help would be greatly appreciated.

So this is a firebase database, so i have given the permission for both read and write just for test purposes and it should be like when i press on the button it should find the nearest bus rider, retrieve the co-ordinates from firebase and store in a double variable and show them on a map.

So for driver i'm using Geofire to store location in firebase and here is the code :

   @Override
   public void onLocationChanged(Location location) {
      if(getApplicationContext() != null){

        mLastLocation = location;

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new 
LatLng(location.getLatitude(), location.getLongitude()), 16.5f));

        String UserId =      
Objects.requireNonNull(FirebaseAuth.getInstance()
.getCurrentUser()).getUid();
        DatabaseReference refAvail = FirebaseDatabase.getInstance().getReference("Location").child("Driver");

        GeoFire geoFire = new GeoFire(refAvail);
        geoFire.setLocation(UserId, new GeoLocation(location.getLatitude(), location.getLongitude()));
    }
}

And for client application, i have tried this :

mCFS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pickuplocation = new LatLng(mLastLocation.getLatitude(), 
mLastLocation.getLongitude());

            mMap.addMarker(new 
MarkerOptions().position(pickuplocation).title("Student is here"));

            mCFS.setText("Sending Location");

            getClosestDriver();

        }
    });
}

The getClosestDriver() & getDriverLocation() method with some variables :

private int radius = 1;

private Boolean driverFound = false;
private String driverFoundID;

private void getClosestDriver(){
    DatabaseReference DriverLocation = 
FirebaseDatabase.getInstance().getReference("Location").child("Driver");

    GeoFire geoFire = new GeoFire(DriverLocation);

    GeoQuery geoQuery = geoFire.queryAtLocation(new 
GeoLocation(pickuplocation.latitude, pickuplocation.longitude), radius);
    geoQuery.removeAllListeners();

    geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(String key, GeoLocation location) {
            if(!driverFound)
            {
                driverFound = true;
                driverFoundID = key;
                Toast.makeText(getApplicationContext(), "Driver KEY 
Found", Toast.LENGTH_SHORT).show();

                getDriverLocation();
                mCFS.setText("Looking For Driver Location");
            }
        }

        @Override
        public void onKeyExited(String key) {

        }

        @Override
        public void onKeyMoved(String key, GeoLocation location) {

        }

        @Override
        public void onGeoQueryReady() {
            if(!driverFound){
                radius++;
                getClosestDriver();
            }
        }

        @Override
        public void onGeoQueryError(DatabaseError error) {

        }
    });
}


Marker mMarker;
private void getDriverLocation(){
    DatabaseReference DLref = 
FirebaseDatabase.getInstance().getReference("Location")
.child("Driver").child(driverFoundID).child("l");
    DLref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                List<Objects> map = (List<Objects>) 
dataSnapshot.getValue();
                double locationLat = 0;
                double locationLng = 0;
                mCFS.setText("Driver Found");

                assert map != null;
                if(map.get(0) != null){
                    locationLat = 
Double.parseDouble(map.get(0).toString());
                }

                if(map.get(1) != null){
                    locationLng = 
Double.parseDouble(map.get(1).toString());
                }
                LatLng DriverLatLng = new LatLng(locationLat, 
locationLng);
                if(mMarker != null){
                    mMarker.remove();
                }
                mMarker = mMap.addMarker(new 
MarkerOptions().position(DriverLatLng).title("Bus"));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

} 

In my output, i get the Toast "Driver Key Found" but after that the application crash without any marker on the map. you guys can also watch the Simcoder Uber Clone Tutorial #7,8,9 i have followed that one to get my desire output.

Here is the Logcat Output as soon as the app crashes :

02-03 10:28:13.023 32241-32241/com.example.clientapplication 
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.clientapplication, PID: 32241
java.lang.ClassCastException: java.lang.Double cannot be cast to 
java.util.Objects
    at 
com.example.clientapplication.ClientMap$4.onDataChange
(ClientMap.java:163)
    at 

com.google.firebase.database.core.ValueEventRegistration.fireEvent
(com.google.firebase:firebase-database@@16.0.6:75)
    at 
 com.google.firebase.database.core.view.DataEvent.fire
(com.google.firebase:firebase-database@@16.0.6:63)
    at 
 com.google.firebase.database.core.view.EventRaiser$1.run
(com.google.firebase:firebase-database@@16.0.6:55)
    at android.os.Handler.handleCallback(Handler.java:742)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:157)
    at android.app.ActivityThread.main(ActivityThread.java:5601)
    at java.lang.reflect.Method.invoke(Native Method)
    at 
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:774)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)

If you guys want my firebase database output, let me know i will post the image with the data in it.

Upvotes: 0

Views: 3665

Answers (1)

Suvidha Malaviya
Suvidha Malaviya

Reputation: 342

You can retrieve the data from firebase using following method of database reference class.

//Get the reference of parent node...
firebaseDatabase= FirebaseDatabase.getInstance()
databaseReference=firebaseDatabase?.getReference("student")

//Create the listener to fetch data...
databaseReference?.addValueEventListener(object :ValueEventListener{
override fun onCancelled(p0: DatabaseError)
{ }

override fun onDataChange(p0: DataSnapshot)
{
lststudent.clear()
var child=p0.children
child.forEach {
     var map=it.value as HashMap<String, String>
     lststudent.add(map)
}
//here you have to use the data fetch from real time databse in outside this method it will reset the data...
lvstud.adapter= SimpleAdapter(this@MainActivity,
                        lststudent,
                        R.layout.student,
                        arrayOf("studname","studmobno"),
                        intArrayOf(R.id.tvStudname,R.id.tvStudmobno))
            }
})

Upvotes: 2

Related Questions