2

Greetings to the community. This is my first question, please guide me if I did any mistake.

I have four fragments in my app. An activity(Main Activity) that hosts all the four fragments.

  1. Google Maps Fragment
  2. Fragment two
  3. Fragment three
  4. Fragment four

When the application starts. Maps fragment is loaded and it shows marker at my current location. But when I move from Maps fragment to Fragment two and then came back to Map Fragment it doesn't show my current location

Here is the code

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


// Fragments
private MapsFragment mapsFragment = new MapsFragment();
private QrScanFragment qrScanFragment = new QrScanFragment();
private SeatsFullFragment seatsFullFragment = new SeatsFullFragment();
private EmergencyFragment emergencyFragment = new EmergencyFragment();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initLayouts();
    initListeners();

    // Maps Fragment Loaded
    mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
    loadFragment(mapsFragment);
   }
 }

loadFragment(Fragment fragment)

public void loadFragment(Fragment fragment) {
    if (fragment != null) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frame_container, fragment)
                .commit();
    }
}

Moving b/w fragments

if (view == mLlMaps) {
        if (!mapsFragment.isVisible()) {
            loadFragment(mapsFragment);
            mTvTitle.setText("Map");
        }
        mIvMaps.setImageResource(R.drawable.ic_map_pin_2_line_fill);
        mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));

    } else if (view == mLlQrScan) {
        if (!qrScanFragment.isVisible()) {
            loadFragment(qrScanFragment);
            mTvTitle.setText("ScanQR");
        }
        mIvQrScan.setImageResource(R.drawable.ic_baseline_qr_code_scanner_24_fill);
        mIvQrScan.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
}
   }

MapsFragment.java

public class MapsFragment extends Fragment implements OnMapReadyCallback {

private GoogleMap mMap;
private SupportMapFragment mapFragment;

// To get Current Location of Driver
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;



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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_maps, container, false);

    buildLocationRequest(); // Request for current Location
    buildLocationCallback(); // When location is provided
    updateLocation(); // Fused Location Provider


    // Child Fragment Manager copied from Uber
    mapFragment = (SupportMapFragment) getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);


    return view;
}



// Request for current Location
private void buildLocationRequest() {
    if (locationRequest == null) {
        locationRequest = new LocationRequest();
        locationRequest.setSmallestDisplacement(50f); // 50m
        locationRequest.setInterval(15000);     // 15s
        locationRequest.setFastestInterval(10000); // 10s
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

}


// When location result is provided
private void buildLocationCallback() {
    if (locationCallback == null) {

        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);

                LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),
                        locationResult.getLastLocation().getLongitude());
                // 18f is the radius of circle
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 18f));
            }

        };
    }
}

// Fused Location Provider
private void updateLocation() {
    if (fusedLocationProviderClient == null) {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                &&
                ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(getActivity(), "Permission Required", Toast.LENGTH_SHORT).show();
            return;
        }
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());

    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    Log.d("EB", "onMapReady: called");

    // Check Permission
    Dexter.withContext(getContext())
            .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            .withListener(new PermissionListener() {
                @Override
                public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                            &&
                            ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                        return;
                    }
                    mMap.setMyLocationEnabled(true);
                    mMap.getUiSettings().setMyLocationButtonEnabled(true);
                    mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
                        @Override
                        public boolean onMyLocationButtonClick() {
                            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                                        android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);

                            } else {
                                Toast.makeText(getContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
                            }
                            fusedLocationProviderClient.getLastLocation().addOnFailureListener(new OnFailureListener() {
                                @Override
                                public void onFailure(@NonNull Exception e) {
                                    Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            }).addOnSuccessListener(new OnSuccessListener<Location>() {
                                @Override
                                public void onSuccess(Location location) {
                                    LatLng userLatLng = new LatLng(location.getLatitude(),
                                            location.getLongitude());
                                    // 18f is the radius of circle
                                    mMap.animateCamera(CameraUpdateFactory
                                            .newLatLngZoom(userLatLng, 18f));

                                }
                            });
                            return true;
                        }
                    });

                    // Set Layout - Location Button
                    View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1"))
                            .getParent())
                            .findViewById(Integer.parseInt("2"));

                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
                            locationButton.getLayoutParams();

                    //Right Bottom
                    params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
                    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
                    params.setMargins(0, 0, 0, 50);

                    // Move to current Location
                    buildLocationRequest();
                    buildLocationCallback();
                    updateLocation();

                }

                @Override
                public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
                    Toast.makeText(getContext(),
                            "Permission" + permissionDeniedResponse.getPermissionName() + "wasdenied",
                            Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {

                }
            }).check();


    // Change/Parse the Maps Style
    try {
        boolean success = googleMap.setMapStyle(MapStyleOptions
                .loadRawResourceStyle(getContext(), R.raw.uber_maps_style));
        if (!success)
            Log.e("Error", "Style parsing Error");
    } catch (Resources.NotFoundException e) {
        Log.e("Error", e.getMessage());
    }


     }

  }

0 Answers0