Android - Arraylist is not being filled

Asked

Viewed 57 times

0

I created a code with a contact class

public class Contato {
    private String nome;
    private Integer foto;
    private String ramal;
    private String setor;
    private String email;

    public Contato(String nome, Integer foto, String ramal, String setor, String email) {
        this.nome = nome;
        this.foto = foto;
        this.ramal = ramal;
        this.setor = setor;
        this.email = email;
    }

    public static Contato[] contatos = {
            new Contato("Fulano", R.drawable.fulano,"7145", "TI", "[email protected]"),
            new Contato("Ciclano", R.drawable.ciclano,"7144", "Comercial", "[email protected]"),
    };

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Integer getFoto() {
        return foto;
    }

    public void setFoto(Integer foto) {
        this.foto = foto;
    }

    public String getRamal() {
        return ramal;
    }

    public void setRamal(String ramal) {
        this.ramal = ramal;
    }

    public String getSetor() {
        return setor;
    }

    public void setSetor(String setor) {
        this.setor = setor;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

So I created another class where values are taken from a screen and should be sent to that Arraylist and when the button is pressed, updating the Recyclerview items.

public class CadastroFragment extends Fragment {

    View view;

    EditText newNome;
    EditText newRamal;
    EditText newEmail;

    String nome;
    String ramal;
    String email;
    String setor;
    String[] setoresSpinner;

    private Spinner setores;

    public CadastroFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_cadastro, container, false);

        newNome = view.findViewById(R.id.new_Nome);
        newEmail = view.findViewById(R.id.new_Email);
        newRamal = view.findViewById(R.id.new_Ramal);
        setores = view.findViewById(R.id.new_setor);

        setoresSpinner = getResources().getStringArray(R.array.sectors);
        setores.setAdapter(new ArrayAdapter<>(getContext(), R.layout.spinner_adapter, setoresSpinner));

        Button cadastrar = view.findViewById(R.id.new_cadastro);
        cadastrar.setOnClickListener(
                new View.OnClickListener(){
                    public void onClick(View view){
                        nome = newNome.getText().toString();
                        email = newEmail.getText().toString();
                        ramal = newRamal.getText().toString();
                        setor = setores.getSelectedItem().toString();

                        List<Contato> listaContato = new ArrayList<Contato>();
                        listaContato.add(new Contato(nome, R.drawable.logo, ramal, setor, email));
                    }
                }

        );

        return view;
    }

}

My Adapter:

public class MyFirstAdapter extends RecyclerView.Adapter<MyFirstAdapter.MyFirstViewHolder> {
    private List<Contato> contatoList;
    private MyOnItemClickListener myOnItemClickListener;
    private View itemView;

    @NonNull
    @Override
    public MyFirstViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, final int viewType) {
        itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.contatos_layout, viewGroup,false);
        itemView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
            if (myOnItemClickListener != null){
                TextView txt = view.findViewById(R.id.contato_nome);
                myOnItemClickListener.myOnItemClick(txt.getText().toString());
            }
            }
        });
        final MyFirstViewHolder holder = new MyFirstViewHolder(itemView);

        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                contatoList.remove(holder.position);
                notifyDataSetChanged();
                return true;
            }
        });


        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyFirstViewHolder myFirstViewHolder, final int position) {
            myFirstViewHolder.onBind(contatoList.get(position), position);
    }

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

    class MyFirstViewHolder extends RecyclerView.ViewHolder{
        ImageView contatoFoto;
        TextView contatoNome;
        TextView contatoRamal;
        TextView contatoEmail;
        TextView contatoSetor;
        int position;
        public MyFirstViewHolder(@NonNull View itemView) {
            super(itemView);

            contatoFoto = itemView.findViewById(R.id.contato_foto);
            contatoNome = itemView.findViewById(R.id.contato_nome);
            contatoRamal = itemView.findViewById(R.id.contato_ramal);
            contatoEmail = itemView.findViewById(R.id.contato_email);
            contatoSetor = itemView.findViewById(R.id.contato_setor);
        }

        public void onBind(Contato contato, int pos){
            position = pos;
            contatoNome.setText(contato.getNome());
            contatoRamal.setText(Html.fromHtml(contato.getRamal()));
            contatoFoto.setImageResource(contato.getFoto());
            contatoEmail.setText(contato.getEmail());
            contatoSetor.setText(contato.getSetor());
        }

    }

    public interface MyOnItemClickListener{
        void myOnItemClick(String nome);
    }


    public MyFirstAdapter(List<Contato> contatoList){
        this.contatoList = contatoList;
    }

    public void setMyOnItemClickListener(MyOnItemClickListener myOnItemClickListener){
        this.myOnItemClickListener = myOnItemClickListener;
    }
}

