微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试在另一个活动“ java.lang.IndexOutOfBoundsException:索引:0,大小:0”中显示详细信息

如何解决尝试在另一个活动“ java.lang.IndexOutOfBoundsException:索引:0,大小:0”中显示详细信息

我正在尝试使用OnItemClick在用户个人资料页面显示详细信息,但仍然出现此错误

java.lang.indexoutofboundsexception: Index: 0,Size: 0
        at java.util.ArrayList.get(ArrayList.java:437)
        at fr.ousoft.suiviemedsBox.ScrollingActivity.OnItemClick(**ScrollingActivity.java:102**)
        at fr.ousoft.suiviemedsBox.UsersAdapter$AdapterVH$1.onClick(**UsersAdapter.java:115**)

这是我的活动代码

    public class ScrollingActivity extends AppCompatActivity implements UsersAdapter.OnItemClickListener {

    public static final String EXTRA_CREATOR_NOM = "Nom";
    public static final String EXTRA_CREATOR_PRENOM = "Prenom";
    public static final String EXTRA_CREATOR_TEL = "Tel";
    public static final String EXTRA_CREATOR_EMAIL = "Email";
    public static final String EXTRA_CREATOR_ETABLISSEMENT = "Etablissement";
    public static final String EXTRA_CREATOR_TYPE = "Type";
    public static final String EXTRA_CREATOR_ACTIVE = "Active";

    RecyclerView recyclerView;
    ApiInterface apiInterface;
    UsersAdapter usersAdapter;
    ArrayList<User> mListe = new ArrayList<>();

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        CollapsingToolbarLayout toolBarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        toolBarLayout.setTitle(getTitle());

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ScrollingActivity.this,Registeractivity.class);
                startActivity(intent);
            }
        });
        recyclerView = findViewById(R.id.recyclerViewList);

        recyclerView.setLayoutManager(new linearlayoutmanager(this));
        recyclerView.addItemdecoration(new DividerItemdecoration(this,DividerItemdecoration.VERTICAL));

        usersAdapter = new UsersAdapter();

        fetchUsers();
    }

    public void fetchUsers(){
        apiInterface = apiclient.getRetrofitInstance().create(ApiInterface.class);
        Call<List<User>> call = apiInterface.getAllUsers();

        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call,Response<List<User>> response) {
                if (response.isSuccessful()){
                    List<User> users = response.body();
                    usersAdapter.setData(users);
                    usersAdapter.setonItemClickListener(ScrollingActivity.this);

                    recyclerView.setAdapter(usersAdapter);

                }
            }

            @Override
            public void onFailure(Call<List<User>> call,Throwable t) {
                Log.e("success",t.getLocalizedMessage());
            }
        });
    }

    @Override
    public void OnItemClick(int position) {
        Intent detailIntent = new Intent(this,DetailActivity.class);
        User clickedUser = mListe.get(position);

        detailIntent.putExtra(EXTRA_CREATOR_NOM,clickedUser.getNom());
        detailIntent.putExtra(EXTRA_CREATOR_PRENOM,clickedUser.getPrenom());
        detailIntent.putExtra(EXTRA_CREATOR_TEL,clickedUser.getTel());
        detailIntent.putExtra(EXTRA_CREATOR_EMAIL,clickedUser.getEmail());
        detailIntent.putExtra(EXTRA_CREATOR_ETABLISSEMENT,clickedUser.getEtablissement());
        detailIntent.putExtra(EXTRA_CREATOR_TYPE,clickedUser.getType());
        detailIntent.putExtra(EXTRA_CREATOR_ACTIVE,clickedUser.getActive());

        startActivity(detailIntent);
    }
}

适配器:

    public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.AdapterVH>{


    private List<User> userList;
    private Context context;
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        void OnItemClick(int position);
    }

    public void setonItemClickListener(OnItemClickListener listener){
        mListener = listener;
    }

    public UsersAdapter(){
    }

    public void setData(List<User> userList){
        this.userList = userList;
        notifyDataSetChanged();
    }
    @NonNull
    @Override
    public AdapterVH onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
        context = parent.getContext();
        return new UsersAdapter.AdapterVH(LayoutInflater.from(context).inflate(R.layout.item_list,parent,false));
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(@NonNull AdapterVH holder,int position) {
        User user = userList.get(position);

        String nom = user.getNom();
        String email = user.getEmail();
        String etab = user.getEtablissement();
        String active = user.getActive();
        String prenom = user.getPrenom();

        holder.txtNom.setText(nom);
        if (nom == null) {
            holder.txtNom.setText("Aucun Nom");
        }
        holder.txtEmail.setText(email);
        if (email == null) {
            holder.txtEmail.setText("Aucun Email");
        }
        holder.txtEttab.setText(etab);
        if (etab == null) {
            holder.txtEttab.setText("Aucun Etablissement");
        }
        holder.txtPrenom.setText(prenom);
        if (prenom == null) {
            holder.txtPrenom.setText("Aucun Prenom");
        }
        if (active == null) {
            holder.ActiveDesactive.setText(R.string.desact);
        }else {
            holder.ActiveDesactive.setText(R.string.activ);
        }
    }

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


    public class AdapterVH extends RecyclerView.ViewHolder{

        TextView txtNom;
        TextView txtPrenom;
        TextView txtEmail;
        TextView txtEttab;
        Button ActiveDesactive;

        public AdapterVH(@NonNull View itemView) {
            super(itemView);

            txtNom = itemView.findViewById(R.id.NomUser);
            txtPrenom = itemView.findViewById(R.id.PrenomUser);
            txtEmail = itemView.findViewById(R.id.EmailUser);
            txtEttab = itemView.findViewById(R.id.EtabUser);
            ActiveDesactive = itemView.findViewById(R.id.ActiveDesavtive);

            itemView.setonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null){
                        int positions = getAdapterPosition();
                        if (positions != RecyclerView.NO_POSITION){
                            mListener.OnItemClick(positions);
                        }
                    }
                }
            });
        }

    }
}

解决方法

您没有在ArrayList<User> mListe = new ArrayList<>();

中添加任何内容

您应该在执行任何操作之前添加值,

尝试

if (response.isSuccessful()){
                List<User> users = response.body();
                mListe.addAll(users);
                usersAdapter.setData(users);
                usersAdapter.setOnItemClickListener(ScrollingActivity.this);
                recyclerView.setAdapter(usersAdapter);
            }
,

您永远不会在mListe中填写任何内容。如果您搜索mListe.,则唯一的匹配项是mListe.get。您没有mListe.addmListe.addAll的调用。相反,您要做的是将响应中的列表直接设置到适配器中:

if (response.isSuccessful()){
    // Here is the error
    List<User> users = response.body();
    
    usersAdapter.setData(users);
    usersAdapter.setOnItemClickListener(ScrollingActivity.this);

    recyclerView.setAdapter(usersAdapter);
}

应采取以下措施:

  1. 从以前的任何内容中清除mListe
  2. 填充新内容;
  3. 将新数据设置为适配器。
if (response.isSuccessful()){
    mListe.clear();
    mListe.addAll(response.body());
    
    usersAdapter.setData(mListe);
}

我已从该if语句中删除了几行,并将其移至onCreate中。应该只调用它们一次,如果再次调用fetchUsers(),则设置相同的适配器并单击侦听器没有任何好处。

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...

    usersAdapter = new UsersAdapter();
    usersAdapter.setOnItemClickListener(this);
    recyclerView.setAdapter(usersAdapter);
 
    fetchUsers();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。