I'm implementing functions of notifications like default messages application in android. Now I'm doing the multiple message deletion by adding checkbox in which I'm using one common checkbox to select all messages in the list. But I can not check the listview checkbox which is in getview of CustomAdpter.
class customListAdpter extends BaseAdapter {
private Context ctx;
CheckBox checkBox;
TextView sender, message;
customListAdpter(Context context) {
this.ctx = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return new NotifiCation().senderlist.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;
}
#Override
public View getView(final int pos, View v, ViewGroup arg2) {
// TODO Auto-generated method stub
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.checkboxlist, null);
checkBox = (CheckBox) v.findViewById(R.id.btn_chck);
sender = (TextView) v.findViewById(R.id.text_senderno);
message = (TextView) v.findViewById(R.id.text_msg);
}
sender.setText("" + new NotifiCation().senderlist.toArray()[pos]);
message.setText("" + new NotifiCation().msglist.toArray()[pos]);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (buttonView.isChecked()) {
}
}
});
return v;
}
}
And this is my main activity. Here I have the main checkbox.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_notifications);
db = new DB(NotificationsDelete.this);
notifications = (ListView) findViewById(R.id.list_with_ckbox);
selectAll = (CheckBox) findViewById(R.id.btn_checkall);
done = (Button) findViewById(R.id.done_notification_delete);
notifications.setAdapter(new customListAdpter(con));
selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton chkbox, boolean arg1) {
if (chkbox.isChecked() == true) {
for (int i = 0; i < new NotifiCation().senderlist.size(); i++) {
//notifications.setItemChecked(i, true);
customListAdpter adpter=new customListAdpter(con);
adpter.checkBox.setChecked(true);
}
} else {
// new customListAdpter(con).checkBox.setChecked(true);
}
}
});
done.setOnClickListener(this);
}
Try calling notifyDataSetChanged() after you handle onCheckedChanged() of selectAll checkbox field.
Related
i have two custom GridView, I want to set Onclick Listener for first GridView, i did it inside its adapter , working fine ... but when generate items in second GridView the onclick listener read values from second GridView when i press on item in first GridView!
The onclick listener working fine if the second GridView empty
I have no idea how to fix this
The problem with holder.tvgroup1 and holder.tvgroup_delete_icon
Thanks
First GridView Adapter
public class GroupGeneratedAdapter extends BaseAdapter {
ArrayList<String> result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
GroupGeneratedAdapter(GroupMakerG groupMakerG, ArrayList<String> UserNameinput) {
// TODO Auto-generated constructor stub
result = UserNameinput;
context = groupMakerG;
// imageId=prgmImages;
inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tvgroup, tvgroup1;
ImageView tvgroup_delete_icon;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder = new Holder();
// View rowView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.group_generated_original, parent, false);
}
holder.tvgroup = (TextView) convertView.findViewById(R.id.tvgroup);
holder.tvgroup1 = (TextView) convertView.findViewById(R.id.tvgroup1);
holder.tvgroup_delete_icon = (ImageView) convertView.findViewById(R.id.tvgroup_delete_icon);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tvgroup.setText(String.valueOf(position + 1) + "-");
holder.tvgroup1.setText(result.get(position));
// holder.img.setImageResource(imageId[position]);
holder.tvgroup_delete_icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GroupMakerG.GroupOfNames.remove(position);
GroupMakerG.MainGroup.invalidateViews();
if (GroupMakerG.arraySugestion.size() > 0) {
GroupMakerG.arraySugestion.clear();
GroupMakerG.makeSuggestions();
} else {
GroupMakerG.makeSuggestions();
}
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.No_Of_Groups.setText("");
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
GroupMakerG.GroupNameLength.setText(String.valueOf(GroupMakerG.GroupOfNames.size()));
}
});
holder.tvgroup1.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Modify Item No." + " " + (position + 1));
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(context).inflate(R.layout.modify_name_mainlist, (ViewGroup) parent.findViewById(android.R.id.content), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.client_name_input);
input.setText(GroupMakerG.GroupOfNames.get(position));
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
String m_Text = input.getText().toString();
if (m_Text.trim().equals("")) {
// Toast.makeText(context, "You should enter name", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(context,context.getString(R.string.group_you_should_enter_name), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
} else {
GroupMakerG.GroupOfNames.set(position, m_Text);
GroupMakerG.MainGroup.invalidateViews();
GroupMakerG.GeneratedGroup.setAdapter(null);
GroupMakerG.numoftries = 0;
GroupMakerG.Group_num_tries.setText("0");
Toast toast = Toast.makeText(context, context.getString(R.string.group_item_changed), Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return false;
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(context, "You Clicked "+ result.get(position), Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Second GridView Adapter
public class GroupGeneratedAdapterG extends BaseAdapter {
private ArrayList<String> resultg;
int[] imageId;
private static LayoutInflater inflaterg = null;
private static int generated_group_counter;
Context contextg;
GroupGeneratedAdapterG(GroupMakerG groupMaker, ArrayList<String> UserNameoutput) {
// TODO Auto-generated constructor stub
resultg = UserNameoutput;
contextg = groupMaker;
// imageId=prgmImages;
inflaterg = (LayoutInflater) contextg.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
generated_group_counter = 0;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return resultg.size();
}
#Override
public Object getItem(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
#Override
public long getItemId(int positiong) {
// TODO Auto-generated method stub
return positiong;
}
public class Holder {
TextView tvgroupg, tvgroup1g;
// ImageView img;
}
#Override
public View getView(final int positiong, View convertViewg, ViewGroup parentg) {
// TODO Auto-generated method stub
generated_group_counter = generated_group_counter + 1;
Holder holderg = new Holder();
// View rowView;
if (convertViewg == null) {
convertViewg = inflaterg.inflate(R.layout.group_generated_generated, parentg, false);
}
holderg.tvgroupg = (TextView) convertViewg.findViewById(R.id.tvgroupg);
holderg.tvgroup1g = (TextView) convertViewg.findViewById(R.id.tvgroup1g);
// holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
String[] ary = resultg.get(positiong).split("!##%");
if (ary[1].length() > 4) {
if (ary[1].substring(0, 5).equals("Group")) {
holderg.tvgroupg.setText("");
holderg.tvgroup1g.setText(ary[1]);
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
} else {
holderg.tvgroupg.setText(ary[0]);
holderg.tvgroup1g.setText(ary[1]);
}
convertViewg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(contextg, "You Clicked "+ String.valueOf(resultg.get(positiong)), Toast.LENGTH_LONG).show();
}
});
return convertViewg;
}
}
I have a custom listview that contains an edittext,checkbox and two text views.Now i am hving a problem with the edittext values in my code.I am not able to get the correct value from the edittext.And also if i set the value of an edit text at one position in the list,that value is also set to edittexts at random positions in the listview.And i have the common problem of the values changing on scroll.Following is the code:
Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assess_list);
prev = getIntent();
final ListView listview = (ListView) findViewById(R.id.studentsListView);
listview.setAdapter(new AssessmentAdapter(this, R.layout.assessment,
StudentNames.student_name, StudentNames.studentRollNo));
}
Adapter:
public class AssessmentAdapter extends ArrayAdapter<String> {
Context context;
ViewHolder holder;
CheckBox present;
EditText marks;
int pos;
public static ArrayList<String> studentNames,studentRollNo,studentsPresent,marksObtainedList;
public AssessmentAdapter(Context context, int textViewResourceId,ArrayList<String> studentNames,ArrayList<String> studentRollNo) {
super(context, textViewResourceId,studentNames);
// TODO Auto-generated constructor stub
this.context=context;
AssessmentAdapter.studentNames=studentNames;
AssessmentAdapter.studentRollNo=studentRollNo;
studentsPresent=new ArrayList<String>();
marksObtainedList=new ArrayList<String>();
Log.d("No. of students",""+studentRollNo.size());
for(int i=0;i<studentNames.size();i++)
{
studentsPresent.add("1");
marksObtainedList.add("0");
}
}
static class ViewHolder {
CheckBox presentCB;
TextView name,Rno;
EditText marksObtained;
Button save;
}
public View getView(final int pos,View convertview,ViewGroup parent)
{
try
{
holder=null;
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(convertview==null)
{
//rowView=inflater.inflate(org.example.attendance.R.layout.list_radio,parent,false);
convertview=inflater.inflate(R.layout.assessment,null);
holder=new ViewHolder();
holder.presentCB=(CheckBox)convertview.findViewById(org.example.attendance2.R.id.presentCB);
holder.name=(TextView)convertview.findViewById(org.example.attendance2.R.id.studNameTV);
holder.Rno=(TextView)convertview.findViewById(org.example.attendance2.R.id.studRollNoTV);
holder.marksObtained=(EditText)convertview.findViewById(org.example.attendance2.R.id.marksET);
holder.save=(Button)convertview.findViewById(org.example.attendance2.R.id.saveButton);
convertview.setTag(holder);
}
else
{
holder=(ViewHolder) convertview.getTag();
}
holder.name.setText(studentNames.get(pos));
holder.Rno.setText(studentRollNo.get(pos));
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
holder.marksObtained.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
marksObtainedList.set(pos, arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
holder.presentCB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(studentsPresent.get(pos).equals("1"))
{
studentsPresent.set(pos, "0");
}
else
{
studentsPresent.set(pos, "1");
}
}
});
//if(RadioChecked[pos])
if(studentsPresent.get(pos).equals("1"))
{
holder.presentCB.setChecked(true);
}
// else if(!RadioChecked[pos])
else if(studentsPresent.get(pos).equals("0"))
{
holder.presentCB.setChecked(false);
}
if(holder.marksObtained.getText().toString().equals(""))
{
marksObtainedList.set(pos,"0");
}
else
{
String marks=holder.marksObtained.getText().toString();
marksObtainedList.set(pos,marks);
Log.d(""+pos,marksObtainedList.get(pos));
}
holder.marksObtained.setText(marksObtainedList.get(pos));
}catch(Exception e)
{
}
return convertview;
}
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int arg0)
{
return true;
}
}
the problem is all about relate to focus . see here , it may help you.
Focusable EditText inside ListView
Please help me with this guys, i am stuck up
I am Working on a viewpager, where i require my linearlayout change it's visibilty on a button click, but the visibilty property seems to but not working.
Here is my code
public class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(final View collection, final int position) {
Log.d("Inside", "Pager");
PagerView = new View(collection.getContext());
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PagerView = inflater.inflate(R.layout.bigimage, null);
imgSubmenu = (ScalableImageView)PagerView.findViewById(R.id.imgSubMenu);
btnBack = (Button)PagerView.findViewById(R.id.btnBack);
btnCart = (Button) PagerView.findViewById(R.id.btnCart);
btnCallWaiter = (Button) PagerView.findViewById(R.id.btnCallWaiter);
btnPayBill = (Button) PagerView.findViewById(R.id.btnPayBill);
btnReadMore = (Button) PagerView.findViewById(R.id.btnReadMore);
btnAddtoOrder = (Button) PagerView.findViewById(R.id.btnAddtoOrder);
tvSubMenuName = (TextView) PagerView.findViewById(R.id.tvSubMenuName);
tvDescption = (TextView) PagerView.findViewById(R.id.tvDescrption);
readLayout=(LinearLayout)PagerView.findViewById(R.id.readLayout);
font = Typeface.createFromAsset(MenuSelectionActivity.this.getAssets(),
"fonts/BEBAS___.ttf");
btnBack.setTypeface(font, Typeface.BOLD);
btnCallWaiter.setTypeface(font, Typeface.BOLD);
btnPayBill.setTypeface(font, Typeface.BOLD);
btnReadMore.setTypeface(font, Typeface.BOLD);
tvSubMenuName.setTypeface(font, Typeface.BOLD);
btnReadMore.setTypeface(font, Typeface.BOLD);
tvDescption.setTypeface(font, Typeface.BOLD);
btnAddtoOrder.setTypeface(font, Typeface.BOLD);
((ViewPager) collection).addView(PagerView, 0);
DisplayItem(position);
btnReadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("readtype",""+readtype);
if(readtype==0)
{
readLayout.setVisibility(View.GONE);
btnReadMore.setText("READ MORE");
btnReadMore.setBackgroundResource(drawable.readmore);
readtype=1;
}
else
{
readLayout.setVisibility(View.VISIBLE);
btnReadMore.setText("READ LESS");
btnReadMore.setBackgroundResource(drawable.readless);
readtype=0;
}
}
});
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
return PagerView;
}
#Override
public void destroyItem(final View arg0, final int arg1,
final Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(final View arg0, final Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return SubMenuIdList.size();
}
}
Can anyone please help me up.
i think your code is right.
have you tried to set the visibility with int?
setVisibility(0) -> visible or setVisibility(View.VISIBLE)
setVisibility(4) -> invisible or setVisibility(View.INVISIBLE)
setVisibility(8) -> gone or setVisibility(View.GONE)
I want to get all the family id selected from the list view. I add the family id in a separate
arraylist when click on the corresponding checkbox. The value in the arraylist losses when i scroll the listview.
Following is my code.
public class FamilyList extends Activity{
ListView fam_list;
DataAdapter myadapt;
ArrayList<ListClass> familyarraylist;
ArrayList<String> familyselectedlist;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("zacharia", "inside oncreate");
setContentView(R.layout.activity_familylist);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
fam_list=(ListView) findViewById(R.id.familylist);
myadapt=new DataAdapter(this);
final TextView empty=(TextView) findViewById(R.id.emptyView);
empty.setText("No Data Found");
familyarraylist= myadapt.getfamilylist("All");
FamilyListAdapter familyadapter=new FamilyListAdapter(this, R.layout.family_list_view,familyarraylist);
fam_list.setAdapter(familyadapter);
fam_list.setEmptyView(empty);
familyselectedlist=new ArrayList<String>();
ImageButton button=(ImageButton) findViewById(R.id.imageButton1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText edit=(EditText) findViewById(R.id.editText1);
if(edit.getText().length()>0){
if(myadapt==null){
myadapt=new DataAdapter(FamilyList.this);
}
familyarraylist=myadapt.getfamilylist(edit.getText().toString());
fam_list.setAdapter(new FamilyListAdapter(FamilyList.this, R.layout.family_list_view, familyarraylist)); }
else{
if(myadapt==null){
myadapt=new DataAdapter(FamilyList.this);
}
familyarraylist=myadapt.getfamilylist("All");
fam_list.setAdapter(new FamilyListAdapter(FamilyList.this, R.layout.family_list_view,familyarraylist ));
}
fam_list.setEmptyView(empty);
}
});
show=(Button) findViewById(R.id.button1);
show.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
for(int i=0;i<familyselectedlist.size();i++){
Log.i("zacharia", familyselectedlist.get(i));
}
MainActivity.selected_list=true;
MainActivity.selected_family_id_array=familyselectedlist;
FamilyList.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.activity_list, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId()==R.id.item1){
final SharedPreferences prefs=getSharedPreferences("search_mode", Activity.MODE_WORLD_READABLE);
int pos=prefs.getInt("position", 0);
new AlertDialog.Builder(this).setTitle("Search By")
.setSingleChoiceItems(new String[]{"Name","House Name"}, pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor edit=prefs.edit();
edit.putInt("position", which);
edit.commit();
dialog.dismiss();
}
}).show();
}
return true;
}
static class ViewHolder {
protected TextView id_text,id_name,id_address;
protected CheckBox id_check;
}
class FamilyListAdapter extends ArrayAdapter<ListClass>{
private ArrayList<ListClass> list_array;
Context context;
boolean checkchange=false;
ListClass obj;
public FamilyListAdapter(Context context, int textViewResourceId,
ArrayList<ListClass> objects) {
super(context, textViewResourceId, objects);
this.context=context;
list_array=objects;
}
#Override
public ListClass getItem(int position) {
// TODO Auto-generated method stub
return list_array.get(position);
}
public int getFamilyId(int position){
return list_array.get(position).getFamilyid();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v=convertView;
if(v==null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.family_list_view, null);
final ViewHolder holder = new ViewHolder();
obj=getItem(position);
holder.id_text=(TextView) v.findViewById(R.id.list_familyid);
holder.id_text.setText(""+obj.getFamilyid());
holder.id_name=(TextView) v.findViewById(R.id.list_name);
holder.id_name.setText(""+obj.getHeadname());
holder.id_address=(TextView) v.findViewById(R.id.list_address);
holder.id_address.setText(""+obj.getAddress());
holder.id_check=(CheckBox) v.findViewById(R.id.check_familyview);
Log.i("zacharia", "check result:"+ getFamilyId(position)+" "+familyselectedlist.contains(""+getFamilyId(position)));
holder.id_check.setSelected(false);
if(familyselectedlist.contains(""+getFamilyId(position))){
holder.id_check.setSelected(true);
}
holder.id_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("zacharia", "inside on change");
if(isChecked){
familyselectedlist.add(""+getFamilyId(position));
}
else{
familyselectedlist.remove(""+getFamilyId(position));
}
}
});
v.setTag(holder);
holder.id_check.setTag(getFamilyId(position));
}
else{
v=convertView;
((ViewHolder)v.getTag()).id_check.setTag(getFamilyId(position));
}
obj=getItem(position);
ViewHolder holder = (ViewHolder) v.getTag();
holder.id_text.setText(""+obj.getFamilyid());
holder.id_name.setText(obj.getHeadname());
holder.id_address.setText(obj.getAddress());
if(familyselectedlist.contains(""+getFamilyId(position))){
holder.id_check.setChecked(true);
}
else{
holder.id_check.setChecked(false);
}
return v;
}
}
}
Just move the following code out of if-condition (if (v==null)):
holder.id_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("zacharia", "inside on change");
if(isChecked){
familyselectedlist.add(""+getFamilyId(position));
}
else{
familyselectedlist.remove(""+getFamilyId(position));
}
}
});
You set listener only if you don't get a view for reusing. But you still have to set listener when you reuse existing view. So, if convertView is not null then it comes already with old onClickListener. This OnClickListener uses wrong position (from old view).
As a result you should set OnClickListener not only if (v == null).
I make some changes to my code and pass an instance of an arraylist (for selected_ids) to the adapter it works.
Following is my code:
public class FamilyList extends Activity{
ListView fam_list;
DataAdapter myadapt;
ArrayList<ListClass> familyarraylist;
ArrayList<String> familyselectedlist;
Button show;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.i("zacharia", "inside oncreate");
setContentView(R.layout.activity_familylist);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
fam_list=(ListView) findViewById(R.id.familylist);
myadapt=new DataAdapter(this);
final TextView empty=(TextView) findViewById(R.id.emptyView);
empty.setText("No Data Found");
familyarraylist= myadapt.getfamilylist("All");
familyselectedlist=new ArrayList<String>();
FamilyListAdapter familyadapter=new FamilyListAdapter(this, R.layout.family_list_view,familyarraylist,familyselectedlist);
fam_list.setAdapter(familyadapter);
fam_list.setEmptyView(empty);
ImageButton button=(ImageButton) findViewById(R.id.imageButton1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText edit=(EditText) findViewById(R.id.editText1);
if(edit.getText().length()>0){
if(myadapt==null){
myadapt=new DataAdapter(FamilyList.this);
}
familyarraylist=myadapt.getfamilylist(edit.getText().toString());
fam_list.setAdapter(new FamilyListAdapter(FamilyList.this, R.layout.family_list_view, familyarraylist,familyselectedlist)); }
else{
if(myadapt==null){
myadapt=new DataAdapter(FamilyList.this);
}
familyarraylist=myadapt.getfamilylist("All");
fam_list.setAdapter(new FamilyListAdapter(FamilyList.this, R.layout.family_list_view,familyarraylist,familyselectedlist));
}
fam_list.setEmptyView(empty);
}
});
show=(Button) findViewById(R.id.button1);
show.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
for(int i=0;i<familyselectedlist.size();i++){
Log.i("zacharia", familyselectedlist.get(i));
}
MainActivity.selected_list=true;
MainActivity.selected_family_id_array=familyselectedlist;
FamilyList.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.activity_list, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId()==R.id.item1){
final SharedPreferences prefs=getSharedPreferences("search_mode", 0);
int pos=prefs.getInt("position", 0);
new AlertDialog.Builder(this).setTitle("Search By")
.setSingleChoiceItems(new String[]{"Name","House Name"}, pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor edit=prefs.edit();
edit.putInt("position", which);
edit.commit();
dialog.dismiss();
}
}).show();
}
return true;
}
class FamilyListAdapter extends ArrayAdapter<ListClass>{
private ArrayList<ListClass> list_array;
Context context;
ArrayList<String> selectedlist;
TextView id_text,id_name,id_address;
CheckBox id_check;
boolean checkchange=false;
ListClass obj;
public FamilyListAdapter(Context context, int textViewResourceId,
ArrayList<ListClass> objects,ArrayList<String> selectedlist) {
super(context, textViewResourceId, objects);
this.context=context;
list_array=objects;
this.selectedlist=selectedlist;
}
#Override
public ListClass getItem(int position) {
// TODO Auto-generated method stub
return list_array.get(position);
}
public int getFamilyId(int position){
return list_array.get(position).getFamilyid();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v=convertView;
if(v==null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.family_list_view, null);
}
obj=getItem(position);
id_text=(TextView) v.findViewById(R.id.list_familyid);
id_text.setText(""+obj.getFamilyid());
id_name=(TextView) v.findViewById(R.id.list_name);
id_name.setText(""+obj.getHeadname());
id_address=(TextView) v.findViewById(R.id.list_address);
id_address.setText(""+obj.getAddress());
id_check=(CheckBox) v.findViewById(R.id.check_familyview);
id_check.setSelected(false);
if(selectedlist.contains(""+getFamilyId(position))){
id_check.setSelected(true);
}
id_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("zacharia", "inside on change");
if(isChecked){
selectedlist.add(""+getFamilyId(position));
}
else{
selectedlist.remove(""+getFamilyId(position));
}
}
});
id_check.setTag(getFamilyId(position));
if(selectedlist.contains(""+getFamilyId(position))){
id_check.setChecked(true);
}
else{
id_check.setChecked(false);
}
return v;
}
}
}
Now i need to show the selected items when i open this activity. How can i done that? i try to pass it by the familyselectedlist to the adapter. If i uncheck the checkbox and scroll the check box status is remain as checked.
I want to have a listview with textview + check box. I was able to create the listview. I can capture listview item select. However when I try to capture check box select, unselect I get a null pointer exception. How to write the setOnCheckedChangeListener() for the check box..
public class LocationActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
final List<String> locLables = new ArrayList<String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.add(cursor.getString(1));
} while (cursor.moveToNext());
}
}
//String[] locLables = new String[] {"Home","University","Office"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.locationmain_entry,R.id.textView12, locLables);
//cb gives a null pointer exception
CheckBox cb = (CheckBox) listview.findViewById(R.id.checkBox12);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("selected");
}else if(!isChecked){
System.out.println("not selected");
}
}
});
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
You can maintain seperate adpater class so that you can achive this easily....
public class bsAdapter extends BaseAdapter
{
Activity cntx;
public bsAdapter(Activity context)
{
// TODO Auto-generated constructor stub
this.cntx=context;
}
public int getCount()
{
// TODO Auto-generated method stub
return listview_arr.length;
}
public Object getItem(int position)
{
// TODO Auto-generated method stub
return listview_arr[position];
}
public long getItemId(int position)
{
// TODO Auto-generated method stub
return listview_array.length;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.search_list_item, null);
TextView tv=(TextView)row.findViewById(R.id.title);
CheckBox cb=(CheckBox)row.findViewById(R.id.cb01);
tv.setText(listview_arr[position]);
cb.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(cb.ischecked)
{
//ur code
}
else //ur code
}
});
return row;
}
}
Do not use listview.findViewById(), just use findViewById() like you did for your list.
Unless the checkbox is part of each of the list items, in which case you would have to access the checkbox from within the getView() of your ListAdapter.