Home > Software engineering >  How to take all the addresses saved in Firebase Realtime Database and show them as markers on google
How to take all the addresses saved in Firebase Realtime Database and show them as markers on google

Time:06-09

I need to make sure that the markers added by the user is also visible to all other users in the google maps activity, so for example if 4 users each put a marker at the end of the map all 4 must be shown. I tried to do this, but once I click on Cardview to be able to go to the Google maps.

I used the log before addreess and also with gender and they are both "Null", how can I solve?

This error appear

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
    at com.example.chatapp.Fragments.TrovamicoActivity$1.lambda$onDataChange$1$com-example-chatapp-Fragments-TrovamicoActivity$1(TrovamicoActivity.java:88)
    at com.example.chatapp.Fragments.TrovamicoActivity$1$$ExternalSyntheticLambda1.onComplete(Unknown Source:2)
    at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

GoogleMaps Activity

 public static final String TAG = "addreess";

//private GoogleMap mMap;
private FragmentsTrovamicoBinding binding;
LatLng latLng;


private DatabaseReference reference;
private FirebaseUser firebaseUser;

List<String> addresses, genders;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = FragmentsTrovamicoBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());
    Log.d(TAG, "String addreess: "   addresses);
    addresses = new ArrayList<>();
    genders = new ArrayList<>();

    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());

  

    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
                reference.child("address").get().addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        String address = task.getResult().getValue().toString();
                        addresses.add(address);
                    }
                });
                Log.d(TAG, "String addreess: "   addresses);
                reference.child("gender").get().addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        String gender = task.getResult().getValue().toString();
                        genders.add(gender);
                    }
                });
            }
        }

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

        }
    };

    reference.addListenerForSingleValueEvent(eventListener);

    // 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);
}

@Override
public void onMapReady(GoogleMap googleMap) {

    for (int i = 0; i < addresses.size(); i  ) {
        String user_address = addresses.get(i);
        if (!user_address.equals("To be added")) {
            Log.d(TAG, "String addreess: "   addresses);
            String user_gender = genders.get(i);
            latLng = getLocationFromAddress(user_address);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("You");
            Log.d(TAG, "String addreess: "   addresses);
            markerOptions.icon(BitmapFromVector(getApplicationContext(), (user_gender.equals("Male")) ? R.drawable.male : R.drawable.female));
            googleMap.clear();
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
            googleMap.addMarker(markerOptions);
        }
    }
}

public LatLng getLocationFromAddress(String strAddress) {

    Geocoder coder = new Geocoder(this);
    List<Address> address;
    LatLng p1;

    try {
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;
        }
        Address location = address.get(0);
        p1 = new LatLng(location.getLatitude(), location.getLongitude());

        return p1;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

private BitmapDescriptor BitmapFromVector(Context context, int vectorResId) {
    // below line is use to generate a drawable.
    Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);

    // below line is use to set bounds to our vector drawable.
    vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());

    // below line is use to create a bitmap for our
    // drawable which we have added.
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);

    // below line is use to add bitmap in our canvas.
    Canvas canvas = new Canvas(bitmap);

    // below line is use to draw our
    // vector drawable in canvas.
    vectorDrawable.draw(canvas);

    // after generating our bitmap we are returning our bitmap.
    return BitmapDescriptorFactory.fromBitmap(bitmap);
}
}

CodePudding user response:

When you load a certain node/path from the Firebase Realtime Database, you get a snapshot with all data under that path. There is no need to make additional calls to get to get that data, as it's already in the snapshot you got.

Knowing this, you can simplify your code to:

ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
            String address = dataSnapshot.child("address").getValue();
            Log.d(TAG, "String address: "   addresses);

            String gender = dataSnapshot.child("gender").getValue();
            Log.d(TAG, "String gender: "   gender);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        throw error.toException(); //            
  • Related