Я пытаюсь создать приложение, такое как Uber, и анализирую геолокацию и UID клиента для Driver.Я использовал массив Map для получения customerUID и массив List для получения широты и долготы соответственно.Но когда я попытался скомпилировать и запустить, он показал ошибку:
Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $.
Раньше это работало очень хорошо, но теперь я даже не могу отменить изменения, которые я сделал, потому что я закрыл проект и перезапустил его, думаявозможно, это решило бы проблему, но это привело к тому, что я не смог отменить ни одного шага.
Ниже приведен код моего проекта, который может помочь вам в решении этой ошибки.
package com.matt.dumate;
import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Welcome extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, RoutingListener{
SupportMapFragment mapFragment;
private Button btnBooking;
private Location lastLocation;
private GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener;
private LocationRequest locationRequest;
private LocationListener locationListener;
private LocationManager locationManager;
private Marker marker, driverMarker;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private final int RequestCode = 10;
private final int ResourceCode = 11;
private DatabaseReference userLastLocation, customersUnderServiceRef, userRequest, driversOnDuty,workingDrivers, driverRef1, driverWorkingRef ;
GeoFire location, request, onDuty, customersUnderService;
private Boolean clicked = false;
private String driverID = "";
private ValueEventListener driverListener;
private GeoQuery geoQuery;
private String myId = "";
private Double driverLat, driverLng;
@Override
protected void onCreate(Bundle savedInstanceState)
{
checkLocationPermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
userLastLocation = FirebaseDatabase.getInstance().getReference("User LastLocation");
location = new GeoFire(userLastLocation);
setupLocation();
userRequest = FirebaseDatabase.getInstance().getReference("User Request");
request = new GeoFire(userRequest);
driversOnDuty = FirebaseDatabase.getInstance().getReference("DriversOnDuty");
onDuty = new GeoFire(driversOnDuty);
driverRef1 = FirebaseDatabase.getInstance().getReference().child("Driver").child(driverID);
driverWorkingRef = FirebaseDatabase.getInstance().getReference().child("DriversWorking");
customersUnderServiceRef = FirebaseDatabase.getInstance().getReference().child("CustomersUnderService");
customersUnderService = new GeoFire(customersUnderServiceRef);
workingDrivers = FirebaseDatabase.getInstance().getReference().child("DriversWorking").child(driverID);
}
@Override
public void onMapReady(GoogleMap googleMap)
{
myId = FirebaseAuth.getInstance().getCurrentUser().getUid();
setupUiViews();
mMap = googleMap;
displayLocation();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
switch (requestCode) {
case RequestCode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
break;
}
}
@Override
public void onConnected(@Nullable Bundle bundle)
{
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
locationRequest = LocationRequest
.create()
.setInterval(1000)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
startLocationUpdates();
displayLocation();
}else {
checkLocationPermission();
}
}
@Override
public void onConnectionSuspended(int i)
{
googleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
}
@Override
public void onLocationChanged(Location location)
{
lastLocation = location;
displayLocation2();
}
public void checkLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
}
} else {
Toast.makeText(this, "Location Permissions Granted", Toast.LENGTH_SHORT).show();
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private void setupUiViews()
{
btnBooking = findViewById(R.id.bookingButton);
btnBooking.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (clicked == false) {
startLocationUpdates();
displayLocation2();
getNearestDriver();
Toast.makeText(Welcome.this, "Getting Cab", Toast.LENGTH_SHORT).show();
btnBooking.setText("Getting Your Cab..");
clicked = true;
} else
{
disconnection();
try{
driverRef1.child("customerRideId").removeValue();
}catch (Exception a){
return;
}
stopLocationUpdates();
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Customer Request");
GeoFire geoFire1 = new GeoFire(databaseReference1);
geoFire1.removeLocation(userId);
Toast.makeText(Welcome.this, "Canceling Cab", Toast.LENGTH_SHORT).show();
btnBooking.setText("Get Cab");
if(driverMarker!=null){
driverMarker.remove();
}
clicked = false;
}
}
});
}
private void displayLocation()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null ){
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
location.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
{
@Override
public void onComplete(String key, DatabaseError error) {
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
}else{
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
}
}
});
}else{
Log.d("Error", "Cannot Get Your Location");
}
}
private void displayLocation2()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null ){
if(clicked == true){
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
request.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
{
@Override
public void onComplete(String key, DatabaseError error) {
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
}else{
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You"));
}
}
});
}
}else{
Log.d("Error", "Cannot Get Your Location");
}
}
private void setupLocation()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
}
}else{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
}
}
}
private void createLocationRequest()
{
locationRequest = LocationRequest.create()
.setInterval(1500)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(0);
}
private boolean checkPlayServices()
{
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, this, ResourceCode).show();
else {
Toast.makeText(this, "This Device Is Not Supported", Toast.LENGTH_SHORT).show();
finish();
}return false;
}
return true;
}
private void stopLocationUpdates()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void startLocationUpdates()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
private int radius = 1;
private Boolean driverFound = false;
private void getNearestDriver()
{
geoQuery = location.queryAtLocation(new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()), radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
@Override
public void onKeyEntered(String key, GeoLocation location) {
String driverId = key;
if(!driverFound){
driverFound = true;
driverID = key;
DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference().child("Driver").child(driverId);
String customerId = FirebaseAuth.getInstance().getCurrentUser().getUid();
HashMap map = new HashMap();
map.put("customerRideId", customerId);
driverRef.updateChildren(map);
driverID = key;
btnBooking.setText("Getting Driver Location");
customersUnderService.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
getDriverLocation();
}
}
@Override
public void onKeyExited(String key) {
disconnection();
}
@Override
public void onKeyMoved(String key, GeoLocation location) { }
@Override
public void onGeoQueryReady() {
if(!driverFound){
radius++;
getNearestDriver();
}
}
@Override
public void onGeoQueryError(DatabaseError error) {
disconnection();
Toast.makeText(Welcome.this, "GeoQuery Error", Toast.LENGTH_SHORT);
}
});
}
private void getDriverLocation()
{
driverWorkingRef = driverWorkingRef.child(driverID).child("l");
driverListener = driverWorkingRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLng = 0;
btnBooking.setText("Driver Found");
if (map.get(0) != null)
{
locationLat = Double.parseDouble(map.get(0).toString());
driverLat = locationLat;
}
if (map.get(1) != null)
{
locationLng = Double.parseDouble(map.get(1).toString());
driverLng = locationLng;
}
LatLng driverLatLng = new LatLng(locationLat, locationLng);
if (driverMarker != null) {
driverMarker.remove();
}
driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.carmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 15.0f));
Location myLoc = new Location("");
Location driverLoc = new Location("");
myLoc.setLatitude(lastLocation.getLatitude());
myLoc.setLongitude(lastLocation.getLongitude());
driverLoc.setLatitude(locationLat);
driverLoc.setLongitude(locationLng);
float distance = myLoc.distanceTo(driverLoc);
;
if (distance<100){
btnBooking.setText("Driver Reached");
}else{
btnBooking.setText("Driver at " + distance);
}
}getDriverLocation();
}
@Override
public void onCancelled(DatabaseError databaseError) {
disconnection();
}
});
}
@Override
public void onRoutingFailure(RouteException e)
{}
@Override
public void onRoutingStart()
{}
@Override
public void onRoutingSuccess(ArrayList<Route> arrayList, int i)
{}
@Override
public void onRoutingCancelled()
{}
private void disconnection(){
try {
customersUnderService.removeLocation(myId);
}catch(Exception b){ }
try {
driverWorkingRef.removeEventListener(driverListener);
}catch(Exception c){
}
try {
onDuty.setLocation(driverID,new GeoLocation(driverLat, driverLng));
}catch(Exception d){ }
try {
geoQuery.removeAllListeners();
}catch(Exception f){ }
try {
request.removeLocation(myId);
}catch(Exception g){ }
try
{
driverRef1.child("customerRideId").removeValue();
} catch(Exception h) { }
try
{
onDuty.setLocation(driverID,new GeoLocation(driverLat, driverLng));
} catch(Exception h) { }
driverFound = false;
if (driverMarker != null){
driverMarker.remove();
}
btnBooking.setText("Get Cab");
clicked = false;
}
@Override
protected void onStop()
{
super.onStop();
//disconnection();
}
private void getDirection(LatLng latLng)
{
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), latLng)
.build();
routing.execute();
}
@Override
protected void onPause() {
super.onPause();
}
}
Коды ошибок:
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
at com.google.gson.Gson.fromJson(Gson.java:899)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.android.build.gradle.internal.pipeline.SubStream.loadSubStreams(SubStream.java:129)
at com.android.build.gradle.internal.pipeline.IntermediateFolderUtils.<init>(IntermediateFolderUtils.java:66)
at com.android.build.gradle.internal.pipeline.IntermediateStream.init(IntermediateStream.java:191)
at com.android.build.gradle.internal.pipeline.IntermediateStream.asOutput(IntermediateStream.java:135)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:228)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:217)
at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:212)
at sun.reflect.GeneratedMethodAccessor568.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
... 107 more
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.Gson.fromJson(Gson.java:887)
... 130 more
Это моя структура базы данных Структура базы данных приложения