select all option for listview with checkbox - android

I'm fetching phone contacts using listview with checkboxes. I used the instrucstions given in this link. The code is working perfectly if I want to select some of the contacts. Now I want to add a "Select All" checkbox in the activity
// Logcat
FATAL EXCEPTION: main
Process: com.sam.afrikk, PID: 10628
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.sam.afrikk.ContactsPickerActivity$1.onCheckedChanged(ContactsPickerActivity.java:54)
at android.widget.CompoundButton.setChecked(CompoundButton.java:156)
at android.widget.CompoundButton.toggle(CompoundButton.java:115)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
but I'm getting IndexOutOfBoundsException.
public class ContactsList{
public ArrayList<Contact> contactArrayList;
ContactsList(){
contactArrayList = new ArrayList<Contact>();
}
public int getCount(){
return contactArrayList.size();
}
public void addContact(Contact contact){
contactArrayList.add(contact);
}
public void removeContact(Contact contact){
contactArrayList.remove(contact);
}
public Contact getContact(int id){
for(int i=0;i<this.getCount();i++){
if(Integer.parseInt(contactArrayList.get(i).id)==id)
return contactArrayList.get(i);
}
return null;
}
}
public class ContactsListAdapter extends BaseAdapter {
Context context;
ContactsList contactsList,filteredContactsList,selectedContactsList;
String filterContactName;
ContactsListAdapter(Context context, ContactsList contactsList){
super();
this.context = context;
this.contactsList = contactsList;
this.filteredContactsList=new ContactsList();
this.selectedContactsList = new ContactsList();
this.filterContactName = "";
}
public void filter(String filterContactName){
filteredContactsList.contactArrayList.clear();
if(filterContactName.isEmpty() || filterContactName.length()<1){
filteredContactsList.contactArrayList.addAll(contactsList.contactArrayList);
this.filterContactName = "";
}
else {
this.filterContactName = filterContactName.toLowerCase().trim();
for (int i = 0; i < contactsList.contactArrayList.size(); i++) {
if (contactsList.contactArrayList.get(i).name.toLowerCase().contains(filterContactName))
filteredContactsList.addContact(contactsList.contactArrayList.get(i));
}
}
notifyDataSetChanged();
}
public void addContacts(ArrayList<Contact> contacts){
this.contactsList.contactArrayList.addAll(contacts);
this.filter(this.filterContactName);
}
#Override
public int getCount() {
return filteredContactsList.getCount();
}
#Override
public Contact getItem(int position) {
return filteredContactsList.contactArrayList.get(position);
}
#Override
public long getItemId(int position) {
return Long.parseLong(this.getItem(position).id);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView==null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(R.layout.contact_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.chkContact = (CheckBox) convertView.findViewById(R.id.chk_contact);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.chkContact.setText(this.filteredContactsList.contactArrayList.get(position).toString());
viewHolder.chkContact.setId(Integer.parseInt(this.filteredContactsList.contactArrayList.get(position).id));
viewHolder.chkContact.setChecked(alreadySelected(filteredContactsList.contactArrayList.get(position)));
viewHolder.chkContact.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Contact contact = filteredContactsList.getContact(buttonView.getId());
if(contact!=null && isChecked && !alreadySelected(contact)){
selectedContactsList.addContact(contact);
}
else if(contact!=null && !isChecked){
selectedContactsList.removeContact(contact);
}
}
});
return convertView;
}
public boolean alreadySelected(Contact contact)
{
if(this.selectedContactsList.getContact(Integer.parseInt(contact.id))!=null)
return true;
return false;
}
public static class ViewHolder{
CheckBox chkContact;
}
}
public class ContactsPickerActivity extends AppCompatActivity {
ListView contactsChooser;
Button btnDone;
TextView txtLoadInfo;
ContactsListAdapter contactsListAdapter;
ContactsLoader contactsLoader;
CheckBox selectAll;
Contact contact;
ContactsList contactsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_picker);
contactsChooser = (ListView) findViewById(R.id.lst_contacts_chooser);
btnDone = (Button) findViewById(R.id.btn_done);
txtLoadInfo = (TextView) findViewById(R.id.txt_load_progress);
selectAll = (CheckBox)findViewById(R.id.selectAll);
contactsListAdapter = new ContactsListAdapter(this,new ContactsList());
contactsChooser.setAdapter(contactsListAdapter);
loadContacts("");
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
contactsList = new ContactsList();
if(isChecked){
selectAll.setText("Unselect All");
//HERE I"M GETTING EXCEPTION
for (int i=0;i<contactsListAdapter.getCount();i++){
contact = contactsListAdapter.selectedContactsList.contactArrayList.get(i);
contactsListAdapter.selectedContactsList.addContact(contact);
}
}else{
selectAll.setText("Select All");
for (int i=0;i<contactsListAdapter.getCount();i++){
contact = contactsListAdapter.selectedContactsList.contactArrayList.get(i);
contactsListAdapter.selectedContactsList.removeContact(contact);
}
}
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(contactsListAdapter.selectedContactsList.contactArrayList.isEmpty()){
setResult(RESULT_CANCELED);
}
else{
Intent resultIntent = new Intent();
resultIntent.putParcelableArrayListExtra("SelectedContacts", contactsListAdapter.selectedContactsList.contactArrayList);
setResult(RESULT_OK,resultIntent);
}
finish();
}
});
}
private void loadContacts(String filter){
if(contactsLoader!=null && contactsLoader.getStatus()!= AsyncTask.Status.FINISHED){
try{
contactsLoader.cancel(true);
}catch (Exception e){
}
}
if(filter==null) filter="";
try{
//Running AsyncLoader with adapter and filter
contactsLoader = new ContactsLoader(this,contactsListAdapter);
contactsLoader.txtProgress = txtLoadInfo;
contactsLoader.execute(filter);
}catch(Exception e){
e.printStackTrace();
}
}
}