The problem is that my Recyclerview is not being updated, as if my code is not entering the new entries in Arraylist.

  • Hi friend.... I would like to help you but I need to see the full code of the class where you enter the data in your recyclerView.... Therefore, I ask you to re-edit with the full class code for my best understanding....

  • Note! I need to see the entire class where you enter the new data (The class of the button) and not the recyclerView Adapter

  • Updated with the whole class

  • Yeah, but how are you doing to set your list in recyclerView?

  • You are using adapter.notifyDataSetChanged(); after inserting a new item in recyclerView?

  • How can I set and where to use notifyDataSetChanged? I’m new to this and thought it was just creating a new contact that he would insert in the list. Prefer I upgrade with my Adapter?

  • So to create a recyclerView and insert data into it, you have to create a constructor, a constructor Adapter for recyclerView and a constructor list to configure in recyclerView’s Adapter.... I can’t teach you this here because it’s too much work, but you can search how to create a "recyclerView in Android Studio (if you use Android Studio)" on youtube. There’s a lot of tutoring there and you get the concept quickly....

  • Note! Recyclerview is ideal for setting up very large lists, as the responsibility assigned to it is much less than in a listview. However, if your application has a small list, use a listview instead of recyclerView, as this is much easier to handle.

  • An example of this is that in listview you can select an item from your list using the method setOnItemClickListiner and in recyclerView you will have to create an interface to be able to select an item from the list and this is much more work.

  • Recycler view is working, those two contacts appear, the problem is that when I use the button to insert new contacts, my recyclerview keeps showing only the old ones, it doesn’t update.

  • Take a look at my answer....

  • Ready..... Ruan

Show 7 more comments

1 answer

0

Take a look. I think the problem is that you were not making the list Adapter for recyclerView.

public class CadastroFragment extends Fragment {

    View view;

    EditText newNome;
    EditText newRamal;
    EditText newEmail;

    String nome;
    String ramal;
    String email;
    String setor;
    String[] setoresSpinner;

    private Spinner setores;

    /*

    Você precisa criar um Adapter para configurar a sua lista no seu recyclerView

    */

    private Adapter<MyFirstAdapter> adapter;
    private RecyclerView recyclerView;



    public CadastroFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_cadastro, container, false);

        List<Contato> listaContato = new ArrayList<Contato>(); //code:(1)

        //Recupere o devido ID do recyclerView e inicie o adapter. Veja abaixo;

        recyclerView = view.findViewById(R.id.seuRecyclerView);
        adapter = new MyFirstAdapter(getContext(),listaContato,CadastroFragment.this);
            //(Você instancia o adapter com os dois contatos pré definidos no seu costrutror)// 
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        newNome = view.findViewById(R.id.new_Nome);
        newEmail = view.findViewById(R.id.new_Email);
        newRamal = view.findViewById(R.id.new_Ramal);
        setores = view.findViewById(R.id.new_setor);

        setoresSpinner = getResources().getStringArray(R.array.sectors);
        setores.setAdapter(new ArrayAdapter<>(getContext(), R.layout.spinner_adapter, setoresSpinner));

        Button cadastrar = view.findViewById(R.id.new_cadastro);
        cadastrar.setOnClickListener(
                new View.OnClickListener(){
                    public void onClick(View view){
                        nome = newNome.getText().toString();
                        email = newEmail.getText().toString();
                        ramal = newRamal.getText().toString();
                        setor = setores.getSelectedItem().toString();

                        // Instacie a lista fora do envento de click. Veja lá em cima em code:(1)
                        listaContato.add(new Contato(nome, R.drawable.logo, ramal, setor, email));

                        adapter.notifyDataSetChanged();
                            //(Você atualiza seu adapter mostando o novo valor adcionado)//
                    }
                }

        );

        return view;
    }

}

