When I roll my listView I lose the checked checkboxes

1

This is a code from my adapter, in it I have a textview and 4 chekboxes. The problem is that I believe I have to save the status of my checkboxes, so as not to lose their data, because when I roll my list view my checkboxes uncheck them alone.

public class ListaFuncionarioAdapter extends BaseAdapter {
/*
   private Activity activity;
    private List<MeuItem> itens;

    public ListaFuncionarioAdapter(Activity activity, List<MeuItem> itens){
        this.activity = activity;
        this.itens = itens;
    }
*/
    private List<MeuItem> itens;

    FirebaseDatabase firebaseDatabase;
    DatabaseReference databaseReference;

    CheckBox chkSalManha, chkDoceManha, chkSalTarde, chkDoceTarde;
    private Context context;

    private List<QtdePaes> listQtdePaes = new ArrayList<QtdePaes>();
    private ArrayAdapter<QtdePaes> arrayAdapterQtdePaes;
    QtdePaes qtdePaesSelecionado;
    private List<Funcionario> listFuncionario;

    final QtdePaes qtdePaes = new QtdePaes();

    int salmanha = 0;
    int saltarde = 0;
    int docemanha = 0;
    int docetarde = 0;

    public ListaFuncionarioAdapter(Context context, List<Funcionario> listFuncionario) {
        this.context = context;
        this.listFuncionario = listFuncionario;
    }



    private void inicializarFirebase() {
        FirebaseApp.initializeApp(context);
        firebaseDatabase = FirebaseDatabase.getInstance();
       // firebaseDatabase.setPersistenceEnabled(true);
        databaseReference = firebaseDatabase.getReference();

        //DatabaseReference novaReference = firebaseDatabase.getReference();
       // novaReference = databaseReference.child("minh");

    }

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

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

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




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

        View v= View.inflate(context, R.layout.item_funcionario, null);

        chkSalManha = (CheckBox)v.findViewById(R.id.chkSalManha);
        chkDoceManha = (CheckBox)v.findViewById(R.id.chkDoceManha);
        chkSalTarde = (CheckBox)v.findViewById(R.id.chkSalTarde);
        chkDoceTarde = (CheckBox)v.findViewById(R.id.chkDoceTarde);
        TextView txtNome = (TextView)v.findViewById(R.id.txtNome);

        inicializarFirebase();
        txtNome.setText(String.valueOf(listFuncionario.get(position).getNome()));

        //MeuItem item = itens.get(position);

        //chkSalManha.setTag(item);
        //chkSalManha.setChecked(item.foiMarcado());
        v.setTag(listFuncionario.get(position).getUid());



        chkSalManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    salmanha += 1;
                    String estado = (String) chkSalManha.getTag();

                   // qtdePaes.setUid(UUID.randomUUID().toString());
                    qtdePaes.setQtdeSalManha(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    //databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);


                }
                if(!isChecked)
                {

                    salmanha -= 1;
                    //qtdePaes.setUid(qtdePaesSelecionado.getUid());
                    qtdePaes.setQtdeSalManha(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);


                }
            }
        });


        chkSalTarde.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    saltarde += 1;

                    //qtdePaes.setUid(UUID.randomUUID().toString());
                    qtdePaes.setQtdeSalTarde(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    //databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);

                }
                if(!isChecked)
                {

                    saltarde -= 1;
                    //qtdePaes.setUid(qtdePaesSelecionado.getUid());
                    qtdePaes.setQtdeSalTarde(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);


                }
            }
        });

        chkDoceManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){

                    docemanha += 1;

                    //qtdePaes.setUid(UUID.randomUUID().toString());
                    qtdePaes.setQtdeSalTarde(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    //databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);

                }
                if(!isChecked)
                {

                    docemanha -= 1;
                    //qtdePaes.setUid(qtdePaesSelecionado.getUid());
                    qtdePaes.setQtdeSalTarde(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);


                }
            }
        });

        chkDoceTarde.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    docetarde += 1;

                   // qtdePaes.setUid(UUID.randomUUID().toString());
                    qtdePaes.setQtdeSalTarde(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    //databaseReference.child("QtdePaes").child(qtdePaes.getUid()).setValue(qtdePaes);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);


                }
                if(!isChecked)
                {

                    docetarde -= 1;
                    //qtdePaes.setUid(qtdePaesSelecionado.getUid());
                    qtdePaes.setQtdeSalTarde(salmanha);
                    qtdePaes.setQtdeDoceManha(docemanha);
                    qtdePaes.setQtdeSalTarde(saltarde);
                    qtdePaes.setQtdeDoceTarde(docetarde);
                    databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);


                }
            }
        });



        return v;

    }


}
    