There are a two issues there:
You're iterating over the entire list of contacts, instead of over the list of selected contacts only:
(I've also changed your iterator from a for-loop, to an array-iterator, this makes the code more readable)
In the unselect block, you're calling addContact instead of removeContact
Array<Contact> selectedContactsArray = contactsListAdapter.selectedContactsList.contactArrayList;
for (Contact contact : selectedContactsArray) {
contactsListAdapter.selectedContactsList.removeContact(contact);
}

Related

Not able to display selected multiple items on toast where the Checkbox is Checked

I am able to load data from database into my custom ListView, but not able to display the item(relevant, courseName to be precise) when the checkbox is checked(multiple checkboxes can be checked) on toast when I press button.
Here is my Adapter code:
public class CourseSelectionAdapter extends ArrayAdapter<CourseDisplay>{
private Context mContext;
private LayoutInflater mInflater;
int layoutResourceId;
public static List<CourseDisplay> mDataSource;
public static int checkBoxCounter;
public CourseSelectionAdapter(Context context, int layoutResourceId, List<CourseDisplay> items) {
super(context, layoutResourceId, items);
mContext = context;
mDataSource = items;
this.layoutResourceId = layoutResourceId;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
checkBoxCounter = 0;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public CourseDisplay getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
//4
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
// Get view for row item
View row = convertView;
ViewHolder holder;
holder = null;
CourseDisplay courseDisplay = getCourse(position);
// 1
if (row == null) {
// 2
row = mInflater.inflate(R.layout.custom_listview_layout, parent, false);
// 3
holder = new ViewHolder();
holder.courseCodeTextView = (TextView) row.findViewById(R.id.course_id_display);
holder.courseNameTextView = (TextView) row.findViewById(R.id.course_name_display);
holder.courseSelectedCheckBox = (CheckBox) row.findViewById(R.id.course_selection_checkbox);
holder.courseCodeTextView.setText(courseDisplay.getCourseCode());
holder.courseNameTextView.setText(courseDisplay.getCourseName());
holder.courseSelectedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
checkBoxCounter++;
getCourse((Integer) buttonView.getTag()).getCourseSelected();
}else {
checkBoxCounter--;
}
System.out.println("Count is: "+ checkBoxCounter);
}
});
// 4
row.setTag(holder);
} else {
// 5
holder = (ViewHolder) row.getTag();
}
// 6
holder.courseSelectedCheckBox.setTag(position);
holder.courseSelectedCheckBox.setChecked(courseDisplay.getCourseSelected());
return row;
}
private static final class ViewHolder {
public TextView courseCodeTextView;
public TextView courseNameTextView;
public CheckBox courseSelectedCheckBox;
}
CourseDisplay getCourse(int position) {
return ((CourseDisplay) getItem(position));
}
List<CourseDisplay> getBox() {
List<CourseDisplay> box = new ArrayList<CourseDisplay>();
for (CourseDisplay p : mDataSource) {
if (p.getCourseSelected())
box.add(p);
}
return box;
}
}//end class
Here is my CourseDisplay code:
package com.example.android.shustudenthelper;
import static android.R.attr.checked;
public class CourseDisplay{
private String courseCode;
private String courseName;
private boolean courseSelected;
public CourseDisplay(String courseCode, String courseName, boolean courseSelected) {
this.courseCode = courseCode;
this.courseName = courseName;
this.courseSelected = courseSelected;
}
public String getCourseCode() {
return courseCode;
}
public String getCourseName() {
return courseName;
}
public boolean getCourseSelected(){
return courseSelected;
}
}//end class
Here is my database method that gets data from Database:
public List<CourseDisplay> getAllCoursesForRegistration() {
List<CourseDisplay> courses = new ArrayList<>();
openDataBase();
Cursor mCursor = database.query(TABLE_COURSES, new String[] {COLUMN_COURSE_CODE,COLUMN_COURSE_NAME,COLUMN_COURSE_SELECTED,COLUMN_COURSE_SELECTED }, null, null, null, null, null);
if(mCursor.moveToFirst()){
do{
String courseCode = mCursor.getString(0);
String courseName = mCursor.getString(1);
boolean courseSelected = Boolean.parseBoolean(mCursor.getString(2));
courses.add(new CourseDisplay(courseCode, courseName,courseSelected));
}while(mCursor.moveToNext());
}
mCursor.close();
close();//close Database
return courses;
}//end method
Here is my main activity:
public class CourseSelectionActivity extends AppCompatActivity {
public static Button confirm_Button;
public List<String> labels;
private static CheckBox saveCourseCheckBox;
public int checkAccumulator = 0;
private ListView myListView;
CourseSelectionAdapter newAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_selection);
DatabaseOpenHelper myDbHelper = new DatabaseOpenHelper(this);
try {
// check if database exists in app path, if not copy it from assets
myDbHelper.create();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
// open the database
myDbHelper.openDataBase();
myDbHelper.getWritableDatabase();
} catch (SQLException sqle) {
throw sqle;
}
//Display in ListView
populateListView();
// close the database
myDbHelper.close();
onClickConfirmButtonListener();
}//end OnCreate
private void populateListView(){
DatabaseOpenHelper myDbHelper = new DatabaseOpenHelper(this);//New Object of Database
List<CourseDisplay> courseDisplay_data = new ArrayList<CourseDisplay>();
courseDisplay_data = myDbHelper.getAllCoursesForRegistration();
newAdapter = new CourseSelectionAdapter(this,R.layout.custom_listview_layout,courseDisplay_data);
myListView = (ListView)findViewById(R.id.listview_courses);
myListView.setChoiceMode(2);
myListView.setAdapter(newAdapter);
}
public void onClickConfirmButtonListener() {
confirm_Button = (Button) findViewById(R.id.course_register_button);
confirm_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(checkBoxCounter < 1) && checkBoxCounter <= 4) {
showResult();//Show the courses selected.
Toast.makeText(CourseSelectionActivity.this, "You are directed to Notifications", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.android.shustudenthelper.NotificationSetupActivity");
startActivity(intent);}
else if (checkBoxCounter > 4){
Toast.makeText(CourseSelectionActivity.this, "You cannot select more than 4 courses", Toast.LENGTH_SHORT).show();
}else if (checkBoxCounter < 1){
Toast.makeText(CourseSelectionActivity.this, "You need to select at least one course", Toast.LENGTH_SHORT).show();
}
}
});
}
public void showResult() {
String result = "Selected Courses are :";
for (CourseDisplay p : newAdapter.getBox()) {
if (p.getCourseSelected()){
result += "\n" + p.getCourseName();
}
}
Toast.makeText(this, result+"\n",Toast.LENGTH_LONG).show();
}
}//end class
Please guide me through this.
First, add a setter method in CourseDisplay class
public boolean setCourseSelected(boolean value){
this.courseSelected = value;
}
In CourseSelectionAdapter class, when a checkbox is click, set the value of the checkbox with the method above
holder.courseSelectedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
checkBoxCounter++;
courseDisplay.setCourseSelected(isChecked);
}else {
checkBoxCounter--;
}
System.out.println("Count is: "+ checkBoxCounter);
}
});
Finally, change showResult() like this
public void showResult() {
String result = "Selected Courses are :";
for (CourseDisplay p : courseDisplay_data) {
if (p.getCourseSelected()){
result += "\n" + p.getCourseName();
}
}
Toast.makeText(this, result+"\n",Toast.LENGTH_LONG).show();
}

Get checked items id from custom listview and pass them to new activity android

I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
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 Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");

List view not getting refreshed

I have displayed all the contacts within the phone along with a check box in a list view. Now when the user checks say A and B and clicks on "ok" button, then what I want is to display the list again when making all the check box checked value to false. For that, I have created a method but when I call this method the value of the selected contacts is set to unchecked only when the list is scrolled, else it remains unchecked.
Whats the problem with my code???
Code
public void getContactSync(Context context, ArrayList<ContactModel> data) {
setListAdapter(null);
contactListAdapter = new ContactListAdapter(context, data);
setListAdapter(contactListAdapter);
// contactListAdapter.notifyDataSetChanged();
}
On OK button click
Arrays.fill(ContactListAdapter.contacts, 0);
contactListFragment.getContactSync(getActivity(), dbHandler.getAlGetContacts());
Custom Adapter
public class ContactListAdapter extends BaseAdapter {
private Context context;
private ArrayList<ContactModel> data;
DbHandler dbHandler;
public static int[] contacts;
static ArrayList<String> contactsSepetrated;
public static ArrayList<String> contactsId;
public ContactListAdapter(Context context, ArrayList<ContactModel> data) {
this.context = context;
this.data = data;
contacts = new int[data.size()];
contactsSepetrated = new ArrayList<String>();
contactsId = new ArrayList<String>();
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
final ViewHolder holder;
dbHandler = new DbHandler(context);
if (view == null) {
holder = new ViewHolder();
view = LayoutInflater.from(context).inflate(R.layout.contact_custom_list, viewGroup, false);
holder.tvContact = (TextView) view.findViewById(R.id.tv_contact_name);
holder.checkBox = (CheckBox) view.findViewById(R.id.cb_contact_checkbox);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (compoundButton == holder.checkBox) {
if (b) {
contacts[i] = 1;
//dbHandler.updateContactList(data.get(i).getUserID(), 1);
//
} else {
contacts[i] = 0;
}
}
}
}
);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (contacts[i] == 1) {
contactsSepetrated.add(data.get(i).getContactName());
Log.e("Contact values", contactsSepetrated.toString());
contactsId.add(data.get(i).getUserID());
Log.e("Position", "" + i);
} else if (contacts[i] == 0) {
contactsSepetrated.remove(data.get(i).getContactName());
contactsId.remove(data.get(i).getUserID());
Log.e("Contact values", contactsSepetrated.toString());
Log.e("Position", "" + i);
}
ShareWithinpocketDocs.etContactsList.setText(contactsSepetrated.toString().subSequence(1, contactsSepetrated.toString().length() - 1));
}
});
if (contacts[i] == 0) {
holder.checkBox.setChecked(false);
// emailSeperated.remove(data.get(i).getEmail());
// Log.e("Email values", emailSeperated.toString());
// ShareWithinpocketDocs.etEmailLists.setText(emailSeperated.toString());
} else {
holder.checkBox.setChecked(true);
// emailSeperated.add(data.get(i).getEmail());
// Log.e("Email values", emailSeperated.toString());
}
holder.tvContact.setText(data.get(i).getContactName());
return view;
}
private class ViewHolder {
TextView tvContact;
CheckBox checkBox;
}
}
on click of checkbox inside adapter just call notifydatasetchanged() it will solve your problem
holder.checkBox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton,
boolean b) {
if (compoundButton == holder.checkBox) {
if (b) {
contacts[i] = 1;
// dbHandler.updateContactList(data.get(i).getUserID(),
// 1);
//
notifyDataSetChanged();
} else {
contacts[i] = 0;
notifyDataSetChanged();
}
}
}
}
);
if you want to refresh adapter on ok button click add this to ok button click
adapter.notifydatasetchagned()
Try to call setListAdapter(contactListAdapter); again inside your onClick()

