Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ArrayList元素突然变为null_Java_Android_Google Maps - Fatal编程技术网

Java ArrayList元素突然变为null

Java ArrayList元素突然变为null,java,android,google-maps,Java,Android,Google Maps,我目前正试图找到离我当前位置最近的商店。我实现了不同的方法(例如:排序),但没有用,它只返回null。我花了很长时间才找出问题所在。每当我使用float distance=currenpos.distanceTo(位置A)它产生0.0。进一步检查后,我发现我的位置a返回空值。我尝试访问了marker.get(0)。在2个for循环之前和之后的location,而在2个for循环之前的location只返回一个值 @Override protected void onCreate(Bundle

我目前正试图找到离我当前位置最近的商店。我实现了不同的方法(例如:排序),但没有用,它只返回null。我花了很长时间才找出问题所在。每当我使用
float distance=currenpos.distanceTo(位置A)它产生
0.0
。进一步检查后,我发现我的
位置a
返回空值。我尝试访问了marker.get(0)。在2个for循环之前和之后的location
,而在2个for循环之前的location只返回一个值

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    marker = new ArrayList();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

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

    try {
        jSonArray = (String) getIntent().getExtras().get("jsonArray");
        jsonArray = new JSONArray(jSonArray);
        for (int i = 0; i < jsonArray.length(); i++) {
            branch = new Markers();
            Float lat;
            Float lon;
            lat = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
            lon = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
            branch.location = new Location("");
            branch.location.setLatitude(lat);
            branch.location.setLongitude(lon);
            marker.add(branch);
        }
        *marker.get(0).location is still accessible here*
        for (int i = 0; i < marker.size(); i++) {
            results[i] = distance(currPos.getLatitude(), currPos.getLongitude(), marker.get(i).location.getLatitude(), marker.get(i).location.getLongitude());
        }
        for (int i = 0; i < results.length; i++) {
            if (results[i] < results[i + 1]) {
                temp = marker.get(i).location;
            }
        }
    *marker.get(0).location returns null here*
    } catch (Exception ex) {
    Log.d("Error", ex.toString());
}
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
marker=newarraylist();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
checkLocationPermission();
}
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
试一试{
jSonArray=(字符串)getIntent().getExtras().get(“jSonArray”);
jsonArray=新jsonArray(jsonArray);
for(int i=0;i
以下是整个活动:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {
private static List<Markers> marker;
private static Markers branch;
private static Location temp;
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private static Location currPos;
private JSONArray jsonArray;
private double[] results;
private String jSonArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
    marker = new ArrayList();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

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

    try {
        jSonArray = (String) getIntent().getExtras().get("jsonArray");
        jsonArray = new JSONArray(jSonArray);
        for (int i = 0; i < jsonArray.length(); i++) {
            branch = new Markers();
            Float lat;
            Float lon;
            lat = Float.parseFloat(jsonArray.getJSONObject(i).getString("latitude"));
            lon = Float.parseFloat(jsonArray.getJSONObject(i).getString("longitude"));
            branch.location = new Location("");
            branch.location.setLatitude(lat);
            branch.location.setLongitude(lon);
            marker.add(branch);
        }
        for (int i = 0; i < marker.size(); i++) {
            results[i] = distance(currPos.getLatitude(), currPos.getLongitude(), marker.get(i).location.getLatitude(), marker.get(i).location.getLongitude());
        }
        for (int i = 0; i < results.length; i++) {
            if (results[i] < results[i + 1]) {
                temp = marker.get(i).location;
            }
        }
    } catch (Exception ex) {
    Log.d("Error", ex.toString());
}
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}

private class Markers {
    public Location location;
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    currPos = location;
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Location");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean 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},
                    MY_PERMISSIONS_REQUEST_LOCATION);


        } else {

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

    }
}
public double distance(double lata, double longa, double latb, double longb) {
    double d2r = Math.PI / 180;
    double dlong = (longa - longb) * d2r;
    double dlat = (lata - latb) * d2r;
    double a = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(latb * d2r)
            * Math.cos(lata * d2r) * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 6367 * c;
    return d;

}
公共类MapsActivity扩展了FragmentActivity在MapreadyCallback上的实现,
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
位置侦听器{
私有静态列表标记;
私有静态标记分支;
专用静态位置温度;
私有谷歌地图;
GoogleapClient MGoogleapClient;
位置mLastLocation;
标记器mCurrLocationMarker;
位置请求mLocationRequest;
专用静态定位系统;
私人JSONArray JSONArray;
私人双[]结果;
私有字符串jSonArray;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
marker=newarraylist();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
if(android.os.Build.VERSION.SDK\u INT>=Build.VERSION\u CODES.M){
checkLocationPermission();
}
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
试一试{
jSonArray=(字符串)getIntent().getExtras().get(“jSonArray”);
jsonArray=新jsonArray(jsonArray);
for(int i=0;i=Build.VERSION\u CODES.M){
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
}
否则{
buildGoogleAppClient();
mMap.setMyLocationEnabled(真);
}
}
私有类标记{
公共场所;
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@凌驾
未连接的公共空间(捆绑包){
mlLocationRequest=新位置请求();
mlLocationRequest.setInterval(1000);
mlLocationRequest.setFastTestInterval(1000);
mLocationRequest.setPriority(位置请求、优先级、平衡、功率、精度);
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.访问(位置)
==PackageManager.权限(已授予){
LocationServices.FusedLocationApi.RequestLocationUpdate(mgoogleapClient、mlLocationRequest、this);
}
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
已更改位置上的公共无效(位置){
mLastLocation=位置;
if(mCurrLocationMarker!=null){
mCurrLocationM