My listview items keep on repeating every time the page loads. I think there is an error in my adapter class. Please help. Thank you in advance.
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.rows, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.rows, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
//convertView.setTag(R.id.label, viewHolder.text);
//convertView.setTag(R.id.check, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}
I am filling the list with this function which i am calling in my fragment's onCreate method
private List getModel() {
list.clear();
for(int i=0;i<list1.size();i++){
String a=list1.get(i);
list.add(new Model(a));
}
return list;
}
This is my fragment class
public class VaccAdmin extends FragmentActivity implements OnItemClickListener{
private Database dbHelper;
private double x,y;
ListView listView;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
List<String> list1=new ArrayList<String>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.list);
dbHelper=new Database(this);
dbHelper.addVaccine();
listView = (ListView) findViewById(R.id.my_list);
String age = getIntent().getStringExtra("age");
System.out.println(age+"Ageinmo");
double ageinmo=Double.parseDouble(age);
if(ageinmo<=1.5){
x=0.0;
y=1.5;
} else if(ageinmo<=2.25){
x=1.75;
y=2.25;
} else if(ageinmo<=4.25){
x=3.5;
y=4.25;
}else if(ageinmo<=6.0){
x=4.5;
y=6.0;
}else if(ageinmo<=9.0){
x=6.25;
y=9.0;
}else if(ageinmo<=12.0){
x=9.25;
y=12.0;
}else if(ageinmo<=15.0){
x=12.25;
y=15.0;
}else if(ageinmo<=18.0){
x=15.25;
y=18.0;
}else if(ageinmo<=23.0){
x=18.25;
y=23.0;
}else if(ageinmo<=72.0){
x=36.25;
y=72.0;
}else if(ageinmo<=120.0){
x=72.25;
y=120.0;
}else if(ageinmo<=144.0){
x=120.25;
y=144.0;
}else if(ageinmo<=216.0){
x=144.25;
y=216.0;
}
list1=dbHelper.getVacNames(x, y);
int size=list1.size();
System.out.println("Size"+size);
adapter = new MyAdapter(this,getModel());
listView.setAdapter(null);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
TextView label = (TextView) v.getTag(R.id.label);
CheckBox checkbox = (CheckBox) v.getTag(R.id.check);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<Model> getModel() {
list.clear();
for(int i=0;i<list1.size();i++){
String a=list1.get(i);
list.add(new Model(a));
}
return list;
}
}
I believe this should be written outide convertview==null
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
Related
Hello i have a listview with checkbox, my problem is when i check the checkbox and scroll the list in checkchanged listener "ischecked" and "else" both execute i think while on scrolling when the the checked checkbox disappears it dont maintain its state
I want when i check the check box (ischecked) should call and when i uncheck the checkbox "else" should call.
Here is my Adapter class
public class NamesAdapter extends BaseAdapter {
private List<EmployeeModel> employeeModelList;
private Context context;
private EmployeeModel employeeModel;
private ListView listView;
public static String check = "stop";
public String name;
int ii;
int getPosition;
boolean isShowing = false;
public NamesAdapter(List<EmployeeModel> employeeModelList, Context context) {
this.employeeModelList = employeeModelList;
this.context = context;
}
#Override
public int getCount() {
return employeeModelList.size();
}
#Override
public Object getItem(int i) {
// return employeeModelList.get(i);
return employeeModelList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder=null;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.empname_listview_model, null);
viewHolder = new ViewHolder();
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(viewHolder);
convertView.setTag(R.id.checkBox, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Here we get the position that we have set for the checkbox using setTag.
// Set the value of checkbox to maintain its state.
//employeeModel = employeeModelList.get(position);
//name = employeeModel.getName();
getPosition = (Integer) buttonView.getTag();
employeeModelList.get(getPosition).setChecked(buttonView.isChecked());
if (isChecked){
//getPosition = finalViewHolder.checkbox.getId();
check="start";
Toast.makeText(context, "This is if", Toast.LENGTH_SHORT).show();
displayEmployeeNamesData();
}
else {
check="stop";
Toast.makeText(context, "This is else", Toast.LENGTH_SHORT).show();
}
}
});
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.checkbox.setText(employeeModelList.get(position).getName());
viewHolder.checkbox.setChecked(employeeModelList.get(position).isChecked());
return convertView;
}
public void displayEmployeeNamesData() {
NewEmployeeDBTable newEmployeeDBTable = new NewEmployeeDBTable(context);
SQLiteDatabase dataBase = newEmployeeDBTable.getWritableDatabase();
//the SQL command to fetched all records from the table
String sql = "SELECT eid FROM "
+ NewEmployeeDBTable.EmployeNameTable + " where ename='" + name + "'";
Cursor mCursor = dataBase.rawQuery(sql, null);
if (mCursor.moveToFirst()) {
do {
ii = mCursor.getInt(mCursor.getColumnIndex(NewEmployeeDBTable.eid));
}
while (mCursor.moveToNext());
}
mCursor.close();
}
private static class ViewHolder {
CheckBox checkbox;
}
}
}
OnCheckedChangeListener() will call when you click on CheckBox or when you call mCheckBox.setCheck(value) in code.
When you scroll on your ListView, the getView() method will call to recreate ListView row and inside your getView() you have call viewHolder.checkbox.setChecked(...) => OnCheckedChangeListener call
To solve it you can use setOnClickListener like
final EmployeeModel employee = employeeModelList.get(getPosition);
holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
employee.setChecked(!employee.isChecked());
}
});
viewHolder.checkbox.setChecked(employee.isChecked());
because OnClickListener() won't call when you call viewHolder.checkbox.setChecked(...)
i have two activities MainActivity and FilterActivity, in FilterActivity i created a listview with row(Textview,Checkbox) using Custom Adapter.
In the custom Adapter,i use Shared Preference to store the checkbox's state,see below code.
public class filterCustomAdapter extends ArrayAdapter<Application>
{
private final List<Application> list;
Context context;
Editor editor;
ViewHolder viewHolder;
private LayoutInflater inflater;
Set<String> set =new HashSet<String>();
public filterCustomAdapter(Context context, List<Application> list)
{
super(context, R.layout.fil_list_items, list);
this.context = context;
this.list = list;
inflater=LayoutInflater.from(context);
}
public int getCount()
{
return list.size();
}
public Application getItem(int position)
{
return list.get(position);
}
public long getItemId(int position)
{
return position;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
}
#SuppressLint("NewApi")
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
final Application item=list.get(position);
view = inflater.inflate(R.layout.fil_list_items, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.fil_txt);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
view.setTag(viewHolder);
/*else
{
viewHolder=(ViewHolder)convertView.getTag();
}*/
viewHolder.text.setText(list.get(position).getApp_name());
SharedPreferences settings = context.getSharedPreferences("data",Context.MODE_PRIVATE);
boolean Checked = settings.getBoolean(item.getApp_name(),true);
viewHolder.checkbox.setChecked(Checked);
viewHolder.checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#SuppressLint("NewApi")
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if(viewHolder.checkbox.isChecked()==true)
{
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean(item.getApp_name(),true).commit();
//set.add(list.get(position).getApp_name());
//settings.edit().putStringSet("selected_app_name",set);
}
else
{
SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
settings.edit().putBoolean(item.getApp_name(),false).commit();
//set.remove(list.get(position).getApp_name());
//settings.edit().putStringSet("selected_app_name",set);
}
}
});
return view;
}
}
I commented out some parts which is storing the name of selected item in set which is again stored in shared preference (which is not working either).
My question is, whenever i switch activities the checkboxes are randomly checked and unchecked. i am working with this matter for 4 hours with no luck. pls help. Thank you in advance.
Update : Here is my filterActivity Code:
public class FilterActivity extends Activity
{
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.filter);
listview = (ListView) findViewById(R.id.filter_item_list);
ArrayAdapter<Application> adapter = new filterCustomAdapter(this,getItems());
listview.setAdapter(adapter);
Intent i = getIntent();
String text=i.getStringExtra("activity");
}
private List<Application> getItems()
{
List<Application> list = new ArrayList<Application>();
list.add(get("Message"));
list.add(get("Mail"));
list.add(get("Reminder"));
list.add(get("Event"));
list.add(get("Contact"));
list.add(get("Application"));
list.add(get("Music"));
list.add(get("Video"));
list.add(get("Search Web"));
return list;
}
private Application get(String s)
{
return new Application(s,true,1);
}
}
i am calling this activity from MainActivity whenever a button is clicked.
Please have a look at this code and modify your code as well.
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}
I customize a listview with textview and a checkbox. Now i want when change check checkbox different old checked will unchecked ( In listview have only a item checked ). I don't have resolve. And now i need help !
Sorry. I speak English not good
Here ! Code in adapter
public class ListSongCheckDownloadAdapter extends ArrayAdapter<String>
implements OnCheckedChangeListener {
private ArrayList<String> listnameSong;
private Context context;
public SparseBooleanArray mCheckStates;
int layoutResourceId;
public ListSongCheckDownloadAdapter(Context context, int resource,
int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
this.context = context;
this.layoutResourceId = resource;
this.listnameSong = new ArrayList<String>(objects);
mCheckStates = new SparseBooleanArray(listnameSong.size());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewholder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.listsongdownload_layout, null);
viewholder = new ViewHolder();
viewholder.tvNameSong = (TextView) rowView
.findViewById(R.id.nameOfSong);
viewholder.cbChecked = (CheckBox) rowView
.findViewById(R.id.cbCheckSong);
rowView.setTag(viewholder);
} else {
viewholder = (ViewHolder) rowView.getTag();
}
viewholder.tvNameSong.setText(listnameSong.get(position));
viewholder.cbChecked.setTag(position);
viewholder.cbChecked.setChecked(mCheckStates.get(position, false));
viewholder.cbChecked.setOnCheckedChangeListener(this);
return rowView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
static class ViewHolder {
TextView tvNameSong;
CheckBox cbChecked;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
And here is Download Activity
public class DownloadAlbumActivity extends Activity implements
OnItemClickListener {
private ArrayList<String> nameSongInList;
private ArrayList<String> linkDownOfAlbum;
ListSongCheckDownloadAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.downloadalbum_layout);
nameSongInList = new ArrayList<String>();
linkDownOfAlbum = new ArrayList<String>();
Intent intent = getIntent();
nameSongInList = intent.getStringArrayListExtra("namesong");
linkDownOfAlbum = intent.getStringArrayListExtra("linkdown");
ImageButton btnChecked = (ImageButton) findViewById(R.id.btnChecked);
ListView lvAdapter = (ListView) findViewById(R.id.lvSongOfAlbum);
lvAdapter.setItemsCanFocus(false);
adapter = new ListSongCheckDownloadAdapter(DownloadAlbumActivity.this,
R.layout.listsongdownload_layout, R.id.tvNameSong,
nameSongInList);
lvAdapter.setAdapter(adapter);
btnChecked.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String result = "";
for (int i = 0; i < adapter.mCheckStates.size(); i++) {
if (adapter.mCheckStates.get(i) == true) {
result = linkDownOfAlbum.get(i).toString();
}
}
Toast.makeText(DownloadAlbumActivity.this, result,
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
adapter.toggle(position);
}
}
You could save the ID of the currently checked item in a variable. Then, when another item is checked (inside the listener) you simply uncheck the old one and change the variable to the new ID.
i have created a listview with checkbox,edittext and textview.
data is populated in listview with sql server. but i am not being able to use onCheckedChangedListener on checkbox. so that on clicking the checkbox corresponding data of textview and edittext is not being saved..
i know i am doing mistake somewhere in my adapter class..
How to save data and what logic should i use in onCheckedChangedListener in my adapter class?
code for pojo class
public class Model {
public String name="";
public boolean selected=false;
public String score="";
public Model(String name) {
this.name = name;
selected = false;
score="";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
code for Adapter class
public class MyAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public MyAdapter(Activity context, List<Model> list)
{
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
protected EditText scores;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
if (convertView == null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);
viewHolder.scores.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count) {
Model element=(Model)viewHolder.scores.getTag();
element.setScore(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
public void afterTextChanged(Editable s)
{
}
});
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
viewHolder.checkbox.setTag(list.get(position));
viewHolder.scores.setTag(list.get(position));
view.setTag(viewHolder);
}
else
{
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
((ViewHolder) view.getTag()).scores.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.scores.setText(list.get(position).getScore());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
code for MainActivity class
public class MainActivity extends Activity {
ListView listView;
Button btnSave;
Connection connect;
ArrayAdapter<Model> adapter;
MyConnection mycon;
List<Model> list = new ArrayList<Model>();
List<String>data=new ArrayList<String>();
List<String>data2=new ArrayList<String>();
StringBuilder sb;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mycon=new MyConnection(getApplicationContext());
listView = (ListView) findViewById(R.id.my_list);
btnSave = (Button)findViewById(R.id.btnSave);
sb=new StringBuilder();
adapter = new MyAdapter(this,getModel());
listView.setAdapter(adapter);
if(list.isEmpty()){
Toast.makeText(getApplicationContext(), "kuldeep", Toast.LENGTH_LONG).show();
}
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
Toast.makeText(getBaseContext(), "Name : "+list.get(i).getName() +" Selected: "+list.get(i).isSelected()+"address: "+list.get(i).getScore().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
private List<Model> getModel() {
list.clear();
try{
Statement smt=mycon.connection().createStatement();
ResultSet rs=smt.executeQuery("WORKINGTYPE");
while(rs.next()){
list.add(new Model(rs.getString("FIELD_NAME")));
}
}catch(Exception e){
e.printStackTrace();
}
/* list.add(new Model("kuldeep"));
list.add(new Model("sandeep"));
list.add(new Model("ravi"));
list.add(new Model("pradeep"));
list.add(new Model("praveena"));
list.add(new Model("ruchi"));
list.add(new Model("vikas"));
list.add(new Model("sonu"));
list.add(new Model("ashu"));
*/
return list;
}
}
for saving data of textview and EditText what logic should i use and where in Adapter clss i should write it..
May not be a solution, but a suggestion.
Prefer not to declare your Listeners inside an 'if' condition. What I meant is,
IF convertview == null
find views
ELSE
getTag()
Rest of the codes
Is it that your checkbox event is not firing?
I use setOnClickListener for my Checkbox events:
CheckBox checkbox = (CheckBox)view.findViewById(R.id.item_checkbox);
checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Mark model as selected/not selected
if (model.isSelected())
model.markAsNotSelected();
else
model.markAsSelected();
}
});
I know it's an old question, but if anyone else is facing same problem, replace the Adapter class with the following code.
public class MyAdapter extends ArrayAdapter<Model> implements TextWatcher{
private final List<Model> list;
private final Context context;
public MyAdapter(Context context, List<Model> list)
{
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
protected EditText scores;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder = null;
if (convertView == null){
LayoutInflater inflator = LayoutInflater.from(context);
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.scores=(EditText) view.findViewById(R.id.txtAddress);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox.setTag(list.get(position));
viewHolder.scores.setTag(list.get(position));
convertView.setTag(viewHolder);
}
else
{
convertView = (ViewHolder) convertView.getTag();
}
viewHolder.scores.addTextChangedListener(this)
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Model element = (Model) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.scores.setText(list.get(position).getScore());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Model element=(Model)viewHolder.scores.getTag();
element.setScore(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
}
I check all topic with similar problem, but I stil stay in deadpoint. I have a listview with contact list, but when i scroll down and scroll up listview don't save a state of my choices. All checkboxes was setting on false. When i debug i see, when i scrolled listview, my onClickListener thinking that checkbox was signed and reset this. I do everything, other array with position boolean, etc etc and I still don't know what to do :( I will be very gratefull for any help:)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
readContacts();
Contact_Database dbhandler = new Contact_Database(
getApplicationContext(), null, null, 1);
numbers.addAll( dbhandler.getAllNumbers());
System.out.println("onCreate");
ListView lv = getListView();
registerForContextMenu(lv);
lv.setTextFilterEnabled(true);
lv.clearChoices();
MyAdapter adapter = (new MyAdapter(this, R.layout.contact_list_sms, contacts));
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
/**
* When I destroy intent i send request to database, faster!
*/
#Override
protected void onDestroy() {
super.onDestroy();
for (int i = 0; i < numbers.size(); ++i)
System.out.println("####" + numbers.get(i));
swap_contacts();
}
class MyAdapter extends ArrayAdapter<Contact> {
LayoutInflater inflat;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<Contact> objects) {
super(context, textViewResourceId, objects);
inflat = LayoutInflater.from(context);
System.out.println("LOLLLLL");
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return (position == this.getCount() - 1) ? 1 : 0;
}
#Override
public int getViewTypeCount() {
return 2;
}
// if that contact exist in database? numbers, in onCreate method
// i init this with saved position from databse
private boolean exist(String x) {
for (int i = 0; i < numbers.size(); i++)
if (numbers.get(i).compareTo(x) == 0)
return true;
return false;
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("ROWS !!! ->" + numbers.size());
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflat.inflate(R.layout.contact_row, null);
holder.textView1 = (TextView) convertView
.findViewById(R.id.name);
holder.textView2 = (TextView) convertView
.findViewById(R.id.number);
holder.on_off = (CheckBox) convertView
.findViewById(R.id.enable);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Contact it = contacts.get(position);
Log.v("XXX", holder.toString());
if (it != null) {
holder.textView1.setText(contacts.get(position).name);
holder.textView2.setText(contacts.get(position).phone);
// update state of checbox from database
if (exist(contacts.get(position).phone))
holder.on_off.setChecked(true);
else
holder.on_off.setChecked(false);
}
final int element_position = position;
holder.on_off
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// update list when we click on it
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
String nr_telefonu = contacts.get(element_position).phone;
if (isChecked) {
numbers.add(nr_telefonu);
} else {
numbers.remove(nr_telefonu);
}
}
});
return convertView;
}
#Override
public Contact getItem(int position) {
return contacts.get(position);
}
private class ViewHolder {
TextView textView1, textView2;
CheckBox on_off;
public String toString() {
return "-";
}
}
}
List does not save it state while scrolling , because each time new object is created for row item. So you need to explicitly save the state of CheckBox with help of Pojo class(Setter and getter).
in getView() method you need to check the value for each checkbox.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
////////////////////
and on setOnCheckedChangeListener you need to save the state of checkbox
holder.on_off
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// update list when we click on it
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// need to save the state
for more details please refer to this below blog
http://amitandroid.blogspot.in/2013/03/android-listview-with-checkbox-and.html
you can change it according to your requirement.
Thank's for answer :) I create a array stan with state for every checkbox button. Tommorrow i will try rebuild all my class like the list on the blog, mayby this help me.
But when I do this :
save state:
holder.on_off
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
// update list when we click on it
// this.setChecked(stan[position]);
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
String nr_telefonu = p.get(element_position).phone;
buttonView.setChecked(stan[element_position]);
stan[element_position] = isChecked;
}
});
Refresh state of button
if (it != null) {
holder.textView1.setText(contacts.get(position).name);
holder.textView2.setText(contacts.get(position).phone);
// update state of checbox from database
holder.on_off.setChecked(stan[position]);
}
I still stand In dead point, nothing is changed
I've posted the solution to this problem below which I spent a lot of time finding and it works for me!
public class RowAdapter extends ArrayAdapter<Rows> {
Context context;
int layoutResourceId;
ArrayList<Rows> data;
boolean[] checkBoxState;
RowHolder rowHolder;
public RowAdapter(Context context, int layoutResourceId, ArrayList<Rows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
checkBoxState = new boolean[data.size()];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
RowHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RowHolder();
holder.textView1 = (TextView)row.findViewById(R.id.textView1);
holder.textView2 = (TextView)row.findViewById(R.id.textView2);
holder.textView3 = (TextView)row.findViewById(R.id.textView3);
holder.textView4 = (TextView)row.findViewById(R.id.textView4);
holder.checkBox=(CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(holder);
}
else{
holder = (RowHolder)row.getTag();
}
Rows rows = data.get(position);
holder.textView1.setText(rows.address);
holder.textView2.setText(rows.tenancy);
holder.textView3.setText(rows.location);
holder.textView4.setText(rows.name);
holder.checkBox.setChecked(checkBoxState[position]);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked())
checkBoxState[position]=true;
else
checkBoxState[position]=false;
}
});
return row;
}
static class RowHolder
{
TextView textView1;
TextView textView2;
TextView textView3;
TextView textView4;
CheckBox checkBox;
}
}