asked by anonymous 03.08.2017 / 01:38

3 answers

0

Each time the ListView needs to render an item / line it calls the getView() of adapter method.

In the implementation of this method the inflate of a new layout is done and its views are assigned their values.

This process is repeated as long as there are items in the list or the height of the ListView is filled.

When scroll , new layouts are "inflated" to the lower positions and those of the upper positions are discarded.

The process is identical when scroll is done in the opposite direction.

If you have checked any CheckBox in the meantime, this markup will be lost when its layout / item / line is discarded as a result of scroll .

So the solution is to save the checbox's state in the object that is used to populate the ListView and assign it to the CheckBox in the same way that the values are assigned to the other views . See here for an example.

Note: To make the process of creating new layouts more efficient consider using the View holder or an RecyclerView .

    
03.08.2017 / 13:24
0

The problem with the last condition does not have a else , so this ends up "interlacing" the items.

Instead of putting:

if(isChecked){
// conteúdo
}
if(!isChecked){
// conteúdo
}

Place:

if(isChecked){
// conteúdo
}else{
// conteúdo
}

This will ensure that CheckBox s is not cleared if checked.

    
03.08.2017 / 01:58
0

Assuming the amount of items in your ListView will not vary in size, so for simplicity, you can create a static 2-dimensional Boolean array on your adapter.

Ex:

private static boolean [][] checkBoxStates; // a primeira dimensão é a quantidade de itens da sua lista, a segunda dimensão, a quantidade de checkboxes por item

Initialize the array in the adapter constructor:

public ListaFuncionarioAdapter(Context context, List<Funcionario> listFuncionario) {
    this.context = context;
    this.listFuncionario = listFuncionario;
    checkBoxStates = new  boolean [listFuncionario.size()][];
    // supondo que o status inicial de todas as check boxes é desmarcado
    for(int i = 0; i < listFuncionario.size(); i++)
        checkBoxStates[i] = new boolean[]{false, false, false, false};
    }

}

Saving / retrieving checks status:

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

  ...
  // após associar os checkboxes com o findviewById
  chkSalManha.setChecked(checkBoxStates[position][0]);
  chkDoceManha.setChecked(checkBoxStates[position][1]);
  chkSalTarde.setChecked(checkBoxStates[position][2]);
  chkDoceTarde.setChecked(checkBoxStates[position][3]);

  ...
  // Guardando o estado nos listeners:
  chkSalManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkBoxStates[position][0] = isChecked;
                ...

            }


  chkDoceManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkBoxStates[position][1] = isChecked;
                ...

            }

  chkSalTarde.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkBoxStates[position][2] = isChecked;
                ...

            }

  chkDoceTarde.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                checkBoxStates[position][3] = isChecked;
                ...

            }
  ...

 }

And as already suggested, you can change the if-else code of your listeners in this way:

 chkSalManha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            checkBoxStates[position][1] = isChecked;

            if(isChecked)
                salmanha++;
            else
                salmanha--;
            }

            qtdePaes.setQtdeSalManha(salmanha);
            qtdePaes.setQtdeDoceManha(docemanha);
            qtdePaes.setQtdeSalTarde(saltarde);
            qtdePaes.setQtdeDoceTarde(docetarde);
            databaseReference.child("QtdePaes").child("6fd2aede-e00f-48d8-b6cb-f1498e23e8e8").setValue(qtdePaes);
        }
    });
    
03.08.2017 / 15:35