attempt to display details in another Activity "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"

huangapple go评论60阅读模式
英文:

attempt to display details in another Activity "java.lang.IndexOutOfBoundsException: Index: 0, Size: 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)

以下是我的Activity代码

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);
                        }
                    }
                }
            });
        }
    }
}
英文:

I'm trying to use OnItemClick to display details in a user profile page and I still have this error:

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**)

Here is my Activity code

    public class ScrollingActivity extends AppCompatActivity implements UsersAdapter.OnItemClickListener {
public static final String EXTRA_CREATOR_NOM = &quot;Nom&quot;;
public static final String EXTRA_CREATOR_PRENOM = &quot;Prenom&quot;;
public static final String EXTRA_CREATOR_TEL = &quot;Tel&quot;;
public static final String EXTRA_CREATOR_EMAIL = &quot;Email&quot;;
public static final String EXTRA_CREATOR_ETABLISSEMENT = &quot;Etablissement&quot;;
public static final String EXTRA_CREATOR_TYPE = &quot;Type&quot;;
public static final String EXTRA_CREATOR_ACTIVE = &quot;Active&quot;;
RecyclerView recyclerView;
ApiInterface apiInterface;
UsersAdapter usersAdapter;
ArrayList&lt;User&gt; mListe = new ArrayList&lt;&gt;();
@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&lt;List&lt;User&gt;&gt; call = apiInterface.getAllUsers();
call.enqueue(new Callback&lt;List&lt;User&gt;&gt;() {
@Override
public void onResponse(Call&lt;List&lt;User&gt;&gt; call, Response&lt;List&lt;User&gt;&gt; response) {
if (response.isSuccessful()){
List&lt;User&gt; users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}
}
@Override
public void onFailure(Call&lt;List&lt;User&gt;&gt; call, Throwable t) {
Log.e(&quot;success&quot;, 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);
}
}

Adapter:

    public class UsersAdapter extends RecyclerView.Adapter&lt;UsersAdapter.AdapterVH&gt;{
private List&lt;User&gt; 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&lt;User&gt; 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(&quot;ResourceAsColor&quot;)
@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(&quot;Aucun Nom&quot;);
}
holder.txtEmail.setText(email);
if (email == null) {
holder.txtEmail.setText(&quot;Aucun Email&quot;);
}
holder.txtEttab.setText(etab);
if (etab == null) {
holder.txtEttab.setText(&quot;Aucun Etablissement&quot;);
}
holder.txtPrenom.setText(prenom);
if (prenom == null) {
holder.txtPrenom.setText(&quot;Aucun Prenom&quot;);
}
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);
}
}
}
});
}
}
}

答案1

得分: 0

你在 ArrayList&lt;User&gt; mListe = new ArrayList&lt;&gt;(); 这行代码中没有添加任何内容。

在执行任何操作之前,你应该先添加数值,

试试这个:

if (response.isSuccessful()){
    List&lt;User&gt; users = response.body();
    mListe.addAll(users);
    usersAdapter.setData(users);
    usersAdapter.setOnItemClickListener(ScrollingActivity.this);
    recyclerView.setAdapter(usersAdapter);
}
英文:

you are not adding anything in ArrayList&lt;User&gt; mListe = new ArrayList&lt;&gt;();

you should add values before implementing any action,

try this

if (response.isSuccessful()){
List&lt;User&gt; users = response.body();
mListe.addAll(users);
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}

答案2

得分: 0

你从未为mListe添加任何内容。如果你搜索mListe.,唯一的匹配项是mListe.get。你没有调用过mListe.add或者mListe.addAll。相反,你是直接将响应中的列表内容设置到适配器中:

if (response.isSuccessful()){
    // 这里是错误的地方
    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();
}
英文:

You never fill mListe with any content. If you search for mListe. the only match you get is mListe.get. You have no invocations of mListe.add or mListe.addAll. What you do instead is set a list from a response directly into the adapter:

if (response.isSuccessful()){
// Here is the error
List&lt;User&gt; users = response.body();
usersAdapter.setData(users);
usersAdapter.setOnItemClickListener(ScrollingActivity.this);
recyclerView.setAdapter(usersAdapter);
}

What should be done instead is the following:

  1. Clear mListe from any previous content;
  2. Fill with new content;
  3. Set new data to the adapter.
if (response.isSuccessful()){
mListe.clear();
mListe.addAll(response.body());
usersAdapter.setData(mListe);
}

I have removed a few lines from this if-statement and moved them into the onCreate. They should be called only once, there is no benefit setting the same adapter and click listener if you call fetchUsers() again.

@Override
protected void onCreate(Bundle savedInstanceState) {
...
usersAdapter = new UsersAdapter();
usersAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(usersAdapter);
fetchUsers();
}

huangapple
  • 本文由 发表于 2020年9月23日 23:00:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64030798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定