2
\$\begingroup\$

I need someone review my google map class , here is my situation I am working in medical project , I created one class to show hospital items in map with data object , here is my fragment class , I create helper class as I don't like to put all methods in long class.

import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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.imaadv.leaynik.Interfaces.VolleyResponseCallBack;
import com.imaadv.leaynik.Interfaces.onLocChange;
import com.imaadv.leaynik.Util.AppConstants;
import com.imaadv.leaynik.Util.MapUtils;
import com.imaadv.leaynik.api.VolleyRequestHandler;
import com.imaadv.leaynik.model.Hospital_Item;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class ClinicFragment extends Fragment implements OnMapReadyCallback, VolleyResponseCallBack, onLocChange {

    private static final String DISTANCE = "1000" ;
    private GoogleMap mMap;
    private MapUtils mapUtils;
    private VolleyRequestHandler _volleyRequestHandler;
    private HashMap<Marker , Hospital_Item> marksHashMap ;

    public static ClinicFragment newInstance() {
        ClinicFragment fragment = new ClinicFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_maps, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        marksHashMap = new HashMap<>();

        _volleyRequestHandler = new VolleyRequestHandler(getActivity());

        mapUtils = new MapUtils(getActivity());

        if (!mapUtils.isGpsEnable()) {
            mapUtils.ShowGpsSettingDialog();
        }

        mapUtils.getCurrentLoc(this);

        return view;
    }


    private void FetchLocationData(Location location) {
        Map<String, String> params = new HashMap<>();
        double lat = location.getLatitude();
        double lon = location.getLatitude();
        params.put(AppConstants.LAT, Double.toString(lat));
        params.put(AppConstants.LON , Double.toString(lon));
        params.put(AppConstants.DISTANCE , DISTANCE);
        _volleyRequestHandler.HandleRequests(Request.Method.POST, VolleyRequestHandler.LOCATION_INT, params, this);
    }

    @Override
    public void RequestSuccess(Object response) {
        if(response != null){
            ArrayList<Hospital_Item> items = (ArrayList<Hospital_Item>) response;
            CreateMarkerWithData(items);
        }
    }
    @Override
    public void RequestFailed(String error) {
        if(error != null){
            Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
        }
    }

    protected void CreateMarkerWithData(ArrayList<Hospital_Item> items){

        for(int i=0 ; i<items.size(); i++){
            Hospital_Item item = items.get(i);
            double lat = Double.parseDouble(item.getPosition_x());
            double lon = Double.parseDouble(item.getPosition_y());
            LatLng latLng = new LatLng(lat , lon);
            Marker mark = mMap.addMarker(new MarkerOptions().position(latLng).title(item.getHospital_name()));
            marksHashMap.put(mark , item);
        }


    }
    @Override
    public void onMapReady(com.google.android.gms.maps.GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return false;
            }
        });
    }
    @Override
    public void newLoc(Location location) {
        FetchLocationData(location);
        LatLng mlatLng = new LatLng(location.getLatitude() ,location.getLongitude());
        CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLng(mlatLng);
        mMap.moveCamera(mCameraUpdate);
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        mapUtils.removeUpdate(mMap);
    }
    @Override
    public void onPause() {
        super.onPause();
        mapUtils.removeUpdate(mMap);
    }
}

my helper class

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;

import com.google.android.gms.maps.GoogleMap;
import com.imaadv.leaynik.Interfaces.onLocChange;
import com.imaadv.leaynik.R;


public class MapUtils implements LocationListener {

    public static final int MIN_TIME = 5000;
    public static final int MIN_DISTANCE = 10;
    private Context _context;
    private LocationManager lm;
    public static int GPS_RESULT = 101;
    public onLocChange callBack;

    public MapUtils(Context _ctx) {
        this._context = _ctx;
        lm = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
    }

    // check if gps is on or off
    public boolean isGpsEnable() {
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public boolean isNetworkProvide() {
        return lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }

    // if gps is off , I show alert to user to open it
    public void ShowGpsSettingDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(_context);
        builder.setTitle(R.string.gps)
                .setMessage(R.string.enablegps)
                .setCancelable(false)
                .setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        _context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();

    }

    public void getCurrentLoc(onLocChange listener) {
        callBack = listener;
        if(checkPermission()) {
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
        }
    }

    public void removeUpdate(GoogleMap mMap) {
        if(checkPermission()&& lm != null && mMap != null){
            lm.removeUpdates(this);
        }

    }

    private boolean checkPermission(){
        if (ActivityCompat.checkSelfPermission(_context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(_context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return false;
        }
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        callBack.newLoc(location);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    private Boolean displayGpsStatus() {
        ContentResolver contentResolver = _context.getContentResolver();
        boolean gpsStatus = Settings.Secure
                .isLocationProviderEnabled(contentResolver,
                        LocationManager.GPS_PROVIDER);
        if (gpsStatus) {
            return true;

        } else {
            return false;
        }
    }



}

I want best practice to avoid battery daring , fast performance

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.