1

我有两个活动LoginActivityMyMapActivity。问题是当我第二次尝试打开MyMapActivity(登录-> MyMapActivity(第一次活动有效)-> 注销-> 登录)时,我收到以下错误:

08-10 06:55:27.663: E/AndroidRuntime(3630): FATAL EXCEPTION: main
08-10 06:55:27.663: E/AndroidRuntime(3630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pac/com.example.pac.MyMapActivity}:    java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2247)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.ActivityThread.access$700(ActivityThread.java:152)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.os.Looper.loop(Looper.java:137)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.ActivityThread.main(ActivityThread.java:5328)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at java.lang.reflect.Method.invokeNative(Native Method)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at java.lang.reflect.Method.invoke(Method.java:511)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at dalvik.system.NativeStart.main(Native Method)
08-10 06:55:27.663: E/AndroidRuntime(3630): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
08-10 06:55:27.663: E/AndroidRuntime(3630):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at java.util.ArrayList.get(ArrayList.java:304)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at com.example.pac.MyMapActivity.onCreate(MyMapActivity.java:232)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.Activity.performCreate(Activity.java:5250)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
08-10 06:55:27.663: E/AndroidRuntime(3630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-10 06:55:27.663: E/AndroidRuntime(3630):     ... 11 more

MyMapActivity 中的第 232 行:

fantasma1 = myMap.addMarker(newMarkerOptions().position(rlevel.get(v)).icon(BitmapDescriptorFactory.fromResource(R.drawable .marker_white)));

MyMapActivity 类:

public class MyMapActivity extends Activity implements AnimationLayout.Listener {
public final static String TAG = "Demo";




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    userFunctions = new UserFunctions();

        setContentView(R.layout.game_screen);
        deigma = (TextView)findViewById(R.id.textView1);
        mLayout = (AnimationLayout) findViewById(R.id.animation_layout);
        mLayout.setListener(this);
        /*permissions gia parse twn sintetagmenwn*/

    //telos permission
        if(userFunctions.isUserLoggedIn(getApplicationContext())){
    //logout
    btnLogout = (Button) findViewById(R.id.logout);

    btnLogout.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            userFunctions.logoutUser(getApplicationContext());
           Intent login = new Intent(getApplicationContext(), LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            startActivity(login);





            // Closing dashboard screen
           finish();
        }
    });
    //telos logout


    /*menu
     */


    //telos

    /* user location settings */
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = null;
      //  locationManager.getlastfix().reset();
        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
        criteria.setBearingRequired(true);

        //API level 9 and up
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setBearingAccuracy(Criteria.ACCURACY_LOW);
        criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
        provider = locationManager.getBestProvider(criteria, true);

        deigma.setText(String.valueOf(locationManager));
        location = locationManager.getLastKnownLocation(provider);

        locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
        /*if (location != null) {
            Log.e("PROVIDER SCELTO", provider);
            onLocationChanged(location);
            Log.e("LATITUDE", String.valueOf("da"));
            Log.e("LONGITUDE", String.valueOf("no"));
        }*/
        }
    //telos rithmisewn






/* Helper function. put it in the same page, or in a library */
protected static String downloadFile(String url) {

// to fill-in url content
StringBuilder builder = new StringBuilder();

// local objects declarations
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);

try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
// Failed to download file

}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}



/*telos*/
private final LocationListener locationListener = new LocationListener() 
{ 

@Override 
public void onLocationChanged(Location location) { 
    locationManager.removeUpdates(this);
    float accuracy = (float) location.getAccuracy();
    //deigma.setText(Float.toString(accuracy));
//updateWithNewLocation(location); 
    myLocationMarker.remove();
    lat =  location.getLatitude();
     lng = location.getLongitude();
    thesi_xristi=new LatLng(lat,lng);
   myLocationMarker = myMap.addMarker(new MarkerOptions()
   .position(thesi_xristi)
   .icon(BitmapDescriptorFactory.fromResource(R.drawable.k)));

   for(int vb23=0;vb23<markers_balls.size();vb23++){
       double rla = rballs.get(vb23).latitude;
       double rlo = rballs.get(vb23).longitude;
       if(calculateDistance(lat, lng, rla, rlo,"M")<0.00080){
           markers_balls.get(vb23).remove();
           markers_balls.remove(vb23);  
           score=score+10;
       }
   }

   deigma.setText(score +" ac: "+accuracy);
} 

@Override 
public void onProviderDisabled(String provider) { 
//updateWithNewLocation(null); 

}


@Override 
public void onProviderEnabled(String provider) { 
} 

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

}; 



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my_map, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_legalnotices:
        String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
                getApplicationContext());
        AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MyMapActivity.this);
        LicenseDialog.setTitle("Legal Notices");
        LicenseDialog.setMessage(LicenseInfo);
        LicenseDialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}




@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    if (resultCode == ConnectionResult.SUCCESS){
        //Toast.makeText(getApplicationContext(), 
            //  "isGooglePlayServicesAvailable SUCCESS", 
                //Toast.LENGTH_LONG).show();
    }else{
        GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
    }

}
private double calculateDistance(double lat1, double lon1, double lat2, double lon2, String unit) 
{
      double theta = lon1 - lon2;
      double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
      dist = Math.acos(dist);
      dist = rad2deg(dist);
      dist = dist * 60 * 1.1515;
      if (unit == "K") {
        dist = dist * 1.609344;
      } else if (unit == "M") {
        dist = dist * 0.8684;
        }
      return (dist);
}

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts decimal degrees to radians             :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    private double deg2rad(double deg) 
    {
      return (deg * Math.PI / 180.0);
    }

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function converts radians to decimal degrees             :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    private double rad2deg(double rad)
    {
      return (rad * 180.0 / Math.PI);
    }



    public void onClickContentButton(View v) {
        mLayout.toggleSidebar();
    }

    @Override
    public void onBackPressed() {
        if (mLayout.isOpening()) {
            mLayout.closeSidebar();
        } else {
            finish();
        }
    }

    /* Callback of AnimationLayout.Listener to monitor status of Sidebar */
    @Override
    public void onSidebarOpened() {
        Log.d(TAG, "opened");
    }

    /* Callback of AnimationLayout.Listener to monitor status of Sidebar */
    @Override
    public void onSidebarClosed() {
        Log.d(TAG, "opened");
    }

    /* Callback of AnimationLayout.Listener to monitor status of Sidebar */
    @Override
    public boolean onContentTouchedWhenOpening() {
        // the content area is touched when sidebar opening, close sidebar
        Log.d(TAG, "going to close sidebar");
        mLayout.closeSidebar();
        return true;
    }


    @Override
    public void onDestroy() {
         super.onPause();
          rlevel.clear();
          rlevel2.clear();
          rlevel3.clear();
          rballs.clear();
          markers_balls.clear();

          go.cancel();

        }

}

我正在尝试重新初始化 arraylists onDestroy,但是,我遇到了同样的问题。

4

1 回答 1

0

错误发生原因:java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

arraylist 被重新初始化,但没有在 arraylist 上添加任何值。所以arraylist的大小为零。

您在索引 0 处获取值。

所以它会抛出 indeoutofboundsexception。

请在获取值之前检查 arraylist 大小。

于 2013-08-10T04:53:39.530 回答