implementation of Checkbox in Custom ListActivity - android

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
}
});
}

Related

How to select all when i check mark All CheckBox?

This image shows how my listview looks like
When we check All then all checkboxes should be checked and when unchecked then all checkboxes should be unchecked, here is the ListView All is also part of the list view, its position is 0 in map list...
public class MultiSelectBaseAdapter extends BaseAdapter{
Context context;
LayoutInflater inflater;
List<Boolean> selectedList;
Map<Integer, MultipleSelect> mapList;
public MultiSelectBaseAdapter(Context context, Map<Integer, MultipleSelect> mapList) {
this.context = context;
this.mapList = mapList;
selectedList = new ArrayList<>();
for(int i=0 ; i< mapList.size() ; i++){
selectedList.add(i, mapList.get(i).isSelected());
}
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public List<Boolean> getSelected(){
return selectedList;
}
public Map<Integer, MultipleSelect> getMapList(){
return mapList;
}
#Override
public int getCount() {
if(mapList != null){
return mapList.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return mapList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.multiselect_item_layout, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.textview_multiselect);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox_multiselect);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setTag(position);
holder.textView.setText(mapList.get(position).getKeyValueType().getName());
if(selectedList.get(position)){
holder.checkBox.setChecked(true);
} else{
holder.checkBox.setChecked(false);
}
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int index = (Integer)buttonView.getTag();
if(isChecked){
selectedList.set(index, true);
}else{
selectedList.set(index, false);
}
notifyDataSetChanged();
}
});
return convertView;
}
public static class ViewHolder {
TextView textView;
CheckBox checkBox;
}
}
please help me I am new in android, I didn't work with CheckBox
[enter image description here][2]
add all selected item ids in your selectedList and then call adapter's notifyDataSetChanged() method
Add boolean value to your MultipleSelect model and change it when you checked or unchecked and for displaying in onBindViewHolder check this value and set checkbox state.
to select all change this value to true for each item in map and call:
yourMultiselectAdapter.notifyDataSetChanged();
same for deselect all - value to true and above call )
i did something like this.
this is y class side code
SelectAll =(Button)findViewById(R.id.footerapproveselectall);
SelectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String btnlbl = SelectAll.getText().toString();
if(btnlbl.equalsIgnoreCase("SelectAll"))
{
// TODO Auto-generated method stub
CustomListAdapter adapter=new CustomListAdapter(Approver.this,AttendanceModelList,1);
lv1.setAdapter(adapter);
SelectAll.setText("Uncheck All");
}else
{
// TODO Auto-generated method stub
CustomListAdapter adapter=new CustomListAdapter(Approver.this, AttendanceModelList,2);
lv1.setAdapter(adapter);
SelectAll.setText("SelectAll");
}
}
});
And this is my adapter side code
public class CustomListAdapter extends ArrayAdapter{
private final Activity context;
/* private final List<String> empname;
private final List<String> reason;
private final List<String> empno;
private final List<String> empdate;
private final List<String> empDay ;
private final List<String> empaid;
*/
private Dialog dialog;
private Dialog dialog1;
private Dialog dialogz;
private AlertDialog BackDialog;
int cheki;
Long id;
String Givenregon;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
private final List<AttendanceModel> AttendanceModelList ;
private TextView NameShow;
private TextView NoShow;
private TextView DayShow;
private TextView DateShow;
private TextView ReasonShow;
private Button Approve;
private Button Cansel;
private Button Reject;
//Date date;
public CustomListAdapter(Activity context, List<AttendanceModel> AttendanceModelList,int cheki)
{
super(context, R.layout.mylist,AttendanceModelList);
// TODO Auto-generated constructor stub
this.context=context;
this.AttendanceModelList =AttendanceModelList;
this.cheki =cheki;
}
static class ViewHolder {
protected TextView txtTitle;
protected TextView textemployeedate;
protected ImageButton View1;
protected TextView textempday;
protected CheckBox Chek1 ;
}
public View getView(int position,View convertview,ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertview == null){
LayoutInflater inflater=context.getLayoutInflater();
convertview=inflater.inflate(R.layout.mylist, null);
viewHolder = new ViewHolder();
viewHolder.txtTitle = (TextView) convertview.findViewById(R.id.idemployeename);
//TextView extratxt = (TextView) rowView.findViewById(R.id.idreason);
//TextView txemployee = (TextView) rowView.findViewById(R.id.idempno);
viewHolder. textemployeedate = (TextView)convertview.findViewById(R.id.idempdate);
viewHolder. textempday = (TextView) convertview.findViewById(R.id.idempday);
/* Button Submit = (Button) rowView.findViewById(R.id.btapprove);
*
*/
/*Button Cansel = (Button) rowView.findViewById(R.id.btreject);*/
viewHolder. View1 =(ImageButton)convertview.findViewById(R.id.btmylistviewshow);
viewHolder. Chek1 = (CheckBox)convertview.findViewById(R.id.checkmylist);
viewHolder.Chek1.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.
AttendanceModelList.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertview.setTag(viewHolder);
convertview.setTag(R.id.idemployeename,viewHolder.txtTitle);
convertview.setTag(R.id.idempday,viewHolder.textempday);
convertview.setTag(R.id.idempdate,viewHolder.textemployeedate);
convertview.setTag(R.id.checkmylist,viewHolder.Chek1);
}
else {
viewHolder = (ViewHolder) convertview.getTag();
}
viewHolder.Chek1.setTag(position);
viewHolder.Chek1.setChecked(AttendanceModelList.get(position).isSelected());
viewHolder.txtTitle.setText(AttendanceModelList.get(position).getEmpname());
if(cheki==1)
{
viewHolder. Chek1.setChecked(true);
}
else if(cheki==2)
{
viewHolder. Chek1.setChecked(false);
}
return convertview;
};
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ListView listView;
String Name[]={"All","One","Two","Three","Four","Five"};
boolean Some[]={false,false,false,false,false,false};
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.listView);
adapter = new MyAdapter(MainActivity.this,Name,Some);
listView.setAdapter(adapter);
}
public void myDAta1(int pos)
{
Some[pos]=false;
adapter.notifyDataSetChanged();
}
public void myDAta2(int pos)
{
Some[pos]=true;
adapter.notifyDataSetChanged();
}
public void myDAta3()
{
for(int i=0;i<Name.length;i++)
{
Some[i]=false;
}
adapter.notifyDataSetChanged();
}
public void myDAta4()
{
for(int i=0;i<Name.length;i++)
{
Some[i]=true;
}
adapter.notifyDataSetChanged();
}
}
MyAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
String Name[];
boolean Some[];
Context context;
LayoutInflater inflater;
MyAdapter(Context mContext,String mName[],boolean mSome[])
{
this.context=mContext;
this.Name= mName;
this.Some=mSome;
}
#Override
public int getCount() {
return Name.length;
}
#Override
public Object getItem(int position) {
return Name[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder ;
if (convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.textView);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(Name[position]);
holder.checkBox.setChecked(Some[position]);
if(position==0) {
if (holder.checkBox.isChecked()) {
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (context instanceof MainActivity) {
((MainActivity) context).myDAta3();
}
}
});
} else {
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (context instanceof MainActivity) {
((MainActivity) context).myDAta4();
}
}
});
}
}
else
{
if(holder.checkBox.isChecked())
{
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(context instanceof MainActivity){
((MainActivity)context).myDAta1(position);
}
}
});
}
else
{
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(context instanceof MainActivity){
((MainActivity)context).myDAta2(position);
}
}
});
}
}
return convertView;
}
public static class ViewHolder {
TextView textView;
CheckBox checkBox;
}
}
replace this code
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int index = (Integer)buttonView.getTag();
if(index==0)
{
if (isChecked)
{
for (int i = 0; i < mapList.size(); i++)
{
MultipleSelect obj = (MultipleSelect) getMapList().get(i);
// obj.setSelected(false);
// arrayList2.set(i, obj);
if(obj.isSelected())
{
selectedList.set(i, false);
}
else
{
selectedList.set(i, true);
}
}
}
else
{
selectedList.set(index, false);
}
}
else
{
if (isChecked)
{
selectedList.set(index, true);
}
else
{
selectedList.set(index, false);
selectedList.set(0, false);
}
}
notifyDataSetChanged();
}
});
return convertView;
}
public static class ViewHolder {
TextView textView;
CheckBox checkBox;
}

