Julien M
Julien M

Reputation: 11

Listview and checkbox problem Android Studio

I am using a SQLite database for an android studio application and I am using a ListView to display data. I recently put a CheckBox (without adding anything in the database) and the problem I have is that when I check a box and go down in the ListView (I specify that it does me when I I have a lot of item in the list) my box is unchecked or either boxes are randomly checked.

here is my code in Adapter:

 @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        //déclaration d"un horlder
        final ViewHolder holder;
        // si la ligne n'existe pas encor
        if(view == null) {
            holder = new ViewHolder();
            // la ligne est construite avec un formatage (inflater) relié à layoutlistpremierp
            view = inflater.inflate(R.layout.layoutlistsacview, null);
            //chaque propriété du holder est relié a une propriété graphique
            holder.checksac = (CheckBox) view.findViewById(R.id.checksac);
            // affceter le holder à la vue
            view.setTag(holder);
        }else{
            //récup du holder dans la ligne existante
            holder = (ViewHolder) view.getTag();
        }
        // valorisation du contenu du holder (donc de la ligne)
        holder.checksac.setText(LesAjoutSac.get(i).getObjetSac());



        return view;
    }

    private class ViewHolder{
        CheckBox checksac;
    }

how can i fix it?

Upvotes: 1

Views: 69

Answers (2)

Sharone Lev
Sharone Lev

Reputation: 841

You need to keep a list with the data for each row that will save the status of the checkbox, and on the adapter you mark checkbox.isChecked = list[position].isChecked You then need to add a listener to the chceckBox to mark the data in the list list[position]..isChecked = isChecked //isChecked comed from the listener

You can see my example here, but it uses a recyclerView (which I highly recommend over a listView!)

Upvotes: 1

javdromero
javdromero

Reputation: 1937

Add this in your adapter:

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

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

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

Upvotes: 0

Related Questions