List view not getting refreshed - android

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()

Related

Listview items with checkbox checked at start

I have a fragment with a listView.
The view is populated from a remote received JSON array as follows:
private void callVolley(){
SharedPreferences prefs3 =
getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
final String id_materia= "42";
final String num_examen= "787878";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando temas de la materia seleccionada...");
showDialog();
JsonArrayRequest jArr = new JsonArrayRequest(url+"?id="+id_materia, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// list.invalidateViews();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
Then I add programmatically a checkbox to each list item.
This is the adapter:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
At start I need all checkboxes to be checked.
Then the user can check/uncheck the desired items.
On the fragment there is a button that reads all items checkbox states.
What should I implement to put all items in status checked so that on button clicked all items are recognized as checked?
This is a screenshot at start with all items unchecked:
EDIT
Code for the button onClickListener in the fragment:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkbox = "";
checkbox_id = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
checkbox_id += hold.getId()+",";
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
String preguntas = checkbox_id;
mPref = getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPref.edit();
editor.putString("preguntas_numero_string",preguntas);
editor.putString("preguntas_string",dipilih);
Log.d("seleccion","seleccion preguntas "+preguntas);
Log.d("seleccion","seleccion dipilih "+dipilih);
editor.apply();
} else {
dipilih = "No has seleccionado ningĂșn tema.";
}
formSubmit(dipilih);
}
});
Do the following changes:
When you are adding Data to the list of Data.
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
item.setCheckbox(true)
itemList.add(item);
This will initially make the checkbox checked.
Edit:
Update your xml layout. in your CheckBox put this attribute.
android:clickable="false"
Update your list setOnItemClickListener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setCheckBox(position);
}
});
Try replacing with the below code
viewHolder.checkBox.setChecked(true);
instead of
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
Use this. It should work. -
Initially this -
viewHolder.checkBox.setChecked(true);
Then
viewHolder.checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton
buttonView,boolean isChecked) {
if(isChecked){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
}
}
);

select all option for listview with checkbox

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

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

Editext not taking user typed value

In my app there is a Edit text and below there is a list with check box.When user selects a particular checkbox,that value is being displayed in the edittext.Now if user writes some values in the edittext and then selects the checkbox,then the value which user had typed is overridden by the selected value.I want both the values to be displayed in the edittext
Code
public class EmailListAdapter extends BaseAdapter {
private Context context;
private ArrayList<EmailModel> data;
DbHandler dbHandler;
int[] emails;
static ArrayList<String> emailSeperated;
private String strEmails, strTemp;
public EmailListAdapter(Context context, ArrayList<EmailModel> data) {
this.context = context;
this.data = data;
emails = new int[data.size()];
emailSeperated = 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.email_custom_list, viewGroup, false);
holder.tvContact = (TextView) view.findViewById(R.id.tv_email_name);
holder.checkBox = (CheckBox) view.findViewById(R.id.cb_email_checkbox);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// if (emails[i] == 0) {
// holder.checkBox.setChecked(false);
// } else {
// holder.checkBox.setChecked(true);
// }
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (compoundButton == holder.checkBox) {
if (b) {
emails[i] = 1;
//dbHandler.updateContactList(data.get(i).getUserID(), 1);
//
} else {
emails[i] = 0;
}
}
}
}
);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (emails[i] == 1) {
emailSeperated.add(data.get(i).getEmail());
Log.e("Email values", emailSeperated.toString());
Log.e("Position", "" + i);
} else if (emails[i] == 0) {
emailSeperated.remove(data.get(i).getEmail());
Log.e("Email values", emailSeperated.toString());
Log.e("Position", "" + i);
}
if (!TextUtils.isEmpty(ShareWithinpocketDocs.etEmailLists.getText().toString())) {
ShareWithinpocketDocs.etEmailLists.setText(ShareWithinpocketDocs.etEmailLists.getText().toString() + "," + emailSeperated.toString().subSequence(1, emailSeperated.toString().length() - 1));
} else {
strTemp = emailSeperated.toString().substring(1, emailSeperated.toString().length() - 1);
Log.e("Email Seperated values", strTemp);
ShareWithinpocketDocs.etEmailLists.setText(strTemp);
}
}
});
if (emails[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).getEmail());
return view;
}
private class ViewHolder {
TextView tvContact;
CheckBox checkBox;
}
}
This will display what is currently in the EditText and the new text separated by a comma. Change
holder.tvContact.setText(data.get(i).getEmail());
to
String s = holder.tvContact.gettext().toString();
holder.setText(s + ", " + data.get(i).getEmail());

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.

Categories

Resources