Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Problem:

I can store my location coordinates(lat and long) on my Firebase database using HashMap, but I don't know how to call the HashMap value onto onDataChanged method for DataSnapshot.

What's Working:

I have print the values of latitude and longitude on my logcat and my HashMap has the value. Below is my SmsReceiver.class which reads incoming messages, and save these data to Firebase database.

My MapActivity.class is currently showing default coordinates to show on map. I am confused on how I am going to access the HashMap value from the SmsReceiver.class to display a marker on GoogleMap.

What I have tried:

public void sendDataToFirebase(SmsMessage sms, Context context) {

       FirebaseApp.initializeApp(context);
       databaseLocation = FirebaseDatabase.getInstance().getReference("database");

       String senderNumber = sms.getOriginatingAddress();
       String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
       String message = sms.getMessageBody();
       String[] separatedSMS = message.split("\\s+");


           DatabaseReference mRef = databaseLocation.push();

           double latitudedb = Double.parseDouble(separatedSMS[1]);
           double longitudedb = Double.parseDouble(separatedSMS[3]);

           HashMap<String,Double> coordinates = new HashMap<String,Double>();
           coordinates.put("latitude", latitudedb);
           coordinates.put("longitude", longitudedb);
           mRef.setValue(coordinates);

           coordinates.get("latitude");
           coordinates.get("longitude");


           mRef.getKey();

           System.out.println(coordinates.get("latitude"));
           System.out.println(coordinates.get("longitude"));


       }



This is my MapActivity.class.

public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        mMap.setMinZoomPreference(15.0f);
        mMap.setMaxZoomPreference(20.0f);
        final LatLng putatan = new LatLng(14.397420, 121.033051);

        final DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("conilocationdata");

        ValueEventListener postListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get Post object and use the values to update the UI


                for(DataSnapshot ds : dataSnapshot.getChildren()) {

//         This is where I should be accessing the HashMap value but I have no idea on the syntax.

//This is the default marker.

                    marker = mMap.addMarker(new MarkerOptions()
                            .position(putatan)
                            .title("Here")
                            .flat(true));

                    mMap.moveCamera(CameraUpdateFactory.newLatLng(putatan));

                }


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
                // ...
            }
        };
        mRef.orderByKey().limitToLast(1).addValueEventListener(postListener);
Posted
Comments
David Crow 20-Mar-19 10:24am    
If it is only one pair of coordinates that you need mapped, you could: 1) store them in your app's preferences area and retrieve them from the same inside of onDataChange(), or 2) store them in your application class (this class is not created by default), or 3) pass them to your MapActivity class using an Intent.

If you need multiple coordinates mapped, these same solutions would work but they may not be the most efficient.
sfdgasdfqqqq 20-Mar-19 10:31am    
Hello. This is what I have tried but I am getting a NullObjectReference error on my LatLng.

HashMap <string, double=""> hashMap = smsReceiver.getLocMap(coordinates);
if(hashMap != null) {
// Double lat = hashMap.get("latitude");
// Double lon = hashMap.get("longitude");


LatLng location = new LatLng(coordinates.get("latitude"),coordinates.get("longitude"));
marker = mMap.addMarker(new MarkerOptions()
.position(location)
.title("Here")
.flat(true));

mMap.moveCamera(CameraUpdateFactory.newLatLng(location));

This is my a class with my hashmap.
//variable
private HashMap<string, double=""> coordinates = new HashMap<string, double="">();

public void sendDataToFirebase(SmsMessage sms, Context context) {
coordinates.put("latitude", latitudedb);
coordinates.put("longitude", longitudedb);
mRef.setValue(coordinates);

Double lcoords = coordinates.get("latitude");
Double lcoords2 = coordinates.get("longitude");




mRef.getKey();

System.out.println(lcoords);
System.out.println(lcoords2);

// }

}

public HashMap<string, double=""> getLocMap(HashMap<string, double=""> coordinates) {
return this.coordinates;

}

When I print out my coordinates, it has the values.
sfdgasdfqqqq 20-Mar-19 10:41am    
Also, I tried using Intent but it says, cannot resolve constructor. Maybe because, SmsReceiver is only a class, not an activity itself.
David Crow 20-Mar-19 10:53am    
You are already using an intent when displaying the map, presumably something like:

Intent intent = new Intent(this, MapActivity.class);
intent.putExtra(...);
startActivity(intent, REQUEST_MAP);
sfdgasdfqqqq 20-Mar-19 11:40am    
I am passing a Double data type. I inserted this code:

Intent toMap = new Intent(context,MapActivity.class);
Bundle coords = new Bundle();
coords.putDouble("lat",lcoords);
coords.putDouble("lon",lcoords2);
toMap.putExtras(coords);
context.startActivity(toMap);

System.out.print(coords);

lcoords contains the latitude. lcoords2 contains the longitude. Whenever I access the Bundle to my MapActivity.class, it says "getDouble on a null object reference"

Bundle coords = getIntent().getBundleExtra("coords");
double lat1 = coords.getDouble("lat");
double lon2 = coords.getDouble("lon");

LatLng location = new LatLng(lat1,lon2);
marker = mMap.addMarker(new MarkerOptions()
.position(location)
.title("Here")
.flat(true));

mMap.moveCamera(CameraUpdateFactory.newLatLng(location));


If I comment out those codes, lcoords and lcoords2 have values and is not null.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900