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

僵尸

我正在制作一个从 Google Places 获取信息并将其显示在列表视图中的应用程序。我目前遇到的问题是列表视图显示信息,但在应用程序崩溃后不久,我在数组适配器中收到一个 IndexOutOfBounds 异常,它从places.get(position) 获取Place 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);
    }
}}

自定义适配器类:

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;
}}
维萨特赫

看起来你有多个问题。

  1. 首先,我建议您在“doInBackground”中创建一个新的数组列表,就像用户在清除数组列表“nearbyPlaces”时碰巧滚动列表视图一样,您的应用程序将崩溃,因为列表“nearbyPlaces”中没有任何元素。
  2. 将项目添加到列表后,您似乎没有调用“notifyDataSetChanged()”。

所以最好的解决办法是

  1. 在“doInBackground”中创建一个新的arraylist,添加你需要的所有项目
  2. 将数组列表传递给“onPostExecute”
  3. 将“nearbyPlaces”设置为新的arraylist,然后调用“adapter.notifyDataSetChanged()”

此外,它可以解决崩溃指数超出范围的问题,但是当您调用“adapter.notifyDataSetChanged()”时,如果用户已经离开活动,例如按下主页,单击项目以移动到另一个活动,则可能会导致崩溃。所以请确保 UI 或 View 是可访问的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

自定义ListView适配器的异常行为

在RecyclerView适配器中设置自定义字体

如何在Android中自定义适配器?

自定义视图的适配器中的NullPointerException

listview项目未在自定义适配器的getview方法中显示分配的值

在getView上的自定义适配器中以编程方式添加textviews

getView()如何在自定义适配器中工作?

ImageView在getView()时崩溃了自定义适配器

自定义适配器中的空指针异常

在自定义适配器中找不到ViewByID

getview自定义适配器上的nullpointerexception

自定义ListView适配器中的NullPointerException

ListView /自定义数组适配器-调用getView时适配器设置为null

android自定义列表视图适配器中的ArrayList索引超出范围异常

使用自定义适配器的notifyDatasetChanged的NullPointer异常

自定义适配器的getview中的NullPointerException

自定义适配器的getView返回错误的位置

getView()中的自定义适配器错误

如果条件在自定义适配器中不起作用(getView())

在自定义适配器中遍历ListView

在调试的自定义适配器中未调用Getview,发现位置返回为-1

自定义绑定适配器中的通用lambda

在自定义适配器类中显示空指针异常的上下文?

无法更新自定义适配器中的项目

在 RecyclerView 的自定义适配器中膨胀时获取空指针异常

自定义适配器 getView 返回空指针

自定义适配器中的意图

Fragment 中的自定义列表适配器

协程中的自定义适配器