java.lang.IndexOutOfBoundsException : Invalid index 18, 大小为 18

标签 java android exception arraylist

<分区>

int i = 0; //used for getting item position
for (Iterator<CustomObject> iterator = mAdapter.getItemsData().iterator(); iterator.hasNext();) {

    if (mAdapter.getItemsData().get(i).getPriceTier() != 1) { //if statement throws error
        // Remove the current element from the iterator and the list.
        iterator.remove();
        mAdapter.removeFromItemsData(i);
    }
    i++;
}

使用 this stackoverflow 的回答,我遍历了 CustomObject 的数组列表。自定义对象只是一个带有 setter 和 getter 的 POJO 类。 setter 和 getter 具有不同的数据类型,例如 int、String、double 等。

mAdapter.getItemsData 从适配器类返回数组。

//method just notifies the RecyclerView that an item was removed.
public void removeFromItemsData(int position){

    notifyItemRemoved(position);
}

这里是异常(exception)

java.lang.IndexOutOfBoundsException: Invalid index 18, size is 18 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.test.TestActivity$5.onClick(TestActivity.java:280) at android.view.View.performClick(View.java:4780) at android.view.View$PerformClick.run(View.java:19866) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

自定义对象类

public class CustomObject{
    private String name;
    private int distance;
    private String category;
    private String id;
    private double rating;
    private String ratingColor;
    private String prefix;
    private String suffix;
    private int priceTier;
    private String currency;
    private String phone;
    private String twitter;
    private String url;
    private String menu;
    String address;
    String city;
    String state;
    String postalCode;
    double lat;
    double lng;
    String review;
    int reviewCount;
    String firstName;
    String lastName;
    String userIconPrefix;
    String userIconSuffix;
    String secondsReview;

    public CustomObject() {
        this.name = "";
        this.distance = 0;
        this.setCategory("");
        this.id = "";
        this.rating = 0;
        this.ratingColor = "";
        this.prefix = "";
        this.suffix = "";
        this.priceTier = 0;
        this.currency = "";
        this.phone = "";
        this.twitter = "";
        this.url = "";
        this.menu = "";
        this.address = "";
        this.city = "";
        this.state = "";
        this.postalCode = "";
        this.lat = 0;
        this.lng = 0;
        this.review = "";
        this.reviewCount = 0;
        this.firstName = "";
        this.lastName = "";
        this.userIconPrefix = "";
        this.userIconSuffix = "";
        this.secondsReview = "";
    }

    public void setSecondsReview(String secondsReview){
        this.secondsReview = secondsReview;
    }

    public String getSecondsReview(){
        return secondsReview;
    }

    public void setUserIconSuffix(String userIconSuffix){
        this.userIconSuffix = userIconSuffix;
    }

    public String getUserIconSuffix(){
        return userIconSuffix;
    }

    public void setUserIconPrefix(String userIconPrefix){
        this.userIconPrefix = userIconPrefix;
    }

    public String getUserIconPrefix(){
        return userIconPrefix;
    }

    public void setFirstName(String firstName){
        this.firstName = firstName;
    }

    public String getFirstName(){
        return firstName;
        //todo if String firstNAme == null, then return "a foursquare user"
    }

    public void setLastName(String lastName){
        this.lastName = lastName;
    }

    public String getLastName(){
        return lastName;
    }

    public void setReviewCount(int reviewCount){
        this.reviewCount = reviewCount;
    }

    public int getReviewCount(){
        return reviewCount;
    }

    public void setReview(String review){
        this.review = review;
    }

    public String getReview(){
        return review;
    }

    public void setLng(double lng){
        this.lng = lng;
    }

    public double getLng(){
        return lng;
    }

    public void setLat(double lat){
        this.lat = lat;
    }

    public double getLat(){
        return lat;
    }

    public void setPostalCode(String postalCode){
        this.postalCode = postalCode;
    }

    public String getPostalCode(){
        return postalCode;
    }

    public void setState(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }

    public void setCity(String city){
        this.city = city;
    }

    public String getCity(){
        return city;
    }

    public void setAddress(String address){
        this.address = address;
    }

    public String getAddress(){
        return address;
    }

    public void setMenuUrl(String menu){
        this.menu = menu;
    }

    public String getMenuUrl(){
        return menu;
    }

