Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – How to fetch specific data from a Firestore database on an activity after clicking on a specific marker in Mapview?

Posted on November 11, 2022 By

Solution 1 :

First You need to check whether the latitude that generated is existed in database fields or not. Check it out official documentation.

Firestore documentation

Then if existed you will get the document id and you can use that.

Problem :

I created a fragment and took a Mapview on it. My Firestore database has a collection called Job Post1 which contains some documents and some fields in it. With that, I fetch Longitude and Latitude with the help of a marker shown on the Mapview.

What I want to do: after clicking on the marker on the Mapview, I want to show all fields in that document (the document from which i have plotted the marker with the help of longitude and latitude) on a Bottomsheet which I created.

What I did: I fetched the fields using documentsnapshot and in the updateBottomSheetContent() method I created a Strings and setText it.
After doing this, when I click on the marker, the hidden sheet is open and data fetch on it of his document but when I click another marker same data fetch instead of his own document. This is my problem.

My Java Code

package part.time.job.v2;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.Constraints;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.PlaceLikelihood;
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.maps.android.ui.IconGenerator;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import model.Jobpost;
import model.Journal;

import static com.android.volley.VolleyLog.TAG;


/**
 * A simple {@link Fragment} subclass.
 */
public class LabourFragment extends Fragment  implements OnMapReadyCallback {
    private GoogleMap mGoogleMap;
    private MapView mMapview;


    private Location mLastKnownLocation;
    Dialog myDialog;
    private BottomSheetBehavior bottomSheetBehavior;
    private View bottomSheet;
    private String title1;
    private String desc1;
    private String cate1;
    private String age1;
    private String vac1;
    private String loc1;
    private String jdate1;
    private String time1;
    private String whour1;


    FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
    CollectionReference mOrderRef = mDatabase.collection("Job Post1");

    public LabourFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {



        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_labour, container, false);
//        myDialog = new Dialog(getActivity());
        bottomSheet = view.findViewById(R.id.bottom_sheet);
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        bottomSheetBehavior.setPeekHeight(120);
        bottomSheetBehavior.setHideable(true);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

        Places.initialize(getActivity(), getString(R.string.google_maps_key));
        mPlacesClient = Places.createClient(getActivity());


        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());


        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mGoogleMap != null) {
            outState.putParcelable(KEY_CAMERA_POSITION, mGoogleMap.getCameraPosition());
            outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view,  Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapview = (MapView) view.findViewById(R.id.mapView);

        if (mMapview!=null){
            mMapview.onCreate(null);
            mMapview.onResume();
            mMapview.getMapAsync(this);
        }
    }



    @Override
    public void onMapReady(final GoogleMap googleMap) {

        mGoogleMap=googleMap;

        FirebaseFirestore mDatabase = FirebaseFirestore.getInstance();
        CollectionReference mOrderRef = mDatabase.collection("Job Post1");

        mOrderRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                for(QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                    if(documentSnapshot.contains("lat") && documentSnapshot.contains("lon")) {
                        String lat = (String) documentSnapshot.get("lat");
                        String lon = (String) documentSnapshot.get("lon");
                        title1= (String) documentSnapshot.get("title");
                        desc1= (String) documentSnapshot.get("desc");
                        cate1= (String) documentSnapshot.get("category");
                        age1= (String) documentSnapshot.get("age");
                        vac1= (String) documentSnapshot.get("vacancy");
                        loc1= (String) documentSnapshot.get("location");
                        jdate1= (String) documentSnapshot.get("jobdate");
                        time1= (String) documentSnapshot.get("time");
                        whour1=(String) documentSnapshot.get("workinghours");

                            if(lat != null && lon != null && !lat.isEmpty() && !lon.isEmpty()) {
                            double latitude = Double.parseDouble(lat.trim());
                            double longitude = Double.parseDouble(lon.trim());
                            IconGenerator iconGen = new IconGenerator(getActivity());

                            googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(title1).icon(BitmapDescriptorFactory.fromBitmap(iconGen.makeIcon(title1))));
                            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 18.0f));

                            googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

                                @Override
                                public boolean onMarkerClick(Marker marker) {
                                    marker.getTitle();

                                    updateBottomSheetContent(marker);
                                    return true;
                                }
                            });
                            googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                                @Override
                                public void onMapClick(LatLng latLng) {
                                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                                }
                            });

                        }

                    }
                }



            }

        });

         }

    private void updateBottomSheetContent(final Marker marker) {
        final TextView jobT = (TextView) bottomSheet.findViewById(R.id.jobTitle);
       final TextView desc = (TextView) bottomSheet.findViewById(R.id.jobDesc);
        final TextView cate = (TextView) bottomSheet.findViewById(R.id.categ);
        final TextView age = (TextView) bottomSheet.findViewById(R.id.ageLimit);
        final TextView vac = (TextView) bottomSheet.findViewById(R.id.vacan);
        final TextView loc = (TextView) bottomSheet.findViewById(R.id.locat);
        final TextView workingH = (TextView) bottomSheet.findViewById(R.id.workingHour);
        final TextView date = (TextView) bottomSheet.findViewById(R.id.jobDate);
        final TextView expire = (TextView) bottomSheet.findViewById(R.id.jobExpire);
        final TextView uid = (TextView) bottomSheet.findViewById(R.id.uid);
        final TextView time = (TextView) bottomSheet.findViewById(R.id.timeStart);



        jobT.setText(title1);
        desc.setText(desc1);
        cate.setText(cate1);
        age.setText(age1);
        vac.setText(vac1);
        loc.setText(loc1);
        workingH.setText(whour1);
        date.setText(jdate1);
        time.setText(time1);


        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }


}

This is Database Structure

READ  [FIXED] android - How can I give Linear gradient to my entire flutter app?
Powered by Inline Related Posts

Comments

Comment posted by Ashish

Please post database structure

Comment posted by AnyTHings S3

posted @ Ashish check in Question

Android Tags:android, android-mapview, firebase, google-cloud-firestore, google-maps-markers

Post navigation

Previous Post: [FIXED] Xamarin.forms – Trouble behaviour between ListView & keyboard
Next Post: [FIXED] android – two elements in linear layout are packed to center instead of to the sides

Related Posts

[FIXED] android – How do you add a marker on google map after button click on dialogFragment? Android
[FIXED] Android Studio 3.6.3 Update does not launch apk on click of “run” icon Android
[FIXED] Android studio – play store – fails to upload – icon is not valid Android
[FIXED] FILENOTFOUND Exception while reading File from file uri for Recent file location and google drive file location in android Android
[FIXED] In Android SQlite Data Base I Got This Error:E/SQLiteLog: (1) table tbl_Individual_Registration has no column named MobileNo Android
[FIXED] android – What is an unregistered parameter in a UrlQuerySanitizer? Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What color are dead flea eggs?
  • What is Indiana vine?
  • What’s the downside of a Chromebook?
  • Is phosphide the same as phosphorus?
  • Why do you need an S bend?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme