Android 自定义适配器getView中的IndexOutOfBounds异常

Android 自定义适配器getView中的IndexOutOfBounds异常,android,listview,android-arrayadapter,indexoutofboundsexception,Android,Listview,Android Arrayadapter,Indexoutofboundsexception,我正在制作一个应用程序,它从GooglePlaces获取信息并将其显示在listview中。我目前遇到的问题是,listview显示信息,但在应用程序崩溃后不久,我在数组适配器中得到一个IndexOutOfBounds异常,它从places.get(位置)获取位置p 活动类: public class NearbyLocationsActivity extends BaseActivity implements AsyncDelegate { private Location mLastLoca

我正在制作一个应用程序,它从GooglePlaces获取信息并将其显示在listview中。我目前遇到的问题是,listview显示信息,但在应用程序崩溃后不久,我在数组适配器中得到一个IndexOutOfBounds异常,它从places.get(位置)获取位置p

活动类:

public class NearbyLocationsActivity extends BaseActivity implements AsyncDelegate {
private Location mLastLocation;
private GetLocations nearbyLocations;
private PlaceAdapter adapter;

private ArrayList<Place> nearbyPlaces;

private double mLat;
private double mLong;

private ListView locationsList;

public Spinner typesSpinner;

private BroadcastReceiver broadcastReceiver;

private String radius = "10000";

private int selectedSpinnerIndex;

private String [] types = {"everything", "restaurant", "bar", "museum", "night_club", "cafe", "movie_theater"};

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

    locationsList = (ListView) findViewById(R.id.locations_list);
    typesSpinner = (Spinner) findViewById(R.id.type_spinner);

    nearbyPlaces = new ArrayList();

    adapter = new PlaceAdapter(getApplicationContext(), nearbyPlaces);
    locationsList.setAdapter(adapter);

    if(!runtimePermissions()) {
        enableService();
    }
}

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

    return true;
}

public void enableService() {
    Intent i = new Intent(getApplicationContext(), LocationService.class);
    startService(i);
}

private boolean runtimePermissions() {
    if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
            return true;
    }
    return false;
}

@Override
public void onResume() {
    super.onResume();
    if (broadcastReceiver == null) {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                mLastLocation = (Location) intent.getExtras().get("coordinates");
                mLat = mLastLocation.getLatitude();
                mLong = mLastLocation.getLongitude();

                nearbyLocations = new GetLocations(NearbyLocationsActivity.this);
                nearbyLocations.execute();
            }
        };
        registerReceiver(broadcastReceiver, new IntentFilter("location_updates"));
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (broadcastReceiver != null) {
        unregisterReceiver(broadcastReceiver);
    }
}

@Override
public void onStop() {
    Intent i = new Intent(getApplicationContext(), LocationService.class);
    stopService(i);
    super.onStop();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            enableService();
        } else {
            runtimePermissions();
        }
    }
}

@Override
public void asyncComplete(boolean success) {
    adapter.notifyDataSetChanged();

    typesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            selectedSpinnerIndex = typesSpinner.getSelectedItemPosition();
            new GetLocations(NearbyLocationsActivity.this).execute();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            selectedSpinnerIndex = 0;
        }
    });

    locationsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Place p = adapter.getItem(position);
            Intent intent = new Intent(getApplicationContext(), CreateEventActivity.class);
            intent.putExtra("selectedPlace", p);
            startActivity(intent);
        }
    });
}

public class GetLocations extends AsyncTask<Void, Void, Void> {

    private AsyncDelegate delegate;

    public GetLocations (AsyncDelegate delegate){
        this.delegate = delegate;
    }

    @Override
    protected Void doInBackground(Void... params) {
        nearbyPlaces.clear();
        StringBuilder sb = new StringBuilder();
        String http = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + mLat + "," + mLong +
                "&radius=10000";

        if (selectedSpinnerIndex != 0) {
            http += "&types=" + types[selectedSpinnerIndex];
        }

        http += "&key=AIzaSyDFb37i6VGPj2EG6L7dLO5H7tDhLCqCW2k";

        HttpURLConnection urlConnection;
        try {
            URL url = new URL(http);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");

            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }

            JSONObject jsonObject = new JSONObject(sb.toString());
            JSONArray array = jsonObject.getJSONArray("results");

            for (int i = 0; i < array.length(); i++) {
                JSONObject placeLine = (JSONObject) array.get(i);
                Place place = new Place();
                JSONObject geometryLine = placeLine.getJSONObject("geometry");
                JSONObject locationLine = geometryLine.getJSONObject("location");
                Place.Location location = new Place.Location();
                location.setLat(locationLine.getDouble("lat"));
                location.setLon(locationLine.getDouble("lng"));
                place.setLocation(location);
                place.setIcon(placeLine.getString("icon"));
                place.setPlaceId(placeLine.getString("place_id"));

                String detailsHttp = "https://maps.googleapis.com/maps/api/place/details/json?key=AIzaSyDFb37i6VGPj2EG6L7dLO5H7tDhLCqCW2k&placeid=" + place.getPlaceId();
                getPlaceDetails(detailsHttp, place);

                place.setName(placeLine.getString("name"));

                /*JSONArray typesJson = new JSONArray("types");
                String [] types = new String[typesJson.length()];
                for (int a = 0; i < typesJson.length(); i++) {
                    types[a] = typesJson.getString(a);
                }
                place.setTypes(types);*/

                place.setVicinity(placeLine.getString("vicinity"));

                try {
                    place.setRating(placeLine.getInt("rating"));
                } catch (JSONException je) {
                    place.setRating(-1);
                }

                try {
                    JSONArray photosJson = placeLine.getJSONArray("photos");
                    //for (int k = 0; i < photosJson.length(); i++) {
                        JSONObject photoLine = (JSONObject) photosJson.get(0);

                        String photoHttp = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&" +
                                "photoreference=" + photoLine.getString("photo_reference") + "&key=AIzaSyDFb37i6VGPj2EG6L7dLO5H7tDhLCqCW2k";

                        place.setPhotoHttp(photoHttp);
                        //place.addPhotoHttp(photoHttp);
                    //}
                } catch (JSONException je) {
                    place.setPhotoHttp(null);
                }
                nearbyPlaces.add(place);
            }

        } catch(MalformedURLException mue){
            System.out.println("A malformed URL exception occurred. " + mue.getMessage());
        } catch(IOException ioe){
            System.out.println("A input/output exception occurred. " + ioe.getMessage());
        } catch(JSONException je){
            System.out.println("A JSON error occurred. " + je.getMessage());
        }

        return null;
    }

    public void getPlaceDetails(String http, Place p) {
        StringBuilder sb = new StringBuilder();
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(http);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");

            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }

            JSONObject jsonObject = new JSONObject(sb.toString());
            JSONObject resultsJson = jsonObject.getJSONObject("result");
            String address = resultsJson.getString("formatted_address");
            p.setAddress(address);
        } catch(MalformedURLException mue){
            System.out.println("A malformed URL exception occurred. " + mue.getMessage());
        } catch(IOException ioe){
            System.out.println("A input/output exception occurred. " + ioe.getMessage());
        } catch(JSONException je){
            System.out.println("A JSON error occurred. " + je.getMessage());
        }
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        // Thread is finished downloading and parsing JSON, asyncComplete is
        delegate.asyncComplete(true);
    }
}}
公共类NearByLocationActivity扩展BaseActivity实现AsyncDelegate{
私人场所;
附近的私人场所;
私人配售适配器;
附近的私人ArrayList;
私人双mLat;
私人双米隆;
私有列表视图位置列表;
公共旋转器类型旋转器;
专用广播接收机;
专用字符串半径=“10000”;
私有int选择喷丝头索引;
私人字符串[]类型={“一切”、“餐厅”、“酒吧”、“博物馆”、“夜总会”、“咖啡馆”、“电影院”};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_附近的位置);
locationsList=(ListView)findViewById(R.id.locations\u列表);
typesSpinner=(微调器)findViewById(R.id.type\u微调器);
nearbyPlaces=newarraylist();
adapter=newplaceadapter(getApplicationContext(),nearbyPlaces);
位置列表设置适配器(适配器);
如果(!runtimePermissions()){
enableService();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
super.onCreateOptions菜单(菜单);
返回true;
}
公共void启用服务(){
Intent i=新Intent(getApplicationContext(),LocationService.class);
startService(一);
}
私有布尔运行时权限(){
if(Build.VERSION.SDK\u INT>=23&&ContextCompat.checkSelfPermission(这是Manifest.permission.ACCESS\u FINE\u位置)
!=已授予PackageManager.PERMISSION\u权限
&&ContextCompat.checkSelfPermission(这是Manifest.permission.ACCESS\u位置)
!=PackageManager.权限(已授予){
requestPermissions(新字符串[]{Manifest.permission.ACCESS\u FINE\u位置,
Manifest.permission.ACCESS\u\u LOCATION},100);
返回true;
}
返回false;
}
@凌驾
恢复时公开作废(){
super.onResume();
if(broadcastReceiver==null){
broadcastReceiver=新的broadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
mLastLocation=(位置)intent.getExtras().get(“坐标”);
mLat=mLastLocation.getLatitude();
mLong=mLastLocation.getLongitude();
nearbyLocations=新的GetLocations(NearbyLocationsActivity.this);
nearbyLocations.execute();
}
};
registerReceiver(广播接收器、新意向过滤器(“位置更新”);
}
}
@凌驾
公共空间{
super.ondestory();
if(broadcastReceiver!=null){
未注册接收器(广播接收器);
}
}
@凌驾
公共void onStop(){
Intent i=新Intent(getApplicationContext(),LocationService.class);
停止服务(一);
super.onStop();
}
@凌驾
public void onRequestPermissionsResult(int-requestCode、字符串[]权限、int[]grantResults){
super.onRequestPermissionsResult(请求代码、权限、授权结果);
if(requestCode==100){
if(授予的grantResults[0]==PackageManager.PERMISSION&&grantResults[1]==授予的PackageManager.PERMISSION){
enableService();
}否则{
运行时权限();
}
}
}
@凌驾
public void异步完成(布尔成功){
adapter.notifyDataSetChanged();
typesSpinner.setOnItemSelectedListener(新的AdapterView.OnItemSelectedListener(){
@凌驾
已选择公共视图(AdapterView父视图、视图视图、整型位置、长id){
selectedSpinnerIndex=typesSpinner.getSelectedItemPosition();
新的GetLocations(NearbyLocationsActivity.this).execute();
}
@凌驾
未选择公共无效(AdapterView父级){
selectedSpinnerIndex=0;
}
});
locationsList.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
放置p=适配器.getItem(位置);
Intent Intent=new Intent(getApplicationContext(),CreateEventActivity.class);
意向。额外(“选定地点”,p);
星触觉(意向);
}
});
}
公共类GetLocations扩展异步任务{
私人代表;
公共GetLocations(异步委托){
this.delegate=委托;
}
@凌驾
受保护的Void doInBackground(Void…参数){
附近的地方。清除();
StringBuilder sb=新的StringBuilder();
字符串http=”https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=“+mLat+”,“+mLong+
“&radius=10000”;
如果(selectedSpinnerIndex!=0){
http+=“&types=“+types[selectedSpinnerIndex];
}
http+=“&key=AIzaSyDFb37i6VGPj2EG6L7dLO5H7tDhLCqCW2k”;
HttpURLConnection-urlConnection;
试一试{
URL=新URL(http);
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod(“GET”);
if(urlConnection.getResponseCode()==HttpURLConnection.HTTP\u确定){
InputStream in=new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
弦线;
而((line=reader.readLine())!=null){
某人附加(行);
}
}
JSONObject JSONObject
public class PlaceAdapter extends ArrayAdapter<Place> {
private Context mContext;
private ArrayList<Place> places;

public PlaceAdapter(Context context, ArrayList<Place> nearbyPlaces) {
    super(context, R.layout.place_list_item, nearbyPlaces);
    mContext = context;
    this.places = nearbyPlaces;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View view = inflater.inflate(R.layout.place_list_item, null);
    final Place p = places.get(position);

    TextView placeName = (TextView) view.findViewById(R.id.place_name);
    placeName.setText(p.getName());

    TextView placeAddress = (TextView) view.findViewById(R.id.place_address);
    placeAddress.setText(p.getAddress());

    ImageView placeImage = (ImageView) view.findViewById(R.id.place_picture);

    if (p.getPhotoHttp() != null) {
        Picasso.with(mContext).load(p.getPhotoHttp()).into(placeImage);
    } else {
        Picasso.with(mContext).load(p.getIcon()).into(placeImage);
    }
    return view;
}}
@Override
protected Void doInBackground(Void... params) {
    nearbyPlaces.clear();

    ..............
    .................

    try {
        .............
        ...................

        for (int i = 0; i < array.length(); i++) {
            ..............
            .................

            nearbyPlaces.add(place);
            adapter.notifyDataSetChanged(); // Update ListView
        }
    } catch(MalformedURLException mue){
        System.out.println("A malformed URL exception occurred. " + mue.getMessage());
    } catch(IOException ioe){
        System.out.println("A input/output exception occurred. " + ioe.getMessage());
    } catch(JSONException je){
        System.out.println("A JSON error occurred. " + je.getMessage());
    }

    return null;
}