Android IndexOutOfBoundsException:索引:1,大小:1

时间:2017-04-09 20:37:02

标签: android sqlite google-maps maps

我刚才在Android上使用SQLite,我在这里遇到了一些错误。

我有这个应用程序:

http://imgur.com/gallery/The7Q

使用下面的代码,我可以点击保存按钮和列表中的第一项,在本例中为伦敦,然后转到该地点的位置。

但是当我添加第二名并尝试上述内容时,我得到了一个:

java.lang.IndexOutOfBoundsException:Index:1,Size:1

在这一行:

 //Centralize the selected item
        Orientation selectedLocation = geocodingResult.getResults().get(getIntent().getIntExtra(SELECTED_POSITION, 1)).getGeometry().getLocation();

如何解决这个问题?

地图活动:

public class MapActivity extends AppCompatActivity {

private GoogleMap map;
private GeocodeResult geocodingResult;

List<Address> listAddresses;

String address = "";

public LatLng latlng;

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

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.activity_map_googlemap)).getMap();

    addMarkers();
}

 // Show the markers on the map
public void addMarkers() {
    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    geocodingResult = getIntent().getParcelableExtra(MainActivity.RESULT);

    if (geocodingResult != null) {
        //  For each Geocoding object, get the results markers
        for (Geocoding geocoding : geocodingResult.getResults()) {
            map.addMarker(new MarkerOptions()
                    .position(new LatLng(geocoding.getGeometry().getLocation().getLat(), geocoding.getGeometry().getLocation().getLng()))
                    .icon(BitmapDescriptorFactory.defaultMarker())
                    .title(geocoding.getFormattedAddress()) //location name that will be shown when click the marker
                    .snippet(String.valueOf(geocoding.getGeometry().getLocation().getLat())
                            + ", "
                            + String.valueOf(geocoding.getGeometry().getLocation().getLng())) //coordinates that will be shown when click the marker
            );
            try {
                latlng = new LatLng(geocoding.getGeometry().getLocation().getLat(), geocoding.getGeometry().getLocation().getLng());
                listAddresses = geocoder.getFromLocation(geocoding.getGeometry().getLocation().getLat(), geocoding.getGeometry().getLocation().getLng(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d("LIST", String.valueOf(listAddresses));
        }


        //Centralize the selected item
        Orientation selectedLocation = geocodingResult.getResults().get(getIntent().getIntExtra(SELECTED_POSITION, 1)).getGeometry().getLocation();
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(selectedLocation.getLat(), selectedLocation.getLng()), 4));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

    if (item.getItemId() == R.id.save) {

        try {

            List<Address> listAddresses = geocoder.getFromLocation(latlng.latitude, latlng.longitude, 1);

            if (listAddresses != null && listAddresses.size() > 0) {

                if (listAddresses.get(0).getLocality() != null) {

                    if (listAddresses.get(0).getPostalCode() != null) {

                        address += listAddresses.get(0).getLocality() + " ";

                    }

                    address += listAddresses.get(0).getPostalCode();

                }
            }
            Log.d("LIST", String.valueOf(listAddresses));
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (address == "") {

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy-MM-dd");

            address = sdf.format(new Date());
        }

        DBController crud = new DBController(getBaseContext());
        String result;
        result = crud.insertData(address, latlng.latitude, latlng.longitude);
        Log.d("ADDRESS", address);
        Log.d("LAT", String.valueOf(latlng.latitude));
        Log.d("LNG", String.valueOf(latlng.longitude));
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }

    return super.onOptionsItemSelected(item);
}// END MENU

主要

public class MainActivity extends AppCompatActivity {

public final static String RESULT = "listGeocoding";
public final static String SELECTED_POSITION = "selectedPosition";

public static ListView listView;
EditText edtSearch;
Button btnSearch;

GeocodeResult geocodingResult;
Dialog dialogProgress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edtSearch = (EditText) findViewById(R.id.edtSearch);
    btnSearch = (Button) findViewById(R.id.btnSearch);

    listView = (ListView) findViewById(R.id.listView);

    setListeners();

}// END ON CREATE

//  Set Listeners to the activity
private void setListeners() {

    //region Button click jump to SearchAddress method
    btnSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchAddress();
        }
    });
    //endregion

    //region List View Click jump to MapActivity
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(MainActivity.this, MapActivity.class);
            intent.putExtra(RESULT, geocodingResult);
            intent.putExtra(SELECTED_POSITION, position);
            startActivity(intent);
        }
    });
    //endregion
}// END METHOD

//region Deal with orientation changes
@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putParcelable(RESULT, geocodingResult);
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    geocodingResult = savedInstanceState.getParcelable(RESULT);

    if (geocodingResult != null && geocodingResult.getResults().size() > 0) {
        loadResult();
    }
}
//endregion

