получить нулевое значение для GoogleApiclient во фрагменте? - PullRequest
1 голос
/ 27 января 2020

Вот мой код. Я получаю нулевое значение в googleapiclient.

public class MapsActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener, AdapterView.OnItemClickListener, DriverListner {

    View view;
    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    private static String TAG = "MAP LOCATION";
    Context mContext;
    TextView mLocationMarkerText;
    private LatLng mCenterLatLong;
    private AddressResultReceiver mResultReceiver;
    protected String mAddressOutput;
    protected String mAreaOutput;
    protected String mCityOutput;
    protected String mStateOutput;
    EditText mLocationAddress;
    TextView mLocationText;
    private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
    AutoCompleteTextView edtDropLocation;
    LatLng source;
    LatLng destination;
    LinearLayout lytBottomView;
    private List < DriverDetail > driverDetailsList = new ArrayList < > ();
    DriverListAdapter driverListAdapter;
    RecyclerView rv_driver_truck;
    DriverDetail driverDetail;
    Button book;
    int driverId = 0, userId = 0;
    String currentLocation = "", dropLocation = "", currentLat = "", currentLong = "", dropLat = "", dropLong = "", token = "",
        vehicleId = "", bookingDateTime = "", truckRent = "";
    private LocationRequest mLocationRequest;
    Date currentTime;
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.activity_maps, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);


        userId = Integer.parseInt(TruckApplication.ReadStringPreferences(SharedPrefData.PREF_UserId));
        token = TruckApplication.ReadStringPreferences(SharedPrefData.PREF_TOKEN);
        currentTime = Calendar.getInstance().getTime();
        Log.e("@@dateandtime", String.valueOf(currentTime));

        mLocationMarkerText = view.findViewById(R.id.locationMarkertext);
        rv_driver_truck = view.findViewById(R.id.rv_driver_truck);
        mLocationAddress = view.findViewById(R.id.Address);
        mLocationText = view.findViewById(R.id.Locality);
        edtDropLocation = view.findViewById(R.id.edtDropLocation);
        lytBottomView = view.findViewById(R.id.lytBottomView);
        book = view.findViewById(R.id.book);
        edtDropLocation.setAdapter(new MapFragment.GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item_text));
        edtDropLocation.setOnItemClickListener(this);
        mLocationText.setOnClickListener(view - > openAutocompleteActivity());
        mapFragment.getMapAsync(this);




        if (checkPlayServices()) {

            if (!AppUtils.isLocationEnabled(getContext())) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                dialog.setMessage("Location not enabled!");
                dialog.setPositiveButton("Open location settings", (paramDialogInterface, paramInt) - > {
                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                });
                dialog.setNegativeButton("Cancel", (paramDialogInterface, paramInt) - > {});
                dialog.show();
            }
            buildGoogleApiClient();
        } else {
            Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        rv_driver_truck.setLayoutManager(linearLayoutManager);
        rv_driver_truck.setItemAnimator(new DefaultItemAnimator());
        getDriverList();

        book.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBookRequest();
            }
        });
        mResultReceiver = new AddressResultReceiver(new Handler());

        return view;
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;



        mMap.setOnCameraChangeListener(cameraPosition - > {
            Log.d("@@Camera postion change" + "", cameraPosition + "");
            mCenterLatLong = cameraPosition.target;

            mMap.clear();
            try {
                Location mLocation = new Location("");
                mLocation.setLatitude(mCenterLatLong.latitude);
                mLocation.setLongitude(mCenterLatLong.longitude);

                currentLat = String.valueOf(mCenterLatLong.latitude);
                currentLong = String.valueOf(mCenterLatLong.longitude);

                startIntentService(mLocation);
                mLocationMarkerText.setText(getCompleteAddressString(mLocation.getLatitude(), mLocation.getLongitude()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
        if (mLastLocation != null) {
            changeMap(mLastLocation);

            Log.d(TAG, "ON connected");

        } else
            try {
                LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        try {
            LocationRequest mLocationRequest = new LocationRequest();
            mLocationRequest.setInterval(10000);
            mLocationRequest.setFastestInterval(5000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        try {
            if (location != null)
                changeMap(location);
            LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
    protected synchronized void buildGoogleApiClient() {



        mGoogleApiClient = new GoogleApiClient.Builder(getContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

    }
    @Override
    public void onStart() {
        super.onStart();
        try {
            mGoogleApiClient.connect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        try {

        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {}
            return false;
        }
        return true;
    }


    private void changeMap(Location location) {

        Log.d(TAG, "Reaching map" + mMap);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        if (mMap != null) {
            mMap.getUiSettings().setZoomControlsEnabled(false);
            LatLng latLong;
            latLong = new LatLng(location.getLatitude(), location.getLongitude());
            CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(latLong).zoom(10 f).tilt(50).build();
            mMap.setMyLocationEnabled(true);
            /*    mMap.getUiSettings().setMyLocationButtonEnabled(true);*/
            mMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
            //  mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
            getCompleteAddressString(location.getLatitude(), location.getLongitude());
            mLocationMarkerText.setText(getCompleteAddressString(location.getLatitude(), location.getLongitude()));
            startIntentService(location);
        } else {
            Toast.makeText(getContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                .show();
        }

    }

    @Override
    public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
        String str = (String) parent.getItemAtPosition(position);
        Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
        LatLng lastLocation = source;
        edtDropLocation.setText(str);
        dropLocation = str;


        Geocoder coder = new Geocoder(getContext());
        try {
            ArrayList < Address > adresses = (ArrayList < Address > ) coder.getFromLocationName(str, 50);
            for (Address add: adresses) {

                double longitude = add.getLongitude();
                double latitude = add.getLatitude();

                dropLat = String.valueOf(latitude);
                dropLong = String.valueOf(longitude);

                destination = new LatLng(latitude, longitude);

                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                mMap.clear();
                markerOptions.title(str);

                markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.droppoint));
                mMap.animateCamera(CameraUpdateFactory.newLatLng(destination));
                mMap.addMarker(markerOptions);
                getDriverList();
                lytBottomView.setVisibility(View.VISIBLE);
                driverListAdapter = new DriverListAdapter(getActivity(), driverDetailsList, this);
                rv_driver_truck.setAdapter(driverListAdapter);

                /*   new GetPathFromLocation(lastLocation, destination, new DirectionPointListener() {
                       @Override
                       public void onPath(PolylineOptions polyLine) {
                           mMap.addPolyline(polyLine);
                           lytBottomView.setVisibility(View.VISIBLE);

                       }
                   }).execute();*/


            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public DriverDetail driverDetail(DriverDetail driverDetail1) {
        driverDetail = driverDetail1;
        driverId = driverDetail1.getId();
        truckRent = driverDetail1.getVehicleRent();
        // Log.e("@@DriverId", truckRent);


        return driverDetail;
    }

    class AddressResultReceiver extends ResultReceiver {
        public AddressResultReceiver(Handler handler) {
            super(handler);
        }
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);
            mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);
            mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
            mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);
            displayAddressOutput();

            if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {

            }
        }

    }
    protected void displayAddressOutput() {
        try {
            if (mAreaOutput != null)
                mLocationAddress.setText(mAddressOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void startIntentService(Location mLocation) {

        Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
        intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);
        intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);
        getActivity().startService(intent);
    }



    private void openAutocompleteActivity() {
        try {

            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                .build(getActivity());
            startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
        } catch (GooglePlayServicesRepairableException e) {

            GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(),
                0 /* requestCode */ ).show();
        } catch (GooglePlayServicesNotAvailableException e) {

            String message = "Google Play Services is not available: " +
                GoogleApiAvailability.getInstance().getErrorString(e.errorCode);

            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
            if (resultCode == RESULT_OK) {

                Place place = PlaceAutocomplete.getPlace(mContext, data);
                LatLng latLong;
                latLong = place.getLatLng();
                CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLong).zoom(19 f).tilt(70).build();

                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mMap.setMyLocationEnabled(true);
                mMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));
            }

        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(mContext, data);
        } else if (resultCode == RESULT_CANCELED) {

        }
    }
    @SuppressLint("LongLogTag")
    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
        try {
            List < Address > addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                }
                strAdd = strReturnedAddress.toString();
                currentLocation = strAdd;
                Log.e("My Current loction address", strReturnedAddress.toString());
            } else {
                Log.w("My Current loction address", "No Address returned!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.w("My Current loction address", "Canont get Address!");
        }
        return strAdd;
    }

    private void getDriverList() {


        ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);

        Call < OnlineDriverList > call = apiInterface.getDriverList();
        call.enqueue(new Callback < OnlineDriverList > () {
            @Override
            public void onResponse(@NonNull Call < OnlineDriverList > call, Response < OnlineDriverList > response) {
                // refreshLayout.setRefreshing(false);
                if (response.isSuccessful()) {
                    OnlineDriverList onlineDriverList = response.body();
                    if (onlineDriverList.getDriverDetails().size() == 0) {
                        Toast.makeText(getContext(), "No Driver is Available at current Time ", Toast.LENGTH_SHORT).show();
                    } else {

                        driverDetailsList = onlineDriverList.getDriverDetails();
                        TruckBo.getInstance().setDriverArrayList(driverDetailsList);
                        //  driverListAdapter.setData(driverDetailsList);
                        // refreshLayout.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onFailure(Call < OnlineDriverList > call, Throwable t) {
                //refreshLayout.setRefreshing(false);
                Log.d("Error", t.getLocalizedMessage());
            }
        });
    }
    public void sendBookRequest() {

        ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
        Call < UserRegistration > call = apiInterface.booking(driverId, userId, truckRent, currentLocation, dropLocation,
            currentLat, currentLong, dropLat, dropLong, token, "", ""

        );
        call.enqueue(new Callback < UserRegistration > () {
            @Override
            public void onResponse(Call < UserRegistration > call, Response < UserRegistration > response) {

                if (response.isSuccessful()) {
                    Toast.makeText(getContext(), "Wait For Respond From Driver Side", Toast.LENGTH_SHORT).show();
                    lytBottomView.setVisibility(View.GONE);

                } else {}
            }

            @Override
            public void onFailure(Call < UserRegistration > call, Throwable t) {
                Log.e("Error", t.getLocalizedMessage());

            }
        });
    }
}

Я получаю нулевое значение здесь:

   protected synchronized void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder(getContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

      }

В первый раз, когда оно не идет в текущее местоположение, и я получаю нулевое значение googleapiclient, и При перемещении маркера я получаю адрес при запуске. Я не получаю текущее местоположение.

...