recyclerview onclicklistener java.lang.IndexOutOfBoundsException:索引0无效,大小为0

时间:2016-01-17 09:42:29

标签: java android android-activity adapter android-recyclerview

当我动态移除一个项目,或者当我刷新适配器(刷到新鲜)时,我得到这些错误:

17/01/2016 02:10:35.891 [main] DEBUG org.jboss.logging - Logging Provider: org.jboss.logging.Slf4jLoggerProvider
17/01/2016 02:10:35.943 [main] DEBUG o.h.i.i.IntegratorServiceImpl - Adding Integrator [org.hibernate.cfg.beanvalidation.BeanValidationIntegrator].
17/01/2016 02:10:35.949 [main] DEBUG o.h.i.i.IntegratorServiceImpl - Adding Integrator [org.hibernate.secure.spi.JaccIntegrator].
17/01/2016 02:10:35.953 [main] DEBUG o.h.i.i.IntegratorServiceImpl - Adding Integrator [org.hibernate.cache.internal.CollectionCacheInvalidator].
17/01/2016 02:10:35.987 [main] DEBUG o.h.b.r.s.i.StrategySelectorImpl - Registering named strategy selector [org.hibernate.dialect.Dialect] : [MySQL5] -> [org.hibernate.dialect.MySQL5Dialect] (replacing [org.hibernate.dialect.MySQL5Dialect])
17/01/2016 02:10:35.987 [main] DEBUG o.h.b.r.s.i.StrategySelectorImpl - Registering named strategy selector [org.hibernate.dialect.Dialect] : [MySQL5InnoDB] -> [org.hibernate.dialect.MySQL5InnoDBDialect] (replacing [org.hibernate.dialect.MySQL5InnoDBDialect])
17/01/2016 02:10:36.082 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {4.3.11.Final}
17/01/2016 02:10:36.086 [main] INFO  o.h.cfg.Environment - HHH000206: hibernate.properties not found
17/01/2016 02:10:36.089 [main] INFO  o.h.cfg.Environment - HHH000021: Bytecode provider name : javassist
17/01/2016 02:10:37.928 [main] DEBUG o.h.s.i.JaxbProcessor - cfg.xml document did not define namespaces; wrapping in custom event reader to introduce namespace information
17/01/2016 02:10:38.405 [main] DEBUG o.h.s.spi.ServiceBinding - Overriding existing service binding [org.hibernate.secure.spi.JaccService]
adds all the types
17/01/2016 02:10:38.651 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [uuid2] -> [org.hibernate.id.UUIDGenerator]
17/01/2016 02:10:38.652 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [guid] -> [org.hibernate.id.GUIDGenerator]
17/01/2016 02:10:38.654 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [uuid] -> [org.hibernate.id.UUIDHexGenerator]
17/01/2016 02:10:38.654 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [uuid.hex] -> [org.hibernate.id.UUIDHexGenerator]
17/01/2016 02:10:38.657 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [hilo] -> [org.hibernate.id.TableHiLoGenerator]
17/01/2016 02:10:38.658 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [assigned] -> [org.hibernate.id.Assigned]
17/01/2016 02:10:38.660 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [identity] -> [org.hibernate.id.IdentityGenerator]
17/01/2016 02:10:38.661 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [select] -> [org.hibernate.id.SelectGenerator]
17/01/2016 02:10:38.662 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [sequence] -> [org.hibernate.id.SequenceGenerator]
17/01/2016 02:10:38.663 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [seqhilo] -> [org.hibernate.id.SequenceHiLoGenerator]
17/01/2016 02:10:38.665 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [increment] -> [org.hibernate.id.IncrementGenerator]
17/01/2016 02:10:38.666 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [foreign] -> [org.hibernate.id.ForeignGenerator]
17/01/2016 02:10:38.667 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [sequence-identity] -> [org.hibernate.id.SequenceIdentityGenerator]
17/01/2016 02:10:38.668 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [enhanced-sequence] -> [org.hibernate.id.enhanced.SequenceStyleGenerator]
17/01/2016 02:10:38.670 [main] DEBUG o.h.i.f.i.DefaultIdentifierGeneratorFactory - Registering IdentifierGenerator strategy [enhanced-table] -> [org.hibernate.id.enhanced.TableGenerator]
17/01/2016 02:10:38.686 [main] WARN  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000402: Using Hibernate built-in connection pool (not for production use!)
17/01/2016 02:10:38.700 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://67.190.147.230:3306/school]
17/01/2016 02:10:38.701 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000006: Autocommit mode: false
17/01/2016 02:10:38.704 [main] INFO  o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
17/01/2016 02:10:38.705 [main] DEBUG o.h.e.j.c.i.DriverManagerConnectionProviderImpl - Initializing Connection pool with 1 Connections
17/01/2016 02:10:40.892 [main] DEBUG o.h.e.j.i.JdbcServicesImpl - JDBC version : 4.0
17/01/2016 02:10:40.897 [main] DEBUG o.h.e.j.c.i.StandardRefCursorSupport - Unexpected error trying to gauge level of JDBC REF_CURSOR support : null
17/01/2016 02:10:40.963 [main] INFO  o.h.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
17/01/2016 02:10:41.268 [main] DEBUG o.h.i.SessionFactoryImpl - Building session factory
17/01/2016 02:10:41.275 [main] DEBUG o.h.e.t.j.p.i.JtaPlatformInitiator - No JtaPlatform was specified, checking resolver
17/01/2016 02:10:41.276 [main] DEBUG o.h.e.t.j.p.i.JtaPlatformResolverInitiator - No JtaPlatformResolver was specified, using default [org.hibernate.engine.transaction.jta.platform.internal.StandardJtaPlatformResolver]
17/01/2016 02:10:41.282 [main] DEBUG o.h.e.t.j.p.i.StandardJtaPlatformResolver - Could not resolve JtaPlatform, using default [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
17/01/2016 02:10:41.292 [main] DEBUG o.h.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled
17/01/2016 02:10:41.292 [main] DEBUG o.h.cfg.SettingsFactory - Automatic session close at end of transaction: disabled
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - JDBC batch size: 15
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - Scrollable result sets: enabled
7/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - Wrap result sets: disabled
17/01/2016 02:10:41.293 [main] DEBUG o.h.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled
17/01/2016 02:10:41.294 [main] DEBUG o.h.cfg.SettingsFactory - multi-tenancy strategy : NONE
17/01/2016 02:10:41.294 [main] DEBUG o.h.cfg.SettingsFactory - Connection release mode: auto
17/01/2016 02:10:41.294 [main] INFO  o.h.e.t.i.TransactionFactoryInitiator - HHH000399: Using default transaction strategy (direct JDBC transactions)
17/01/2016 02:10:41.300 [main] DEBUG o.h.cfg.SettingsFactory - Using BatchFetchStyle : LEGACY
17/01/2016 02:10:41.300 [main] DEBUG o.h.cfg.SettingsFactory - Maximum outer join fetch depth: 2
17/01/2016 02:10:41.300 [main] DEBUG o.h.cfg.SettingsFactory - Default batch fetch size: 1
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Generate SQL with comments: disabled
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Order SQL updates by primary key: disabled
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Order SQL inserts for batching: disabled
17/01/2016 02:10:41.301 [main] DEBUG o.h.cfg.SettingsFactory - Default null ordering: none
17/01/2016 02:10:41.302 [main] DEBUG o.h.cfg.SettingsFactory - Query translator: org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
17/01/2016 02:10:41.306 [main] INFO  o.h.h.i.a.ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - Query language substitutions: {}
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - JPA-QL strict compliance: disabled
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - Second-level cache: enabled
17/01/2016 02:10:41.307 [main] DEBUG o.h.cfg.SettingsFactory - Query cache: disabled
17/01/2016 02:10:41.309 [main] DEBUG o.h.c.i.RegionFactoryInitiator - Cache region factory : org.hibernate.cache.internal.NoCachingRegionFactory
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Optimize cache for minimal puts: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Structured second-level cache entries: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Second-level cache direct-reference entries: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Automatic eviction of collection cache: disabled
17/01/2016 02:10:41.314 [main] DEBUG o.h.cfg.SettingsFactory - Statistics: disabled
17/01/2016 02:10:41.315 [main] DEBUG o.h.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled
17/01/2016 02:10:41.316 [main] DEBUG o.h.cfg.SettingsFactory - Default entity-mode: pojo
17/01/2016 02:10:41.317 [main] DEBUG o.h.cfg.SettingsFactory - Named query checking : enabled
17/01/2016 02:10:41.317 [main] DEBUG o.h.cfg.SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): enabled
17/01/2016 02:10:41.331 [main] DEBUG o.h.cfg.SettingsFactory - Allow initialization of lazy state outside session : : disabled
17/01/2016 02:10:41.332 [main] DEBUG o.h.cfg.SettingsFactory - JTA Track by Thread: enabled
17/01/2016 02:10:41.357 [main] DEBUG o.h.i.SessionFactoryImpl - Session factory constructed with filter configurations : {}
17/01/2016 02:10:41.384 [main] DEBUG o.h.s.spi.JaccIntegrator - Skipping JACC integration as it was not enabled
17/01/2016 02:10:41.592 [main] DEBUG o.h.i.SessionFactoryRegistry - Initializing SessionFactoryRegistry : org.hibernate.internal.SessionFactoryRegistry@36916eb0
17/01/2016 02:10:41.597 [main] DEBUG o.h.i.SessionFactoryRegistry - Registering SessionFactory: 6757530c-07f1-45bd-8c6f-a3a9697d6341 (<unnamed>)
17/01/2016 02:10:41.597 [main] DEBUG o.h.i.SessionFactoryRegistry - Not binding SessionFactory to JNDI, no JNDI name configured
17/01/2016 02:10:41.597 [main] DEBUG o.h.i.SessionFactoryImpl - Instantiated session factory
17/01/2016 02:10:41.598 [main] DEBUG o.h.i.NamedQueryRepository - Checking 0 named HQL queries
17/01/2016 02:10:41.598 [main] DEBUG o.h.i.NamedQueryRepository - Checking 0 named SQL queries
17/01/2016 02:10:41.610 [main] DEBUG o.h.s.i.StatisticsInitiator - Statistics initialized [enabled=false]
sessionfactory made, now creating session
made session
17/01/2016 02:10:41.739 [main] DEBUG o.h.e.t.s.AbstractTransactionImpl - begin
17/01/2016 02:10:41.740 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtaining JDBC connection
17/01/2016 02:10:41.740 [main] DEBUG o.h.e.j.i.LogicalConnectionImpl - Obtained JDBC connection
17/01/2016 02:10:41.740 [main] DEBUG o.h.e.t.i.j.JdbcTransaction - initial autocommit status: false

