Venkata Venkata - 1 month ago 8
Android Question

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.

Answer

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