ArrayList错误:java.lang.IndexOutOfBoundsException:索引26无效,大小为26

时间:2014-01-05 15:00:36

标签: java android

我有以下活动运行不同的线程。我需要检索一个数组列表,但我得到的只是一个例外。我在谷歌上发现了类似的问题,但我无法使解决方案适应我的代码。

这是我的班级:

public class MapActivity  extends Activity {

    private int userIcon, jewelleryIcon;
    private GoogleMap theMap;
    private LocationManager locMan;
    private Marker userMarker;
    private Marker bijouterie;
    private String latitude;
    private String longitude;
    ArrayList<String> latList;
    ArrayList<String> longList;
    ArrayList<String> latitudeList;
    ArrayList<String> longitudeList;

    // URL to get JSON
    private static String url = "api";
    private static String url2 = "api";

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Portrait only
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        // Check status of Google Play Services
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        // Check Google Play Service Available
        try {
            if (status != ConnectionResult.SUCCESS) {
            }
        } catch (Exception e) {
            Log.e("Error: GooglePlayServiceUtil: ", "" + e);
        }

        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        // Google Maps
        setContentView(R.layout.activity_map);




        // Calling async task to get json
        new GetJson().execute();


    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetJson extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }



        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            JSONArray array = null;
            try {
                array = new JSONArray(jsonStr);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                for (int i = 0; i <array.length(); i++){
                JSONObject jsonObject = array.getJSONObject(i);
                String id = jsonObject.getString("id");
                 System.out.println("id --->" + id);
                 String url = jsonObject.getString("url");
                 System.out.println("url --->" + url);
            //   shopurl.add(url);
                 String created_at = jsonObject.getString("created_at");
                 System.out.println("created_at --->" + created_at);
                 String updated_at = jsonObject.getString("updated_at");
                 System.out.println("updated_at --->" + updated_at);
                 String name = jsonObject.getString("name");    
                 System.out.println("name --->" + name);
                // shopname.add(name);
                 JSONArray photos_urls = jsonObject.getJSONArray("photos_urls");
                 System.out.println("photos_urls --->" + photos_urls);
                 String address_string = jsonObject.getString("address_string");
                 System.out.println("address_string --->" + address_string);
            //   shopaddress.add(address_string);
                 JSONObject booklet = jsonObject.getJSONObject("booklet");
                 String id_booklet = booklet.getString("id");
                 System.out.println("id_booklet --->" + id_booklet);
                 String url_booklet = booklet.getString("url");
                 System.out.println("url_booklet --->" + url_booklet);
                 String created_at_booklet = booklet.getString("created_at");
                 System.out.println("created_at_booklet --->" + created_at_booklet);
                 String updated_at_booklet = booklet.getString("updated_at");
                 System.out.println("updated_at_booklet --->" + updated_at_booklet);
                 String document_url = booklet.getString("document_url");
                 System.out.println("document_url --->" + document_url);
                 String presented = booklet.getString("presented");
                 System.out.println("presented --->" + presented);


                }
                    }
                 catch (JSONException e) {
                    e.printStackTrace();
                }


                 // 2e JSON

              // Creating service handler class instance
                 ServiceHandler sh2 = new ServiceHandler();

                 // Making a request to url and getting response
                 String jsonStr2 = sh2.makeServiceCall(url2, ServiceHandler.GET);

                 Log.d("Response: ", "> " + jsonStr2);

                 JSONArray array2 = null;
                try {
                    array2 = new JSONArray(jsonStr2);
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    ArrayList<String> latitudeList = new ArrayList<String>();
                    ArrayList<String> longitudeList = new ArrayList<String>();


                    for (int j = 0; j <array2.length(); j++){

                    JSONObject jsonObject2 = array2.getJSONObject(j);
                     JSONArray coordinates = jsonObject2.getJSONArray("coordinates");
                    latitude = coordinates.getString(0);
                    Log.d("latitude: ", "> " + latitude);

                    latitudeList.add(latitude);

                    longitude = coordinates.getString(1);
                    Log.d("longitude: ", "> " + longitude);

                    latitudeList.add(latitude);
                    longitudeList.add(longitude);




                     JSONObject shop = jsonObject2.getJSONObject("shop");

                        String logo_thumbnail_url = shop.getString("logo_thumbnail_url");
                        System.out.println("logo_thumbnail_url --->" + logo_thumbnail_url);

                        }
                    latList = latitudeList;
                    longList = longitudeList;

                } catch (JSONException e) {
                    e.printStackTrace();

            } 
            return null;

    }

        @Override 
        protected void onPostExecute(Void result){


            updatePlaces();
        }

    }

    private void updatePlaces(){

        userIcon = R.drawable.blue_point;
        jewelleryIcon = R.drawable.pointeur;

        if(theMap==null){
            //map not instantiated yet
        }
        theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
        if(theMap != null){
            //ok - proceed
        }
        theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        //update location
        locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        double lat = lastLoc.getLatitude();
        double lng = lastLoc.getLongitude();
        LatLng lastLatLng = new LatLng(lat, lng);
        //if(userMarker==null) userMarker.remove();

        userMarker = theMap.addMarker(new MarkerOptions()
        .position(lastLatLng)
        .title("Vous êtes ici")
        .icon(BitmapDescriptorFactory.fromResource(userIcon))
        .snippet("Votre dernière position enregistrée"));

        theMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 7.5f), 4000, null);

        String thelatitude;
        String thelongtitude;

        for (int i = 0; i < latList.size(); i++) {
            thelatitude  = latList.get(i);
            thelongtitude = longList.get(i);

            double latitudeFromString = Double.parseDouble(thelatitude);
            double longitudeFromString = Double.parseDouble(thelongtitude);

            LatLng SHOP = new LatLng(latitudeFromString, longitudeFromString);
            bijouterie = theMap.addMarker(new MarkerOptions()
            .position(SHOP)
            .icon(BitmapDescriptorFactory.fromResource(jewelleryIcon)));


        }

    }


    @Override
    public void onBackPressed() {
        finish();//go back to the previous Activity
        overridePendingTransition(R.anim.backin, R.anim.backout);  
    }
}