真的无法弄清楚为什么会这样,真正感谢任何反馈。

MainActivity:

recyclerview onclicklistener java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

适配器:

adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                GroupModel selectedList = mGroupModels.get(position);

                if (selectedList != null) {

                    Log.d(TAG, "setAdpterListner > view.getId: " + view.getId() +
                                    " | P: " + position +
                                    " | data ID: " + selectedList.getGroupName()
                            //" | viewID: " + viewID
                    );


                    Intent intent = new Intent(this, DetailsActivity.class);
                    String listId = selectedList.getGroupID();
                    String listName = selectedList.getGroupName();
                    intent.putExtra(Constant.KEY_LIST_ID, listId);
                    intent.putExtra(Constant.KEY_LIST_NAME, listName);
                    startActivity(intent);
                }
            }
        });
  
    

更新:

  

我考虑了Yurii Tsap反馈。我再次检查代码。我认为问题出在以下某处:

每当我刷到Fresh,如果我直接点击列表,应用程序崩溃,上面有错误。

public class GroupListAdapter extends RecyclerView.Adapter<GroupListAdapter.StatusViewHolder> {

    Context context;
    private List<GroupModel> mGroupModels;
    private static OnItemClickListener listener;




    public GroupListAdapter(Context context, List<GroupModel> groupList) {
        this.context = context;
        this.mGroupModels = groupList;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        GroupListAdapter.listener = listener;
    }




    @Override
    public StatusViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_group_list, parent, false);
        return new StatusViewHolder(view);
    }


    @Override
    public void onBindViewHolder(StatusViewHolder holder, int position) {

        final GroupModel data = mGroupModels.get(position);

        holder.text_view_list_name.setText(data.getGroupName());


    }//end onBindViewHolder


    @Override
    public int getItemCount() {
        return mGroupModels.size();
    }






    public class StatusViewHolder extends RecyclerView.ViewHolder {

        public TextView text_view_list_name;
        public TextView created_by;



        public StatusViewHolder(final View itemView) {
            super(itemView);

            text_view_list_name = (TextView) itemView.findViewById(R.id.text_view_list_name);
            created_by = (TextView) itemView.findViewById(R.id.created_by);


            // Setup the click listener
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null)
                        listener.onItemClick(itemView, getLayoutPosition());
                }
            });


        }
    }//end StatusViewHolder


}//end GroupListAdapter

在API调用中

 mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Refresh items
                mRecyclerView.invalidate();
                adapter = null;

                initGetGroupList();
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

3 个答案:

答案 0 :(得分:1)

问题绝对不在静态侦听器中。而且监听器只是一个接口回调(与上面的注释相关)而不是AdapterView.OnItemClickListener()。我认为问题是在这个代码背后的某个地方,也许你正在清除其他地方的项目列表或类似的东西?
对我而言,最好使用getAdapterPosition()而不是getLayoutPosition()。 如文档中所述:

  

如果LayoutManager需要调用需要项目的适配器位置的外部方法,它可以使用getAdapterPosition()或RecyclerView.Recycler.convertPreLayoutPositionToPostLayout(int)。

答案 1 :(得分:0)

OnItemClickListener非静态.Like

private OnItemClickListener listener;

答案 2 :(得分:0)

你的代码有很多问题 我将解释我处理回收视图的方法

非常简单的适配器

package com.pentavalue.ongo.transportway.adapter;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;


import com.pentavalue.ongo.R;
import com.pentavalue.ongo.Utilts.ImageLoaderHelper;
import com.pentavalue.ongo.register.model.Vechiles;
import com.pentavalue.ongo.widget.ArabicTextView;

import java.util.ArrayList;

/**
 * Created by hamada on 19/09/2015.
 */
public class TransportTypeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public LayoutInflater inflater = null;

    Activity activity;
    ArrayList<Vechiles> vechileList;
    ImageLoaderHelper imageLoaderHelper;

    public TransportTypeAdapter(Activity activity, ArrayList<Vechiles> vechileList) {
        this.activity = activity;
        this.vechileList = vechileList;
        imageLoaderHelper = new ImageLoaderHelper(activity, null);
        inflater = LayoutInflater.from(activity);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View vi = inflater.inflate(R.layout.single_transport_item, parent, false);
        RecyclerView.ViewHolder vh = new VechileListHolder(vi);
        return vh;

    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int pos) {

        VechileListHolder mHolder = (VechileListHolder) viewHolder;
        mHolder.renderDate(vechileList.get(pos));

    }


    @Override
    public int getItemCount() {
        if (vechileList != null)
            return this.vechileList.size();
        else
            return 0;
    }


    public class VechileListHolder extends RecyclerView.ViewHolder implements
        View.OnClickListener {
        ArabicTextView vecName;
        RelativeLayout img_layout;
        ProgressBar progress;
        ImageView imgView;

        public VechileListHolder(View vi) {
            super(vi);
            vi.setOnClickListener(this);
            img_layout = (RelativeLayout) vi.findViewById(R.id.img_layout);
            vecName = (ArabicTextView) vi.findViewById(R.id.TVVecName);
            progress = (ProgressBar) vi.findViewById(R.id.progress);
            imgView = (ImageView) vi.findViewById(R.id.imgView);


        }

        public void renderDate(Vechiles item) {
            imageLoaderHelper.loadImage(imgView, progress, item.getImg());
            vecName.setText(item.getVecName());

        }

        @Override
        public void onClick(View v) {
            if (mItemClickListener != null)
                mItemClickListener.onItemClickListener(getPosition(), v);
        }
    }


    public void setOnItemClickListener(ItemClickListener itemClick) {
        this.mItemClickListener = itemClick;
    }

    public ItemClickListener mItemClickListener;

    public interface ItemClickListener {
        public void onItemClickListener(int pos, View v);
    }

    public void updateList(ArrayList<Vechiles> vechileList) {
        this.vechileList = vechileList;
        notifyDataSetChanged();
    }


 public void removeItem(int pos){
     this.vechileList.remove(pos);
    notifyItemRemoved(pos);
    }

    }

并在片段或活动中可以    @覆盖     public void onActivityCreated(@Nullable Bundle savedInstanceState){         super.onActivityCreated(savedInstanceState);

        initListView();

}

private void initRecycleView(){
 listView = (RecyclerView) v.findViewById(R.id.listView);
        listView.getItemAnimator().setAddDuration(1000);
        listView.getItemAnimator().setChangeDuration(1000);
        listView.getItemAnimator().setMoveDuration(1000);
        listView.getItemAnimator().setRemoveDuration(1000);
        listView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        listView.setAdapter(new TransportTypeAdapter(getActivity(), vecList));
}

然后从API返回的数据可以通过使用方法更新

更新带有新数据的适配器
((VechileListHolder ) listView.getAdapter).updateList( vechileList);

以防使用Pos删除任何项目可以在适配器removeItem(pos)中执行调用方法

((VechileListHolder ) listView.getAdapter).removeItem(1);

希望此代码可以帮助您