onclick button is not working in listview

My project contains listView(homelistView) that contains button(btnList).
When I click on button(btnList) it must go to another Activity. I tried a lot but I didn't find a good example.
Please suggest me a good example regarding this.
Below is my code:
Here is my listview contains button. When on click of button it must go to other activity
--------------------------------A--
text text button(btnList) B
--------------------------------C---
text text BUTTON(btnList) D
--------------------------------E--
homempleb.xml
Before i used this code in xml. buttonlist worked fine for me as per below code
<ListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</ListView>
EfficientAdapter.java
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
In your ViewHolder class you need to add `Button btnList.`
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
homempleb.xml
Currently i added scroll index to my listview and changed the code as per below.. Listbutton is not working for me now.. Plz help me u can see code for quick reference in EfficientAdapter.JAVA-----> getview method--->holder.btnList.
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
MainActivity.java
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView listView;
// private IndexableListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
// EfficientAdapter2 objectAdapter1;
int textlength = 0;
private CheckBox checkStat, checkRoutine, checkTat;
private ArrayList<Patient> patientListArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan", " txtScanResult ");
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this,
QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed",
Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE",
Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
// listView = (IndexableListView) findViewById(R.id.homelistView);
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(true);
objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);
Button refreshButton = (Button) findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// objectAdapter1 = new EfficientAdapter2(MainActivity.this);
objectAdapter = new EfficientAdapter(MainActivity.this);// adapter
// with
// new
// data
listView.setAdapter(objectAdapter);
Log.i("notifyDataSetChanged", "data updated");
// objectAdapter1.notifyDataSetChanged();
objectAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.JAVA
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<Patient> patientListArray;
private LayoutInflater mInflater;
private Context context;
ViewHolder holder;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
String patientListJson = CountriesList.jsonData;
JSONObject jssson;
try {
jssson = new JSONObject(patientListJson);
patientListJson = jssson.getString("PostPatientDetailResult");
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray();
patientListArray = new ArrayList<Patient>();
for (JsonElement obj : Jarray) {
Patient patientList = gson.fromJson(obj, Patient.class);
patientListArray.add(patientList);
Log.i("patientList", patientListJson);
}
}
/**
* sorting the patientListArray data
*/
public void sortMyData() {
// sorting the patientListArray data
Collections.sort(patientListArray, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Patient p1 = (Patient) o1;
Patient p2 = (Patient) o2;
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
}
public int getCount() {
return patientListArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.name);
holder.text2 = (TextView) convertView.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView.findViewById(R.id.date);
holder.text4 = (TextView) convertView.findViewById(R.id.age);
holder.text5 = (TextView) convertView.findViewById(R.id.gender);
holder.text6 = (TextView) convertView.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView.findViewById(R.id.bedno);
holder.btnList = (Button) convertView.findViewById(R.id.listbutton);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(Util.formatN2H(patientListArray.get(position)
.getName()));
holder.text2.setText(patientListArray.get(position).getMrnNumber());
holder.text3.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text4.setText(Util.formatN2H(patientListArray.get(position)
.getAge()));
holder.text5.setText(Util.formatN2H(patientListArray.get(position)
.getGender()));
holder.text6.setText(Util.formatN2H(patientListArray.get(position)
.getWard()));
holder.text7.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text8.setText(Util.formatN2H(patientListArray.get(position)
.getBed()));
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getPositionForSection(int section) {
// sorting the patientListArray data
sortMyData();
// If there is no item for current section, previous section will be
// selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j)
.getName().charAt(0)),
String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j).getName()
.charAt(0)),
String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
The problem is in onInterceptTouchEvent method. You are using IndexableListView from woozzu, and this class overrides onInterceptTouchEvent to return true. This means that IndexableListView always steal touch events from your child's views so it can provide it to IndexScroller. You can change this behavior if instead of returning true you enter this condition:
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mScroller != null && mScroller.contains(ev.getX(), ev.getY()))
return true;
return super.onInterceptTouchEvent(ev);
}
This way only events meant to interact with IndexScroller will be consumed. Other events will be propagated to children's views, and your button will be clickable.
In your Efficient adapter class declare ViewHolder holder outside getView method
and do as MoshErsan said.
Also Change your
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
to
convertView = mInflater.inflate(R.layout.homemplebrowview, parent,false);
in your adapter, just move
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
just before return convertView;
you need to set the listener every time the adapter returns a view.

onclick button in listview in android

My project contains listView(homelistView) that contains button(btnList).
When I click on button(btnList) it must go to another Activity. I tried a lot but I didn't find a good example.
Please suggest me a good example regarding this.
Below is my code:
Here is my listview contains button. When on click of button it must go to other activity
--------------------------------A--
button(btnList) B
--------------------------------C---
BUTTON(btnList) D
--------------------------------E--
homempleb.xml Before i used this code in xml. buttonlist worked fine for me as per Mohith verma sample
<ListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</ListView>
homempleb.xml Currently i added scroll index to my listview and changed the code as per below.. Listbutton is not working for me now..Plz help me
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
MainActivity.java
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView listView;
// private IndexableListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
// EfficientAdapter2 objectAdapter1;
int textlength = 0;
private CheckBox checkStat, checkRoutine, checkTat;
private ArrayList<Patient> patientListArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan", " txtScanResult ");
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this,
QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed",
Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE",
Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
// listView = (IndexableListView) findViewById(R.id.homelistView);
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(true);
objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);
Button refreshButton = (Button) findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// objectAdapter1 = new EfficientAdapter2(MainActivity.this);
objectAdapter = new EfficientAdapter(MainActivity.this);// adapter
// with
// new
// data
listView.setAdapter(objectAdapter);
Log.i("notifyDataSetChanged", "data updated");
// objectAdapter1.notifyDataSetChanged();
objectAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.JAVA
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<Patient> patientListArray;
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
String patientListJson = CountriesList.jsonData;
JSONObject jssson;
try {
jssson = new JSONObject(patientListJson);
patientListJson = jssson.getString("PostPatientDetailResult");
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray();
patientListArray = new ArrayList<Patient>();
for (JsonElement obj : Jarray) {
Patient patientList = gson.fromJson(obj, Patient.class);
patientListArray.add(patientList);
Log.i("patientList", patientListJson);
}
}
/**
* sorting the patientListArray data
*/
public void sortMyData() {
// sorting the patientListArray data
Collections.sort(patientListArray, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Patient p1 = (Patient) o1;
Patient p2 = (Patient) o2;
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
}
public int getCount() {
return patientListArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.name);
holder.text2 = (TextView) convertView.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView.findViewById(R.id.date);
holder.text4 = (TextView) convertView.findViewById(R.id.age);
holder.text5 = (TextView) convertView.findViewById(R.id.gender);
holder.text6 = (TextView) convertView.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView.findViewById(R.id.bedno);
holder.btnList = (Button) convertView.findViewById(R.id.listbutton);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(Util.formatN2H(patientListArray.get(position)
.getName()));
holder.text2.setText(patientListArray.get(position).getMrnNumber());
holder.text3.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text4.setText(Util.formatN2H(patientListArray.get(position)
.getAge()));
holder.text5.setText(Util.formatN2H(patientListArray.get(position)
.getGender()));
holder.text6.setText(Util.formatN2H(patientListArray.get(position)
.getWard()));
holder.text7.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text8.setText(Util.formatN2H(patientListArray.get(position)
.getBed()));
**
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { Intent next=new
Intent(context, Home.class); context.startActivity(next);
} });
**
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getPositionForSection(int section) {
// sorting the patientListArray data
sortMyData();
// If there is no item for current section, previous section will be
// selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j)
.getName().charAt(0)),
String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j).getName()
.charAt(0)),
String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
First remove btnList, btnScan from your MainActivity class.
In your EfficientAdapter class add object Context Context
Change your contructor:
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
to:
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
In your ViewHolder class you need to add Button btnList.
Then in getview method find its view using holder.btnList
Then use:
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
in your getview method before return convertView.
try this..
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_layout_ip_addtional_users, null);
}
//Handle TextView and display string from your list
TextView listItemText2 = (TextView)view.findViewById(R.id.list_item_string_name);
listItemText2.setText(list.get(position));
ImageButton button8 = (ImageButton) view.findViewById(R.id.ip_additional_user_edit);
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, IPAdditionalUsersEdit.class);
context.startActivity(intent);
}
});
return view;
}

Categories

Resources