日志猫:

01-05 15:52:12.389: W/dalvikvm(15320): threadid=1: thread exiting with uncaught exception (group=0x41d34300)
01-05 15:52:12.389: E/AndroidRuntime(15320): FATAL EXCEPTION: main
01-05 15:52:12.389: E/AndroidRuntime(15320): java.lang.IndexOutOfBoundsException: Invalid index 26, size is 26
01-05 15:52:12.389: E/AndroidRuntime(15320):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at java.util.ArrayList.get(ArrayList.java:304)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at com.begital.votrebijoutier.MapActivity.updatePlaces(MapActivity.java:272)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at com.begital.votrebijoutier.MapActivity.access$6(MapActivity.java:237)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at com.begital.votrebijoutier.MapActivity$GetJson.onPostExecute(MapActivity.java:232)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at com.begital.votrebijoutier.MapActivity$GetJson.onPostExecute(MapActivity.java:1)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at android.os.AsyncTask.finish(AsyncTask.java:631)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at android.os.Looper.loop(Looper.java:137)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at android.app.ActivityThread.main(ActivityThread.java:4745)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at java.lang.reflect.Method.invokeNative(Native Method)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at java.lang.reflect.Method.invoke(Method.java:511)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-05 15:52:12.389: E/AndroidRuntime(15320):    at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:3)

doInBackground方法中,您在纬度列表中添加两次latitude次,而{{1>}只增加{{>>一次<{strong>时间longitude 1}}在经度列表中。

    latitudeList.add(latitude);
    longitude = coordinates.getString(1);
    Log.d("longitude: ", "> " + longitude);
    latitudeList.add(latitude); //<-- here why adding another time ?

在你做完之后:

latList = latitudeList;
longList = longitudeList;

我非常怀疑latListlongList长两倍,因此行IndexOutOfBoundsException中的thelongtitude = longList.get(i);因为你从{{1}循环而来} 0(两倍latList.size()}。

删除一个than longList.size(),这应该有效。

答案 1 :(得分:0)

    for (int i = 0; i < latList.size(); i++) {
        thelatitude  = latList.get(i);
        thelongtitude = longList.get(i);

这里的代码假设longList与latlist完全相同(或更长)。如果这个假设不正确,那么它将失败。