immma immma - 6 days ago 8
Android Question

Checkedtextview check/uncheck after scroll Listview

I'm developing checkedtextview in listvew using viewHolder and getview. To populate check/uncheck status binding from database is running well. But, if I check item and then scroll listview, it will back to uncheck.

here is my customAdapter code.

public class CustomAdapter extends ArrayAdapter<Model> {
private Activity activity;
int id;
String autoid;
ArrayList<Model> items;
DatabaseHelper dbhelper = new DatabaseHelper(getContext());

public CustomAdapter(Activity context, int resource, ArrayList<Model> obj) {
super(context, resource, obj);

this.activity = context;
this.id = resource;
this.items = obj;

try {
dbhelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
}



static class ViewHolder {
protected CheckedTextView textView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh = null;

if (convertView == null) {

LayoutInflater inflater = activity.getLayoutInflater();
convertView = inflater.inflate(id, null);
vh = new ViewHolder();
convertView.setTag(vh);

vh.textView = (CheckedTextView) convertView.findViewById(R.id.textbox1);

}
else
{
vh = (ViewHolder) convertView.getTag();

}

final Model item = items.get(position);
String status = item.getStatus();

final Model check = getItem(position);

final ViewHolder finalVh = vh;

vh.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
autoid = item.getAutoid();

if (! finalVh.textView.isChecked()) {
finalVh.textView.setChecked(true);
}
else
{
finalVh.textView.setChecked(false);
}
}
});

vh.textView.setText(item.getDate() +". "+item.getInfo());
vh.textView.setChecked(Boolean.parseBoolean(status));

return convertView;
}}


Thanks in advance.

Answer

Thats because your list(items) which you passed has the old value.When you change the check status,update it to the list(items) which is populated to the listview.On Scroll the list view will load them items again, where it is getting the old value.

vh.textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        autoid = item.getAutoid();

        if (! finalVh.textView.isChecked()) {
            finalVh.textView.setChecked(true);
            item.setStatus("true")
        } else {
            finalVh.textView.setChecked(false);
            item.setStatus("false");
        }
        items.set(position, item);
    }
});
Comments