android - 我正在创建一个类似Uber的应用程序,但它突然崩溃,并出现预期的BEGIN_ARRAY错误,但在第1行第1列路径$ STRING

标签 android arrays list compiler-errors runtime-error

我正在尝试创建类似Uber的应用,并且正在为Driver解析客户的地理位置和UID。我使用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

这是我的数据库结构Database Structure Of App

最佳答案

这是android studio中的错误。但是,您可以通过复制在不同 Activity 中拥有的代码以及您自己创建的其他文件来恢复项目。不要尝试复制整个项目,因为那样会使应用程序再次崩溃。在某些自动生成的文件中,Android Studio似乎输入了错误的内容。因此,仅复制您创建或更改过的文件。我会尝试将错误报告提交给android studio以解决错误。
无论如何,如果有帮助,请告诉我。
谢谢...

关于android - 我正在创建一个类似Uber的应用程序,但它突然崩溃,并出现预期的BEGIN_ARRAY错误,但在第1行第1列路径$ STRING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50342814/

相关文章:

android - 发布有排行榜但没有成就的 Android 应用程序

android - 如何在表中创建外键?

java - 在初始化类成员之前调用方法

javascript - 不能强制对象键为整数

javascript - JS : How to combine Object from two different arrays into one Array/Object

python - 如何将对象类附加到列表?

android - 如果已经显示了一个 Toast,如何避免 Toast

python - 如何在 Python 中将图像数组转换为二维数组

Android:保存int列表的最有效方法

python - 列表理解与循环——我不明白什么?