我现在有一个例外

时间:2018-11-12 10:33:07

标签: android gps location

这是我的实时位置活动更新代码。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {

private GoogleMap mMap;
private Marker currentLocationMaker;
private LatLng currentLocationLatLong;
private DatabaseReference mDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    startGettingLocations();
    mDatabase = FirebaseDatabase.getInstance().getReference();
    getMarkers();
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in Sydney and move the camera
    LatLng recife = new LatLng(-8.065638, -34.891130);
    mMap.addMarker(new MarkerOptions().position(recife).title("Related Searches"));

    CameraPosition cameraPosition = new CameraPosition.Builder().zoom(15).target(recife).build();


    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

@Override
public void onLocationChanged(Location location) {

    if (currentLocationMaker != null) {
        currentLocationMaker.remove();
    }
    //Add marker
    currentLocationLatLong = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(currentLocationLatLong);
    markerOptions.title("My Current Location");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    currentLocationMaker = mMap.addMarker(markerOptions);

    //Move to new location
    CameraPosition cameraPosition = new CameraPosition.Builder().zoom(15).target(currentLocationLatLong).build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    LocationData locationData = new LocationData(location.getLatitude(), location.getLongitude());
    mDatabase.child("location").child(String.valueOf(new Date().getTime())).setValue(locationData);

    Toast.makeText(this, "Updated Location", Toast.LENGTH_SHORT).show();
    getMarkers();

}
private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
    ArrayList result = new ArrayList();

    for (String perm : wanted) {
        if (!hasPermission(perm)) {
            result.add(perm);
        }
    }

    return result;
}

private boolean hasPermission(String permission) {
    if (canAskPermission()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
        }
    }
    return true;
}

private boolean canAskPermission() {
    return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
    alertDialog.setTitle("GPS disabled!");
    alertDialog.setMessage("Enable GPS?");
    alertDialog.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });

    alertDialog.setNegativeButton("Not", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}

private void startGettingLocations() {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean isNetwork = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    boolean canGetLocation = true;
    int ALL_PERMISSIONS_RESULT = 101;
    long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;// Distance in meters
    long MIN_TIME_BW_UPDATES = 1000 * 10;// Time in milliseconds

    ArrayList<String> permissions = new ArrayList<>();
    ArrayList<String> permissionsToRequest;

    permissions.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    permissions.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    permissionsToRequest = findUnAskedPermissions(permissions);

    //Check if GPS and Network are on, if not asks the user to turn on
    if (!isGPS && !isNetwork) {
        showSettingsAlert();
    } else {
        // check permissions

        // check permissions for later versions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissionsToRequest.size() > 0) {
                requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
                        ALL_PERMISSIONS_RESULT);
                canGetLocation = false;
            }
        }
    }

    //Checks if FINE LOCATION and COARSE Location were granted
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

        Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
        return;
    }

    //Starts requesting location updates
    if (canGetLocation) {
        if (isGPS) {
            lm.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

        } else if (isNetwork) {
            // from Network Provider

            lm.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

        }
    } else {
        Toast.makeText(this, "Unable to get location", Toast.LENGTH_SHORT).show();
    }
}


private void getMarkers(){

    mDatabase.child("location").addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    //Get map of users in datasnapshot
                    if (dataSnapshot.getValue() != null)
                        getAllLocations((Map<String,Object>) dataSnapshot.getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    //handle databaseError
                }
            });
}

private void getAllLocations(Map<String,Object> locations) {




    for (Map.Entry<String, Object> entry : locations.entrySet()){

        Date newDate = new Date(Long.valueOf(entry.getKey()));
        Map singleLocation = (Map) entry.getValue();
        LatLng latLng = new LatLng((double) singleLocation.get("latitude"), (double) singleLocation.get("longitude"));
        addGreenMarker(newDate, latLng);

    }


}

private void addGreenMarker(Date newDate, LatLng latLng) {
    SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title(dt.format(newDate));
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
    mMap.addMarker(markerOptions);
}


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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

}

这是我的Logcat Stack跟踪

Process: com.softtech.aqeel.childsequrity, PID: 3739
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
    at com.softtech.aqeel.childsequrity.MapsActivity.getAllLocations(MapsActivity.java:247)
    at com.softtech.aqeel.childsequrity.MapsActivity.access$000(MapsActivity.java:39)
    at com.softtech.aqeel.childsequrity.MapsActivity$3.onDataChange(MapsActivity.java:228)
    at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.4:183)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

我正在尝试为我的项目跟踪Android设备的实时位置,但此时它给了我这些例外。我的应用程序启动,当我打开“地图活动”时,地图会向我显示一点,然后应用程序自动停止。

4 个答案:

答案 0 :(得分:0)

使用以下代码创建对象并进行投射。

#!/bin/bash
file="$1"
THRESHOLD=120
while [ 1 ] ;
do
    #Get the last accesstime as unixtime stamp
    last_access_time=$(stat -c %X $file)

    #Current time as unixTimeStamp
    current_time=$(date +%s)

    #difference
    diff=`echo "$currnet_time - $last_access_time" | bc`

    # Threshold here is 120 seconds
    if [ $diff < $THRESHOLD ]; 
    then
       echo "Do something "
    fi

    sleep $THRESHOLD;
done

答案 1 :(得分:0)

使用doubleValue()中的Long

更改

LatLng latLng = new LatLng((Double) singleLocation.get("latitude"), (Double) singleLocation.get("longitude"));

LatLng latLng = new LatLng((Long) singleLocation.get("latitude").doubleValue(), (Long) singleLocation.get("longitude").doubleValue());

答案 2 :(得分:0)

从singleLocation获取经度和纬度,并通过此way进行转换,然后插入LatLng。

答案 3 :(得分:0)

您必须首先将Object值转换为String。 像下面一样

Map singleLocation = (Map) entry.getValue();
String latitude = String.valueOf(singleLocation.get("latitude"));
String longitude = String.valueOf(singleLocation.get("longitude"));

Double doublelat = Double.parseDouble(latitude);
Double doublelong = Double.parseDouble(longitude);

LatLng latlng = new LatLng(doublelat, doublelong);

您不会有任何例外。