如何在填充arraylist后执行asynctask

时间:2015-03-05 22:33:37

标签: java android http arraylist android-asynctask

我试图查看asynctask是否可以从纬度和经度获取参数。我需要知道如何在arraylist填充后执行它。我目前收到的错误是:

" java.lang.RuntimeException:无法实例化活动ComponentInfo {trak.com.trak / trak.com.trak.MapsActivity}:java.lang.IndexOutOfBoundsException:索引0无效,大小为0"

我相信这个错误正在发生,因为asynctask比填充arraylist的方法运行得更快。

这是我的代码:

public class MapsActivity extends FragmentActivity  implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener{

ArrayList<Double> list = new ArrayList<Double>();
Marker marker;
Marker markerparadas;
private boolean mRequestingLocationUpdates = true;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
int ruta = 37;
int ID_camion;
private Location mLastLocation ;
//variables globales de latitud y longitud
double latitude;
double longitude;
public double externallatitude;
public double externallongitude;
private static String url = "URL";
// LogCat tag
private static final String TAG = MapsActivity.class.getSimpleName();

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

//private Location mLastLocation;
private Location mCurrentLocation;

// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;

private LocationRequest mLocationRequest;

// Location updates intervals in sec
private static int UPDATE_INTERVAL = 5000; // 10 sec
private static int FASTEST_INTERVAL = 1000; // 5 sec
private static int DISPLACEMENT = 1; // 10 meters

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

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

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();
    // First we need to check availability of play services
    if (checkPlayServices()) {

        // Building the GoogleApi client
        buildGoogleApiClient();

        createLocationRequest();
    }
}

@Override
protected void onResume() {
    super.onResume();
    setUpMapIfNeeded();

    mGoogleApiClient.connect();
    if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {//eliminando updates y desconectando
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }

}

private void setUpMapIfNeeded() {
    // hacer una pruba de null para saber si mMap esta activo
    if (mMap == null) {
        // obtener el mapa por SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // verificar si el mapa esta activo
        if (mMap != null) {
            setUpMap();
        }
    }
}


private void setUpMap() {
}

@Override
public void onConnected(Bundle bundle) {
    Log.i(TAG, "Servicios de localización activados");
    setUpParadas();
    Get1stLatLong();
    gs();
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(17);
    mMap.animateCamera(zoom);
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mRequestingLocationUpdates) { //Se llama cuando no hay una ultima localización disponible
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    mLastLocation= LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

}

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}
public void Get1stLatLong(){
    mLastLocation= LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);
    latitude = mLastLocation.getLatitude();
    list.add(latitude);
    longitude =  mLastLocation.getLongitude();
    list.add(longitude);
}
public void GetLatLong(){
    mLastLocation= LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);
    double latitude1 = mLastLocation.getLatitude();
    list.set(0, latitude1);
    double longitude1 =  mLastLocation.getLongitude();
    list.set(1,longitude1);


}
public void removeSingleMarker() {
    if(marker != null) {
        marker.remove();
        marker = null;
    }
}
@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Servicios de localización suspendidos. Favor de reconectar.");
}


myTask mtask = new myTask();


//Metodo para cuando la localización cambia
@Override
public void onLocationChanged(Location location) {
    removeSingleMarker();
    GetLatLong();
    handleNewLocation(location);
    mCurrentLocation = location;
    setextlat();
    setextlon();
    mtask.execute();

}


private void gs (){
    double latitude1 = list.get(0);
    double longitude1 = list.get(1);
    LatLng latLng1 = new LatLng(latitude1, longitude1);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng1));
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

    Log.i(TAG, "Servicio de localización falló con el siguiente codigo: " + connectionResult.getErrorCode());
}
private void handleNewLocation(Location location) {
    if (mLastLocation != null) {

        LatLng latLng = new LatLng(list.get(0), list.get(1));
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


        //añadir un nuevo marker con la posición de la variable latLng


        MarkerOptions camion = new MarkerOptions()
                .position(latLng)
                .title("Camión")
                .snippet("ruta " + ruta)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.busnew));


        marker = mMap.addMarker(camion);
        if (marker == null) {
            mMap.addMarker(camion);
        } else {
            camion.position(latLng);

        }
    }
}
private void setUpParadas(){
LatLng latLng = new LatLng(20.5657523,-100.4147976);
MarkerOptions parada = new MarkerOptions()
        .position(latLng)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada);
LatLng latLng1 = new LatLng(20.5517581,-100.4090568);
MarkerOptions parada1 = new MarkerOptions()
        .position(latLng1)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada1);
LatLng latLng2 = new LatLng(20.5517459,-100.4090175);
MarkerOptions parada2 = new MarkerOptions()
        .position(latLng2)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada2);
LatLng latLng3 = new LatLng(20.5467857,-100.4057283);
MarkerOptions parada3 = new MarkerOptions()
        .position(latLng3)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada3);
LatLng latLng4 = new LatLng(20.5431296,-100.4038233);
MarkerOptions parada4 = new MarkerOptions()
        .position(latLng4)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada4);
LatLng latLng5 = new LatLng(20.5383595,-100.3978791);
MarkerOptions parada5 = new MarkerOptions()
        .position(latLng5)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada5);
LatLng latLng6 = new LatLng(20.5327648,-100.4013547);
MarkerOptions parada6 = new MarkerOptions()
        .position(latLng6)
        .title("Parada")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.busstop));
markerparadas = mMap.addMarker(parada6);
}

public void setextlat()
{
    this.externallatitude = list.get(0);
}

public void setextlon(){
    this.externallongitude = list.get(1);
}

public class myTask extends AsyncTask<String,String, Void> {

    double lat=list.get(0);
    double lon=list.get(1);

    /*@Override
    protected void onPreExecute() {
        String result = Double.toString(lat);
        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_SHORT).show();
    }*/
    @Override
    protected Void doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("url");

        try {
            // Add the data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(lat)));
            nameValuePairs.add(new BasicNameValuePair("longitude", Double.toString(lon)));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        return null;
    }
}
}

编辑:完整logcat = http://pastebin.com/saiuLUcj

1 个答案:

答案 0 :(得分:0)

您在myTask mtask = new myTask();中创建了MainActivity,因此您可以在mtask构造函数中调用MainActivity的构造函数。但是在myTask你有这个:

double lat=list.get(0);
double lon=list.get(1); 

创建Activity列表时为空。设置成员时无法呼叫myTask()。在填写清单之后和首次使用之前,您必须执行此操作。它可以在onLocationChanged()方法