I am creating a custom listview item with a textview and a check box. Whenever the checkbox of corresponding to a user is selected, I would like to see his name in a toast. I have used the following code :
mUserList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(ManualInviteActivity.this, position, Toast.LENGTH_SHORT).show();
Users1 user = (Users1) parent.getItemAtPosition(position);
if(user.isSelected()==true)
{
Toast.makeText(getBaseContext(), user.getName(), Toast.LENGTH_SHORT).show();
}
}
});
I don't see anything however, when I toggle the check box. What is the mistake here ?
Thanks
(isSelected and getName are my own functions in the user class)
Adapter Code :
public class UserListAdapter extends ArrayAdapter<Users1> {
static Context context;
static int layoutResourceId;
Users1 data[] = null;
public UserListAdapter(Context context, int layoutResourceId, Users1[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public long getItemId(int position) {
return position;
}
static class UserHolder {
TextView txtTitle;
CheckBox cbxUser;
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.user_name);
holder.cbxUser = (CheckBox) row.findViewById(R.id.user_checked);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
Users1 weather = data[position];
holder.txtTitle.setText(weather.title);
holder.cbxUser.setChecked(weather.isSelected());
// holder.txtTitle2.setText(weather.title2);
// holder.txtTitle2.setText(weather.title2);
// holder.txtTitle3.setText(weather.title3);
return row;
}
}
Users1 class :
public class Users1 {
public String title;
boolean selected = true;
public Users1()
{
super();
}
public Users1(String title,boolean selected) {
super();
this.selected = selected;
this.title = title;
}
public String getName() {
return title;
}
public void setName(String name) {
this.title = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
You need to use onCheckedStateChange for Check box.
You need to set a listener to your RadioGroup (not to your list).
Something like this:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
OnCheckedChangeListener OCCL = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio1:
//...
break;
case R.id.radio2:
//...
break;
case R.id.radio3:
//...
break;
default:
break;
}
}
};
radioGroup.setOnCheckedChangeListener(OCCL);
holder.checkbox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Toast.makeText(getBaseContext(), user.getName(), Toast.LENGTH_SHORT).show();
}
});
try this code
public class Customadapter extends BaseAdapter {
Context context;
ArrayList<String> names;
LayoutInflater inflater;
public Customadapter(Context context, ArrayList<String> names) {
this.names = names;
this.context = context;
inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return names.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public class Holder {
TextView name;
CheckBox check;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
final Holder holder;
if(convertView==null)
{
holder=new Holder();
convertView=inflater.inflate(R.layout.checkbox,null);
holder.name=(TextView) convertView.findViewById(R.id.textView1);
holder.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.check.setId(position);
}
else
{
holder=(Holder) convertView.getTag();
}
holder.name.setText(names.get(position));
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,""+names.get(holder.check.getId()),Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
Related
UPDATE WITH VIEW HOLDER
public class DatabaseListAdapter extends BaseAdapter {
Context context;
ArrayList<DatabaseListItems> databaseList;
ArrayList<String> DeleteList = new ArrayList<>();
static class ViewHolder {
TextView tvFirstName;
TextView tvSecondName;
View row;
}
public DatabaseListAdapter(Context context, ArrayList<DatabaseListItems> list) {
this.context = context;
databaseList = list;
}
#Override
public int getCount() {
return databaseList.size();
}
#Override
public Object getItem(int position) {
return databaseList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final DatabaseListItems databaseListItems = databaseList.get(position);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_listview_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvFirstName = (TextView) rowView.findViewById(R.id.txtViewFirstName);
viewHolder.tvSecondName = (TextView) rowView.findViewById(R.id.txtViewSecondName);
viewHolder.row = rowView.findViewById(R.id.row);
rowView.setTag(viewHolder);
}
final ViewHolder holder = (ViewHolder) rowView.getTag();
holder.tvFirstName.setText(databaseListItems.getFirstName());
holder.tvSecondName.setText(databaseListItems.getSecondName());
if (databaseListItems.getFirstRow() == true) {
holder.tvSecondName.setAlpha(0.0f);
holder.tvFirstName.setTextColor(Color.parseColor("#161616"));
holder.row.setBackgroundColor(Color.parseColor("#f7f7f7"));
holder.row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,OtherActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
} else {
holder.tvSecondName.setAlpha(1.0f);
}
}
return rowView;
}
}
in my android app, i have got an custom table list, where the data will be dynamic filled.
only the first row should a an static row, which i set programmatically.
i have this function to fill my data into the list
private void showList() {
boolean FirstRow = true;
ArrayList<DatabaseListItems> databaseList = new ArrayList<>();
databaseList.clear();
String query = "SELECT * FROM " + DatabaseHelper.DATABASE_TABLE;
Cursor c1 = dbHandler.selectQuery(query);
if (c1.moveToFirst()) {
do {
DatabaseListItems databaseListItems = new DatabaseListItems();
if (c1.getPosition() == 0 && FirstRow == true) {
databaseListItems.setFirstRow(true);
FirstRow = false;
databaseListItems.setFirstName("FIRST ROW");
databaseListItems.setSecondName(null);
c1.moveToPosition(-1);
} else {
databaseListItems.setFirstRow(false);
FirstRow = false;
databaseListItems.setFirstName(c1.getString(c1.getColumnIndex(DatabaseHelper.COLUMN_FIRSTNAME)));
databaseListItems.setSecondName(c1.getString(c1.getColumnIndex(DatabaseHelper.COLUMN_SECONDNAME)));
}
databaseList.add(databaseListItems);
} while (c1.moveToNext());
}
c1.close();
DatabaseListAdapter databaseListAdapter = new DatabaseListAdapter(getActivity(), databaseList);
ListView.setAdapter(databaseListAdapter);
}
DatabaseListItems
public class DatabaseListItems {
String firstname;
String secondname;
Boolean FirstRow;
public String getFirstName() {
return firstname;
}
public void setFirstName(String first name) {
this.firstname= firstname;
}
public String getSecondName() {
return secondname;
}
public void setSecondName(String secondname) {
this.secondname = secondname;
}
public Boolean getFirstRow() {
return FirstRow;
}
public void setFirstRow(Boolean FirstRow) {
this.FirstRow = FirstRow;
}
}
DatabaseListAdapter
public class DatabaseListAdapter extends BaseAdapter {
Context context;
ArrayList<DatabaseListItems> databaseList;
ArrayList<String> DeleteList = new ArrayList<>();
public DatabaseListAdapter(Context context, ArrayList<DatabaseListItems> list) {
this.context = context;
databaseList = list;
}
#Override
public int getCount() {
return databaseList.size();
}
#Override
public Object getItem(int position) {
return databaseList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
final DatabaseListItems databaseListItems = databaseList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_listview_item, null);
}
TextView tvFirstName = (TextView) convertView.findViewById(R.id.txtViewFirstName);
tvFirstName.setText(databaseListItems.getFirstName());
TextView tvSecondName = (TextView) convertView.findViewById(R.id.txtViewSecondName);
tvSecondName.setText(databaseListItems.getSecondName());
View row = convertView.findViewById(R.id.row);
ImageView Arrow = (ImageView) convertView.findViewById(R.id.Arrow);
// First Static Row
if (databaseListItems.getFirstRow() == true) {
tvSecondName.setAlpha(0.0f);
Arrow.setAlpha(1.0f);
tvFirstName.setTextColor(Color.parseColor("#161616"));
row.setBackgroundColor(Color.parseColor("#f7f7f7"));
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,OtherActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
} else {
tvSecondName.setAlpha(1.0f);
Arrow.setAlpha(0.0f);
}
return convertView;
}
}
On the first view, all looks fine.
but if i scroll down and up, random rows get the background color and the onClick function , which only the first row should get.
anyone an idea what i do wrong?
In the following code
here is my main Activity Where i choose various product and proceed further
but when I checked multiple or one it pass 0 value;
that is in Toast I am not getting anything as below in image
public class MainActivity extends ListActivity {
ListView list;
Button btn1;
String url="";
private ArrayList <Product> allProducts = new ArrayList<Product>();
private ProductAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
btn1 = (Button) findViewById(R.id.btn);
list = getListView();
url="http://192.168.1.100/test/product.txt?id=";//+d.getInt("id");
try{
ConnectivityManager c =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo n =c.getActiveNetworkInfo();
if (n!= null && n.isConnected()){
Log.d("url*********",url);
new Background().execute(url);
}
}catch(Exception e){}
adapter = new ProductAdapter(this,allProducts);
setListAdapter(adapter);
getListView().setItemsCanFocus(false);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
for(int i=0;i<allProducts.size();i++){
Product product = allProducts.get(i);
if(product.isChecked()){
responseText.append("\n" + product.getProduct_name());
}
}
Toast.makeText(getApplicationContext(),
responseText, Toast.LENGTH_LONG).show();
}
});
}
Here is ProductAdapter
public class ProductAdapter extends ArrayAdapter<Product> {
ArrayList<Product> allProducts;
LayoutInflater vi;
int Resource;
Context context;
public ProductAdapter (Context context ,ArrayList<Product> objects)
{
super(context, R.layout.productrow, objects);
allProducts = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(R.layout.productrow, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.price);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb1);
int s = allProducts.get(position).getProduct_price();
name.setText(Integer.toString(s));
cb.setText(allProducts.get(position).getProduct_name());
if(allProducts.get(position).isChecked())
cb.setChecked(true);
else
cb.setChecked(false);
return convertView;
}
}
My Product.java file which is my model
public class Product {
int product_id;
private boolean checked = false ;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
String product_name;
int product_price;
int product_qunatity;
int hotel_id;
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_price() {
return product_price;
}
public void setProduct_price(int product_price) {
this.product_price = product_price;
}
public int getProduct_qunatity() {
return product_qunatity;
}
public void setProduct_qunatity(int product_qunatity) {
this.product_qunatity = product_qunatity;
}
public int getHotel_id() {
return hotel_id;
}
public void setHotel_id(int hotel_id) {
this.hotel_id = hotel_id;
}
}
Img Of screen Shot
Ok, there is declaration of checkbox CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb1); but where is the listener?
I assume you need to add listener:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//your code goes here
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(TAG, "Entered onCheckedChanged()");
//other stuff for listener
}
});
}
I am android developer, I have a custom listview with a checkbox. This layput also contain a delete button. I want when I click on cheakbox all the item in a particular row is selected and on click of delete it is deleted.
The problem is when I click on delete button I get a list of +1 row value.
Initially I already define :
int position=0;
btmsgdelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("request send for message delete");
for(Message msg:almsg) {
if(msg.isSelected()) {
CheckBox chk = (CheckBox)findViewById(R.id.checkBox1);
System.out.println("msg is selected");
msgid=almsg.get(position).getEmpid();
System.out.println(msgid);
empname=almsg.get(position).getEmpname();
System.out.println(empname);
msgheader=almsg.get(position).getHeader();
System.out.println(msgheader);
}
}
Try this sample code
public class MainActivity extends Activity {
private int textViewResourceId;
private ArrayList<CompareListData> searchResults;
private ListView lst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchResults = GetSearchResults();
lst = (ListView) findViewById(R.id.list);
findViewById(R.id.delete).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < searchResults.size(); i++) {
if (searchResults.get(i).getSelected()) {
searchResults.remove(i);
}
}
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
});
System.out.println("size " + searchResults.size());
lst.setAdapter(new Adapter(MainActivity.this, textViewResourceId,
searchResults));
}
private ArrayList<CompareListData> GetSearchResults() {
ArrayList<CompareListData> results = new ArrayList<CompareListData>();
CompareListData sr1 = new CompareListData();
sr1.setName("John Smith");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Jane Doe");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Steve Young");
results.add(sr1);
sr1 = new CompareListData();
sr1.setName("Fred Jones");
results.add(sr1);
return results;
}
}
CompareListData.java
public class CompareListData {
String name;
boolean selected;
public String getName() {
return name;
}
public void setName(String Name) {
name = Name;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
Adapter.java
public class Adapter extends BaseAdapter{
public static int count = 0;
public LayoutInflater inflater;
public static ArrayList<CompareListData> selectedId;
public ArrayList<CompareListData> listObjects;
Context contex;
public Adapter(Context context, int textViewResourceId,
ArrayList<CompareListData> objects) {
super();
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listObjects = objects;
this.contex = context;
}
public static class ViewHolder
{
TextView txtViewLoanName;
CheckBox chkSelected;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if(convertView==null)
{
final ViewHolder holder = new ViewHolder();
view = inflater.inflate(R.layout.row_comparelist, null);
holder.txtViewLoanName= (TextView) view.findViewById(R.id.rowcomparelist_tv_loanname);
holder.chkSelected= (CheckBox) view.findViewById(R.id.rowcomparelist_chk_selected);
holder.chkSelected.setId(position);
holder.chkSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CompareListData element = (CompareListData) holder.chkSelected.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(holder);
holder.chkSelected.setTag(listObjects.get(position));
}
else{
view = convertView;
((ViewHolder) view.getTag()).chkSelected.setTag(listObjects.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.txtViewLoanName.setText(listObjects.get(position).getName());
holder.chkSelected.setChecked(listObjects.get(position).getSelected());
return view;
}
public int getCount() {
return listObjects.size();
}
public Object getItem(int position) {
return listObjects.get(position);
}
public long getItemId(int position) {return position;
}
}
I have a list, in which each row contains a checkbox and a textview, also I have a button which should check/uncheck all checkboxes in the list, however, I have not been able to achieve this with the checkboxes OUTSIDE of the screen, only with the visibles one. And if I understood well, that happens because items outside of the screens dont exist, they are recycled to create the new rows while scrolling, causing null pointers/out of index errores while trying to check/access the checkboxes outside of the screen.
I Googled for solutions but nothing worked so far.
How can I solve this?
Here is the adapter:
public class AlumnoArrayAdapter<T> extends BaseAdapter{
Context mContext;
LayoutInflater mInflater;
ArrayList<T> mList;
ArrayList<Alumno> alumno;
boolean verEstadisticas;
SparseBooleanArray mSparseBooleanArray;
public AlumnoArrayAdapter(Context context, ArrayList<T> list, ArrayList<Alumno> alumno, boolean verEstadisticas) {
//TODO Auto-generated constructor stub
this.alumno = alumno;
this.verEstadisticas = verEstadisticas;
this.mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<T>();
this.mList = list;
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for(int i=0;i<mList.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
public int getCount() {
return mList.size();
}
public Object getItem(int position) {
return mList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
tvTitle.setText(mList.get(position).toString());
CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.chkEnable);
mCheckBox.setTag((Integer) position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
if(verEstadisticas){
mCheckBox.setVisibility(View.GONE);
}
mCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Integer position = (Integer) cb.getTag();
alumno.get(position).setChecked(cb.isChecked());
}
});
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
};
}
If more code is needed please let me know.
Would appreciate any help possible.
Thanks in advance!
EDIT: Got a solution!, the modified adapter:
public class AlumnoArrayAdapter<T> extends BaseAdapter{
Context mContext;
LayoutInflater mInflater;
ArrayList<T> mList;
ArrayList<Alumno> alumno;
boolean verEstadisticas;
SparseBooleanArray mSparseBooleanArray;
boolean checarTodo = false;
public AlumnoArrayAdapter(Context context, ArrayList<T> list, ArrayList<Alumno> alumno, boolean verEstadisticas) {
//TODO Auto-generated constructor stub
this.alumno = alumno;
this.verEstadisticas = verEstadisticas;
this.mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<T>();
this.mList = list;
}
public ArrayList<T> getCheckedItems() {
ArrayList<T> mTempArry = new ArrayList<T>();
for(int i=0;i<mList.size();i++) {
if(mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
public int getCount() {
return mList.size();
}
public Object getItem(int position) {
return mList.get(position);
}
public long getItemId(int position) {
return position;
}
public void checkAll(){
for(int x = 0; x < alumno.size(); x++){
alumno.get(x).setChecked(!alumno.get(x).isChecked());
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
}
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
tvTitle.setText(mList.get(position).toString());
CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.chkEnable);
mCheckBox.setTag((Integer) position);
mCheckBox.setChecked(alumno.get(position).isChecked());
if(verEstadisticas){
mCheckBox.setVisibility(View.GONE);
}
mCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
//Alumno Alumno = (Alumno) cb.getTag();
Integer position = (Integer) cb.getTag();
alumno.get(position).setChecked(cb.isChecked());
}
});
return convertView;
}
}
You can try following:
Add one boolean property in adapter and a method to set the same.
On click of button where you want to check all the checkbox. Call the adapter method to set boolean value. And call notifyDataSetChanged, this should invalidate and redraw the list view.
While redrawing process, getView method of adapter is called. So in this method check if boolean value is set to true or false and accordingly check or uncheck the check box.
I hope this steps help.
You need to manipulate the "checked" information in your underlying data structure. As you correctly say, the GUI objects only serve the purpose of representing a visual form to your underlying data. It's tempting, but not such a good idea to use GUI objects as the only means to hold application status information.
Check this code. Try to adopt to your adapter. It is not the same. But little modification will definitely work.
class CustomAdapter extends ArrayAdapter<ContactPerson>{
private ArrayList<ContactPerson> contactList;
public CustomAdapter(Context context, int textViewResourceId,
ArrayList<ContactPerson> contactList) {
super(context, textViewResourceId, contactList);
// TODO Auto-generated constructor stub
this.contactList = new ArrayList<ContactPerson>();
this.contactList.addAll(contactList);
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = null;
Log.v("Convert View", String.valueOf(position));
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.checkbox_item, null);
holder = new ViewHolder();
holder.ContactName = (TextView) convertView.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) convertView.findViewById(R.id.contact_check);
convertView.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
ContactPerson contact = (ContactPerson) cb.getTag();
// Log.i("clicked users", contact.getName());
contact.setSelected(cb.isChecked());
}
});
}
else{
holder = (ViewHolder) convertView.getTag();
}
ContactPerson contacts = contactList.get(position);
holder.ContactName.setText("("+contacts.getName()+")");
holder.contactCheck.setChecked(contacts.isSelected());
holder.contactCheck.setTag(contacts);
holder.ContactName.setText(contacts.getName());
return convertView;
}
}
private void checkButtonClick(){
Button nextButton = (Button) findViewById(R.id.selected_done);
nextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuffer display = new StringBuffer();
display.append("the selected contacts are");
ArrayList<ContactPerson> finalContactList = contactAdapter.contactList;
for(int i=0;i<finalContactList.size();i++){
ContactPerson selected = finalContactList.get(i);
if(selected.isSelected()){
display.append("\n"+selected.getName()+"\t"+selected.getPhoneNumber());
}
}
Toast.makeText(getApplicationContext(), display, Toast.LENGTH_LONG).show();
}
});
}
I would use the built-in listview function for marking items checked: setItemChecked, combined with a custom checkable view for the rows. For an excellent walkthrough on creating a checkable view (with a section on handling checkbox children) see Here. For completeness, here is an example of a checkable view:
public class ExampleListItemView extends RelativeLayout implements Checkable {
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public ExampleListItemView(Context context) {
super(context);
}
public ExampleListItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ExampleListItemView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
TextView txtExample;
CheckBox cbExample;
private boolean isChecked = false;
#Override
protected void onFinishInflate() {
super.onFinishInflate();
txtExample = (TextView) findViewById(R.id.txtExample);
cbExample = (CheckBox) findViewById(R.id.cbExample);
isChecked = false;
}
public void setText(String text){
txtExample.setText(text);
}
#Override
public boolean isChecked() {
return isChecked;
}
#Override
public void setChecked(boolean checked) {
if (isChecked != checked) {
cbExample.setChecked(checked);
isChecked = checked;
refreshDrawableState();
}
}
#Override
public void toggle() {
setChecked(!isChecked);
}
#Override
public int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
And the associated xml layout:
<?xml version="1.0" encoding="utf-8"?>
<com.example.ExampleListItemView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
ndroid:addStatesFromChildren="true" >
<CheckBox android:id="#+id/cbExample" />
<TextView
android:id="#+id/txtExample"
android:layout_toRightOf="#id/cbExample" />
</com.example.ExampleListItemView>
You would then end up with something like this:
for(int i = 0; i < adapter.getCount(); i++){
listView.setItemChecked(i, true);
}
SparseBooleanArray checked = listView.getCheckedItemPositions();
I wrote a code that retrieve data from server and display them in a simple list and it work successfully,but when I use a custom list view "in which each row consist of textviews and checkbox" it doesn't work..
this is my classes:
public class ItemInList {
private String name;
private float Description;
private boolean selected;
public ItemInList(String name, float Description) {
this.name = name;
this.Description =Description;
selected = false;
}
public String getName() {
return name;
}
public float getDescription() {
return Description;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(float Description) {
this.Description = Description;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
this is the adapter class
public class DataAdapter extends ArrayAdapter<ItemInList> {
public ArrayList<ItemInList> list;
public Activity context;
public LayoutInflater inflater;
public DataAdapter(Activity context,int x,ArrayList<ItemInList> list) {
super(context, 0, list);
this.context = context;
this.list = list;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
protected TextView name,Description;
protected CheckBox checkbox;
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public ItemInList getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.name = (TextView) convertView.findViewById(R.id.food_title);
holder.name.setTextColor(Color.BLACK);
holder.Description = (TextView) convertView.findViewById(R.id.food_description);
holder.Description.setTextColor(Color.GRAY);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.add_food_item);
//viewHolder.checkbox
//.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//#Override
//public void onCheckedChanged(CompoundButton buttonView,
//boolean isChecked) {
//ItemInList element = (ItemInList) viewHolder.checkbox.getTag();
//element.setSelected(buttonView.isChecked());
//System.out.println("Checked : " + element.getName());
//}
//});
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
ItemInList bean = (ItemInList) list.get(position);
holder.name.setText( bean.getName());
holder.Description.setText( bean.getDescription()+"");
holder.checkbox.setChecked( bean.isSelected());
return convertView;
}
holder.name.setText(list.get(position).getName());
holder.Description.setText(list.get(position).getDescription()+"");
holder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
You do not initate your
ItemInList item;
before setting the values in doInBackground()
item.setName(foodName);
//...
Does it work if you remove "return null" from LoadData.doInBackground()? It's a void function, after all, which shouldn't return anything.