//region Search method
private void searchAddress() {
    //region Deal with the keyboard and user input
    CommonUtils.hideKeyboard(MainActivity.this, edtSearch);

    //  Ask the user for the address if not provided
    if (edtSearch.getText().toString().equals("")) {
        Toast.makeText(MainActivity.this, "Please enter an address", Toast.LENGTH_SHORT).show();
        return; //  pause and await for response
    }
    //endregion

    listView.setVisibility(View.GONE);
    showProgress();

        //region Search the address
        GoogleMaps service = ServiceGenerator.createService(GoogleMaps.class, "http://maps.googleapis.com");    //  API URL
        service.getGeocoding(edtSearch.getText().toString(), true, new Callback<GeocodeResult>() {
            @Override
            public void success(GeocodeResult googleGeocodingResult, Response response) {
                hideProgress();
                geocodingResult = googleGeocodingResult;

                if (geocodingResult.getResults().size() > 0) {
                    loadResult();
                } else {
                    Toast.makeText(MainActivity.this, "Didn't find a place.", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
                Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        //endregion
}

private void loadResult() {
    listView.setVisibility(View.VISIBLE);
    listView.setAdapter(new Adapter(MainActivity.this, geocodingResult.getResults()));
}
//endregion

//region Progress Dialog
private void showProgress() {
    if (dialogProgress == null) {
        dialogProgress = new Dialog(this);
        dialogProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialogProgress.setContentView(R.layout.custom_progress);
        dialogProgress.setCancelable(false);
    }
    dialogProgress.getWindow().getDecorView().getRootView();
    dialogProgress.show();
}

private void hideProgress() {
    if (dialogProgress != null) {
        dialogProgress.dismiss();
        dialogProgress = null;
    }
}
//endregion

//region Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.save){
        Intent intent = new Intent(getApplicationContext(), Query.class);
        intent.putExtra(RESULT, geocodingResult);
        startActivity(intent);
    }
    return super.onOptionsItemSelected(item);
}

查询:

    import static com.arthurabreu.memorableplaces.MainActivity.RESULT;
import static com.arthurabreu.memorableplaces.MainActivity.SELECTED_POSITION;


/**
 * Created by blitz on 4/8/2017.
 */

public class Query extends AppCompatActivity {

    private ListView list;
    private GeocodeResult geocodingResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view_query);

        DBController crud = new DBController(getBaseContext());
        Cursor cursor = crud.loadData();

        String[] titles = new String[] {SQLite.ID, SQLite.KEY_TITLE};
        int[] idViews = new int[] {R.id.idNumber, R.id.idTitle};


        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(),
                R.layout.adapter_query_layout,cursor,titles,idViews, 0);
        list = (ListView)findViewById(R.id.listView);
        list.setAdapter(adapter);


        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                final Cursor c = ((SimpleCursorAdapter)list.getAdapter()).getCursor();
                c.moveToPosition(position);
                String place = c.getString(1); //Get the name of the place saved in the cursor
                Log.d("TEST", String.valueOf(c.getString(1)));

                //region Search the address
                GoogleMaps service = ServiceGenerator.createService(GoogleMaps.class, "http://maps.googleapis.com");    //  API URL
                service.getGeocoding(place, true, new Callback<GeocodeResult>() {
                    @Override
                    public void success(GeocodeResult googleGeocodingResult, Response response) {

                        geocodingResult = googleGeocodingResult;

                        if (geocodingResult.getResults().size() > 0) {
                            Intent intent = new Intent(getApplicationContext(), MapActivity.class);
                            intent.putExtra(RESULT, geocodingResult);
                            intent.putExtra(SELECTED_POSITION, position);
                            Log.d("POSITION", String.valueOf(position));
                            startActivity(intent);
                        } else {
                            Toast.makeText(getApplicationContext(), "Didn't find a place.", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {

                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
                //endregion

            }// END ON CLICK
        });

    }// END ONCREATE
}// ENDMAIN

1 个答案:

答案 0 :(得分:1)

当编码无法达到特定索引时,就会出现错误。您可以查看thread

  

IndexOutOfBound异常意味着您遇到了问题,因为您尝试访问的索引不存在或为空(非空)。例如,如果您有一个只有两个元素的数组,那么它只有索引0和1,并且您尝试访问索引2,您将获得IndexOutOfBoundException,因为索引2不存在。如果您创建一个包含10个元素且仅填充5的数组,则索引4-9将为空,访问这些元素可能会导致IndexOutOfBoundException。

以下是解决此问题的可能解决方法:

  

如果您正在使用IDE,则可以通过删除throws语句来帮助您调试问题。抛出陈述&#34;推卸责任&#34;当涉及到异常时,您实际上并没有通过使用throws来处理异常。 Try-catch语句更好地处理异常,因为它们缩小了问题所在的区域(因为它们测试了试验括号内的代码。

     

抛出它们的位置,但是为了调试try-catch可能会更有帮助。

其他参考资料: