Problem with Android Arraylist

Asked

Viewed 155 times

0

I’m trying to create a listview with images and I’m getting this error and the app does not run.

Error stack

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.pedido.meu.telas_meu_pedido, PID: 5562
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.ArrayList.get(ArrayList.java:437)
        at com.pedido.meu.telas_meu_pedido.ItemAdapter.getView(ItemAdapter.java:54)
        at android.widget.AbsListView.obtainView(AbsListView.java:2373)
        at android.widget.ListView.makeAndAddView(ListView.java:2052)
        at android.widget.ListView.fillDown(ListView.java:786)
        at android.widget.ListView.fillFromTop(ListView.java:847)
        at android.widget.ListView.layoutChildren(ListView.java:1826)
        at android.widget.AbsListView.onLayout(AbsListView.java:2165)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:788)
        at android.view.View.layout(View.java:20680)
        at android.view.ViewGroup.layout(ViewGroup.java:6197)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2830)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2357)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1493)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7283)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6912)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
I/Process: Sending signal. PID: 5562 SIG: 9
Application terminated.

Listproductosactivity.java

package com.pedido.meu.telas_meu_pedido;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class ListaProdutosActivity extends AppCompatActivity {

    ItemAdapter adapter;
    ArrayList<Integer> idImages;
    ArrayList<String> nameList;

    int ids[] = {R.mipmap.ic_acai};

    String names[] = {"AÇAÍ"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista_produtos);
     //   String[] listaProdutos = {"Açaí", "Açaí", "Açaí", "Botijão de Gás", "Botijão de água", "Botijão de Gás", "Botijão de Gás", "Botijão de água", "Botijão de água"};
        ListView listView = findViewById(R.id.txListViewProdutos);

        idImages = new ArrayList<>();
        idImages = getList();
        nameList = new ArrayList<>();
        nameList = getNameList();
        adapter = new ItemAdapter(ListaProdutosActivity.this, idImages, nameList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ListaProdutosActivity.this, "Item Id Is" + nameList.get(position), Toast.LENGTH_SHORT).show();
            }
        });

 /*   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
   cria um objeto do tipo MenuInflater, o qual é responsável por criar objetos do tipo menu, a partir de um
   arquivo xml
        MenuInflater inflater = getMenuInflater();
        metodo que pega a referencia do arquivo xml e pega item por item e vai criando os MenuItem e adicionando no menu
        inflater.inflate(R.menu.activity_simple_list_view, menu);
        return super.onCreateOptionsMenu(menu);

    } */

    }

    public ArrayList<Integer> getList ()
    {
        idImages = new ArrayList<>();
        /*    idImages.add(R.drawable.java);
            idImages.add(R.drawable.php);
            idImages.add(R.drawable.csharp);
            idImages.add(R.drawable.android);
            idImages.add(R.drawable.js);
            idImages.add(R.drawable.html);
            idImages.add(R.drawable.css); */
        return idImages;
    }

    public ArrayList<String> getNameList () {
        nameList = new ArrayList<>();
        nameList.add("AÇAÍ");
     /*       nameList.add("JAVA");
            nameList.add("PHP");
            nameList.add("C SHARP");
            nameList.add("ANDROID");
            nameList.add("JAVASCRIPT");
            nameList.add("HTML 5");
            nameList.add("CSS 3"); */
        return nameList;
    }

}

Java image.

package com.pedido.meu.telas_meu_pedido;

public class Imagem
{
    private int imageId;
    private String imageName;

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }
}

Itemadapter.java

package com.pedido.meu.telas_meu_pedido;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.pedido.meu.telas_meu_pedido.R;

import java.util.ArrayList;

public class ItemAdapter extends BaseAdapter
{
    private Context context;
    private ArrayList<Integer> listaId;
    private ArrayList<String> listaNome;
    public ItemAdapter(Context context, ArrayList<Integer> listaId, ArrayList<String> listaNome)
    {
        this.context = context;
        this.listaId = listaId;
        this.listaNome=listaNome;
    }

    @Override
    public int getCount()
    {
        return listaNome.size();
    }

    @Override
    public Object getItem(int position)
    {
        return listaNome.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {

        if (convertView == null)
        {
            convertView = View.inflate(context, R.layout.list_item_produtos, null);
        }
        ImageView img = convertView.findViewById(R.id.imgListItemProduto);
        TextView tv =  convertView.findViewById(R.id.txtListItemProduto);
        img.setImageResource(listaId.get(position));
        tv.setText(listaNome.get(position));

        return convertView;
    }
}

activity_list_products.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    tools:context="com.pedido.meu.telas_meu_pedido.ListaProdutosActivity"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">


                    <!-- Título da tela -->
    <ImageView
        android:id="@+id/imgListaProdutos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_lista_produtos_round"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="30dp"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/txtTitleListaProdutos"
        android:textColor="@color/colorPrimary"
        android:layout_gravity="center"
        android:textStyle="bold"
        android:textSize="30dp"
        android:layout_marginBottom="20dp"
        />

                    <!-- Lista de produtos -->
        <ListView
            android:id="@+id/txListViewProdutos"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </ListView>

    </LinearLayout>


**list_item_produtos.xml**

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <ImageView
        android:id="@+id/imgListItemProduto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="38dp"
        android:layout_marginStart="38dp"
        android:layout_marginTop="25dp"
        android:src="@mipmap/ic_acai_round"
        />

    <TextView
        android:id="@+id/txtListItemProduto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/imgListItemProduto"
        android:layout_marginLeft="29dp"
        android:layout_marginStart="29dp"
        android:layout_marginTop="15dp"
        android:layout_toEndOf="@+id/imgListItemProduto"
        android:layout_toRightOf="@+id/imgListItemProduto"
        android:text="TextView"
        />
</RelativeLayout>

2 answers

2

You are setting the setImageResource with an int, your getList is not returning anything but an empty array.

While your getCount in your Adapter is taking into account the amount of listName.size(); note that the id array is empty, while the name list has 1 element.

Recommend you to upload dynamic images from the internet. Know Glide or Picasso? great lib to upload image;

    Glide.with(context)
            .load(listaNotificacoes.get(position).getUrlFotoPerfil())
            .into(imagemPerfil);

or direct link to the image for you to test there

    Glide.with(context)
            .load("https://i.imgur.com/SAVP4sO.jpg")
            .into(imagemPerfil);

0


As Leonardo mentioned above, the problem was in the code snippet below:

Listproductosactivity.java

 public ArrayList<Integer> getList ()
    {
        idImages = new ArrayList<>();
        /*    idImages.add(R.drawable.java);
            idImages.add(R.drawable.php);
            idImages.add(R.drawable.csharp);
            idImages.add(R.drawable.android);
            idImages.add(R.drawable.js);
            idImages.add(R.drawable.html);
            idImages.add(R.drawable.css); */
        return idImages;
    } 

I solved the problem by inserting the following code snippet (to insert the image I would like):

idImages.add(R.mipmap.ic_acai);

So the final code of the method is as follows::

 public ArrayList<Integer> getList ()
    {
        idImages = new ArrayList<>();
        idImages.add(R.mipmap.ic_acai);
        return idImages;
    }
  • good hehe, are small details that go unnoticed and give a headache

Browser other questions tagged

You are not signed in. Login or sign up in order to post.