I select and then deselect a row in listview it returned as selected

I am facing problem in ListView with selecting and then deselecting Checkbox. I have a button in which i am bypassing all the selected items of a list. But i check and then uncheck, it returned as checked.I am using sparse boolean array.
Here is my code-
#Override
public void onClick(View v) {
if(addProductAdapter.mCheckedState.size()==0){
Toast toast = Toast.makeText(this,SELECT_PRODUCTS, Toast.LENGTH_LONG);
toast.show();
}
else{
ArrayList<Object> list = new ArrayList<Object>();
for (int i = 0; i < addProductAdapter.getCount(); i++) {
if (addProductAdapter.mCheckedState.get(i) == true) {
//ArrayList<Object> list = new ArrayList<Object>();
// for(int j = 0;j<=productObject.size();j++){
ProductEntity productEntity = (ProductEntity) productObject
.get(i);
ProductsEntity pe = new ProductsEntity();
pe.setProcdut_name(productEntity.getName());
pe.setUnit_price(productEntity.getUnitPrice());
pe.setTotal_price(productEntity.getUnitPrice());
pe.setQuantity("1");
list.add(pe);
// arrayList.add(list);
}
}
Intent returnIntent = new Intent();
returnIntent.putExtra(RESULT, list);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
}
here is my adapter class`private Context context;
private int resourceId;
private List<Object> objArrayList;
public SparseBooleanArray mCheckedState;
public AddProductsAdapter(Context context, int resource, List<Object> objList ) {
super(context, resource,objList);
this.context = context;
this.resourceId = resource;
mCheckedState = new SparseBooleanArray(objList.size());
this.objArrayList = objList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View productview = convertView;
ProductHolder productHolder;
if (productview == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
productview = inflater.inflate(resourceId, parent, false);
productHolder = new ProductHolder();
productHolder.productNameView = (TextView) productview.findViewById(R.id.nameProductView);
productHolder.productIdView = (TextView) productview.findViewById(R.id.IdProductView);
productHolder.productPriceView = (TextView) productview.findViewById(R.id.priceProductView);
productHolder.checkBox = (CheckBox) productview.findViewById(R.id.checkBoxView);
productview.setTag(productHolder);
productview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ProductHolder productHolder = (ProductHolder) v.getTag();
if (productHolder.checkBox.isChecked()){
productHolder.checkBox.setChecked(false);
}
else{
productHolder.checkBox.setChecked(true);
}
}
});
}
else{
productHolder = (ProductHolder) productview.getTag();
}
try {
if(objArrayList!=null){
ProductEntity productEntity= (ProductEntity) objArrayList.get(position);
String productName = productEntity.getName();
String productId = productEntity.getProductId();
String productPriceStandrd = productEntity.getStandard();
productHolder.productNameView.setText(productName);
productHolder.productIdView.setText(productId);
productHolder.productPriceView.setText(productPriceStandrd);
//productHolder.checkBox.setTag(position);
productHolder.checkBox.setTag(position);
productHolder.checkBox.setChecked(mCheckedState.get(position, false));
productHolder.checkBox.setOnCheckedChangeListener(this);
}
}
catch (Exception e) {
e.printStackTrace();
}
return productview;
}
public boolean isChecked(int position) {
return mCheckedState.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckedState.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public int getCount() {
return objArrayList != null ? objArrayList.size() : 0;
}
private class ProductHolder {
TextView productNameView;
TextView productIdView;
TextView productPriceView;
CheckBox checkBox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckedState.put((Integer) buttonView.getTag(), isChecked);
}
`

How to get selected user name in listview

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;
}
}

ListView Position on button click

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;
}
}

listview with edittext ,checkbox and textView in android

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)
{
}
});
}

Categories

Resources