    public void setUrl(String url){
        this.url = url;
    }

    public String getUrl(){
        return url;
    }

    public void setTwitter(String twitter){
        this.twitter = twitter;
    }

    public String getTwitter(){
        return twitter;
    }

    public void setPhone(String phone){
        this.phone = phone;
    }

    public String getPhone(){
        return phone;
    }

    public String getCurrency(){
        return currency;
    }

    public void setCurrency(String currency){
        this.currency = currency;
    }

    public int getPriceTier(){
        return priceTier;
    }

    public void setPriceTier(int priceTier){
        this.priceTier = priceTier;
    }

    public String getSuffix(){
        return suffix;
    }

    public void setSuffix(String suffix){
        this.suffix = suffix;
    }

    public  String getPrefix(){
        return prefix;
    }

    public void setPrefix(String prefix){
        this.prefix = prefix;
    }

    public double getRating(){
        if(rating > 0){
            return rating;
        }
        return 0; //TODO display symbol if rating not found
    }

    public void setRating(double rating){
        this.rating = rating;
    }

    public Integer getDistance() {
        if (distance >= 0) {
            return distance;
        }
        return 0; //TODO display symbol if distance not found, like N/A
    }

    public void setDistance(int distance) {
            this.distance = distance;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

}

数据是如何添加的

在activity的onCreate中,我实例化了Recyclerview。 RecyclerView 采用一个数组列表,因此我传递了一个空数组。

List listTitle = new ArrayList(); //empty arraylist
mAdapter = new Fragment1Adapter(listTitle);

RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);

稍后在 AsyncTask 中,我将项目添加到适配器。

for (int i = 0; i < jsonArray.length(); i++) { 
    CustomObject poi = new CustomObject ();

    if (jsonArray.getJSONObject(i).has("venue")) {
        poi.setName(jsonArray.getJSONObject(i).getJSONObject("venue").getString("name"));
        poi.setId(jsonArray.getJSONObject(i).getJSONObject("venue").getString("id"));
    }
    mAdapter.addItem(poi);
}

这是addItem类

在适配器类顶部声明 private final List<FoursquareVenue> itemsData;

public void addItem(FoursquareVenue data) {
        itemsData.add(data);
        notifyItemInserted(itemsData.size() - 1);
    }

最佳答案

编辑

自从您开始我们的聊天和您的编辑:

您需要向您的 ArrayList 添加和删除项,它们会通知适配器更改。

CustomObject poi = new CustomObject ();
if (jsonArray.getJSONObject(i).has("venue")) {
    poi.setName(jsonArray.getJSONObject(i).getJSONObject("venue").getString("name"));
    poi.setId(jsonArray.getJSONObject(i).getJSONObject("venue").getString("id"));
}
listTitle.addItem(poi);// Add to ListArray

然后遍历您的 ArrayList 以删除项目。


您只是在尝试访问数据的方式上弄糊涂了。

创建 CustomObjects 的迭代器并将其解析为 mAdapter.getItemsData() 的数据类型时出现问题。

从迭代器中删除元素应该将其从列表中删除。

 for (Iterator<CustomObject> iterator = mAdapter.iterator(); iterator.hasNext();) {
     CustomObject itemsData = iterator.next();
     if (itemsData.getItemsData().get(i).getPriceTier() != 1) { //if statement throws error
            // Remove the current element from the iterator and the list.

            iterator.remove();
        }
        i++;
      }
    CustomObject itemsData = iterator.next();

如果这有帮助,请告诉我。

关于java.lang.IndexOutOfBoundsException : Invalid index 18, 大小为 18,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896886/

相关文章:

java - 如何绘制多边形,然后按比例调整其大小并将其移动到显示区域的中心?

java - 如何在音频均衡器中添加立体声、高音选项?

java - Maven 依赖项的全局范围

android - 如何在PreferenceActivity中的Preference Item右边标记一个Icon?

来自数据库的 Android SimpleCursorAdapter ID

java - 捕获 GenericJDBCException

java - 通过调用 Java 方法为 H2 数据库中的新行生成默认值

android - 我怎样才能让别人看不到我的源代码?

java - 我自己在 java 中的异常 - 找不到符号

java - 我可以使用捕获的异常绕数组移动一圈吗?