[ADDED]

public class MyFirstAdapter extends RecyclerView.Adapter<MyFirstAdapter.MyFirstViewHolder> {


    private List<Contato> contatoList;
    private MyOnItemClickListener myOnItemClickListener;
    private View itemView;

    private Context mContext;
    private List<Constructor_Bula> mData ;
    private List<Constructor_Bula> mDataFiltered ;
    private ContactsAdapterListener listener;



    public interface ContactsAdapterListener {
        void onContactSelected(Constructor_Bula construtorBula);
    }

    MyFirstAdapter(Context mContext, List<Contato> mContatoList, ContactsAdapterListener listener) {
        this.mContext = mContext;
        this.contatoList = mContatoList;
        this.listener = listener;

    }


    @NonNull
    @Override
    public MyFirstViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, final int viewType) {

        itemView = LayoutInflater.from(mContext).inflate(R.layout.contatos_layout, viewGroup,false);
        itemView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
            if (myOnItemClickListener != null){
                TextView txt = view.findViewById(R.id.contato_nome);
                myOnItemClickListener.myOnItemClick(txt.getText().toString());
            }
            }
        });
        final MyFirstViewHolder holder = new MyFirstViewHolder(itemView);

        itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                contatoList.remove(holder.position);
                notifyDataSetChanged();
                return true;
            }
        });


        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyFirstViewHolder myFirstViewHolder, final int position) {
            myFirstViewHolder.onBind(contatoList.get(position), position);
    }

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

    class MyFirstViewHolder extends RecyclerView.ViewHolder{
        ImageView contatoFoto;
        TextView contatoNome;
        TextView contatoRamal;
        TextView contatoEmail;
        TextView contatoSetor;
        int position;
        public MyFirstViewHolder(@NonNull View itemView) {
            super(itemView);

            contatoFoto = itemView.findViewById(R.id.contato_foto);
            contatoNome = itemView.findViewById(R.id.contato_nome);
            contatoRamal = itemView.findViewById(R.id.contato_ramal);
            contatoEmail = itemView.findViewById(R.id.contato_email);
            contatoSetor = itemView.findViewById(R.id.contato_setor);
        }

        public void onBind(Contato contato, int pos){
            position = pos;
            contatoNome.setText(contato.getNome());
            contatoRamal.setText(Html.fromHtml(contato.getRamal()));
            contatoFoto.setImageResource(contato.getFoto());
            contatoEmail.setText(contato.getEmail());
            contatoSetor.setText(contato.getSetor());
        }

    }

    public interface MyOnItemClickListener{
        void myOnItemClick(String nome);
    }


    public MyFirstAdapter(List<Contato> contatoList){
        this.contatoList = contatoList;
    }

    public void setMyOnItemClickListener(MyOnItemClickListener myOnItemClickListener){
        this.myOnItemClickListener = myOnItemClickListener;
    }
}

You’ll need to modify your Adaper a little bit. In this case, you need to create a constructor to receive the context, list and event click on the item. But in the latter, it seems that you already do in the Adapter itself so just consider the first two....

Observe!!!

DO NOT CHANGE ANYTHING IN YOUR CLASS, DO THESE TESTS IN A SEPARATE CLASS, BECAUSE IF THE TEST DOES NOT WORK YOU WILL NOT LOSE WHAT YOU HAVE ALREADY DONE!!!

So I suggest that for these tests, create a class called MyFirstAdapter2.class and enter the respective code there and in the fragment install this test class....

  • When I create the private Adapter<Myfirstadapter> Adapter; it gives error "Cannot resolve Symbol Adapter

  • Strange, the private Adapter<Myfirstadapter> Adapter; says that the <Myfirstadapter> does not have type Parameters

Browser other questions tagged

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