Search code examples
androidandroid-arrayadapterandroid-datepicker

Android:Button Click to show datepicker and then date from datepicker.Button is in every listview item in ArrayAdapter


I have a button in listview which is getting populated from the arrayadpater class.I have managed to get the button click to show date picker by using showdialog.But now i want the date from date picker to be shown on the same button.Problem is that datesetlistener is in activity file and how can i use that to show the date on button in arrayadapter class.? Please help!!

LessonDetailsActivity.java

private Button pPickDate;
private int pYear;
private int pMonth;
private int pDay;
/**
 * This integer will uniquely define the dialog to be used for displaying
 * date picker.
 */
static final int DATE_DIALOG_ID = 0;

/**
 * Callback received when the user "picks" a date in the dialog private
 * DatePickerDialog.OnDateSetListener pDateSetListener = new
 * DatePickerDialog.OnDateSetListener() {
 * 
 * public void onDateSet(DatePicker view, int year, int monthOfYear, int
 * dayOfMonth) { pYear = year; pMonth = monthOfYear; pDay = dayOfMonth;
 * updateDisplay(); //displayToast(); } };
 */

DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int yr, int monthOfYear,
            int dayOfMonth) {
        // TODO Auto-generated method stub
        pYear = yr;
        pMonth = monthOfYear;
        pDay = dayOfMonth;
        Log.d("Date",
                String.valueOf(new StringBuilder()
                        // Month is 0 based so add 1
                        .append(pMonth + 1).append("/").append(pDay)
                        .append("/").append(pYear).append(" ")));

    }

};

/** Updates the date in the TextView */
private void updateDisplay() {
    pPickDate.setText(new StringBuilder()
            // Month is 0 based so add 1
            .append(pMonth + 1).append("/").append(pDay).append("/")
            .append(pYear).append(" "));
}

// public static final String[] lessonTitles = new String[] {
// "Intro to fine wood working", "Your Workplace tools and materials" };

// public static final String[] lessonIds = { "5", "6" };

// public static final int[] progressValues = { 100, 100 };

// public static final String[] lessonGrades = { "80", "78"};

// public static final String[] lessonRetakeGrades = { "0", "0" };

// public static final String[] planExamDates = new String[] {
// "00/00/0000","00/00/0000" };

// public static final String[] actualExamDates = new String[] {
// "00/00/0000","00/00/0000" };

// public static final String[] retakePlanExamDates = new String[] {
// "00/00/0000","00/00/0000" };

// public static final String[] retakeActualExamDates = new String[] {
// "00/00/0000","00/00/0000" };

ListView listView;
List<LessonRowItem> rowItems;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_lesson_listview);

    savedInstanceState = this.getIntent().getExtras();
    TextView textViewCourseTitle = (TextView) findViewById(R.id.label_course_title);
    textViewCourseTitle.setText((String) savedInstanceState
            .get("course_title"));

    String courseId = (String) savedInstanceState.get("course_id");
    DataBaseHandler db = new DataBaseHandler(this);
    List<Lesson> lessonList = db.getLessonDetails(courseId);
    int size = lessonList.size();

    final String[] lessonTitles = new String[size];
    final String[] lessonIds = new String[size];
    final int[] progressValues = new int[size];
    final String[] lessonGrades = new String[size];
    final String[] lessonRetakeGrades = new String[size];
    final String[] planExamDates = new String[size];
    final String[] actualExamDates = new String[size];
    final String[] retakePlanExamDates = new String[size];
    final String[] retakeActualExamDates = new String[size];

    int j = 0;
    for (Lesson lesson : lessonList) {

        lessonTitles[j] = lesson.getLessonTitle();
        lessonIds[j] = lesson.getLessonId();

        if ("0".equals(lesson.getCompleted())) {
            progressValues[j] = 0;
        } else {
            progressValues[j] = 100;
        }

        lessonGrades[j] = lesson.getGrade();
        lessonRetakeGrades[j] = lesson.getRetakeGrade();
        planExamDates[j] = lesson.getPlanExamDate();
        actualExamDates[j] = lesson.getActualExamDate();
        retakePlanExamDates[j] = lesson.getRetakePlanExamDate();
        retakeActualExamDates[j] = lesson.getRetakeActualExamDate();
        j++;

    }

    rowItems = new ArrayList<LessonRowItem>();

    for (int i = 0; i < lessonGrades.length; i++) {
        LessonRowItem item = new LessonRowItem(lessonTitles[i],
                lessonIds[i], progressValues[i], lessonGrades[i],
                lessonRetakeGrades[i], planExamDates[i],
                actualExamDates[i], retakePlanExamDates[i],
                retakeActualExamDates[i]);
        rowItems.add(item);

    }

    listView = (ListView) findViewById(R.id.my_lesson_list);
    LessonListViewAdapter adapter = new LessonListViewAdapter(this,
            R.layout.my_lesson_list_item, rowItems);
    listView.setAdapter(adapter);

    pPickDate = (Button) findViewById(R.id.label_lesson_plan_exam_date_value);
    // pPickDate.setOnClickListener((OnClickListener) this);
    /**
     * Listener for click event of the button
     * pPickDate.setOnClickListener(new View.OnClickListener() { public void
     * onClick(View v) { showDialog(DATE_DIALOG_ID); } });
     */

    /** Get the current date */
    final Calendar cal = Calendar.getInstance();
    pYear = cal.get(Calendar.YEAR);
    pMonth = cal.get(Calendar.MONTH);
    pDay = cal.get(Calendar.DAY_OF_MONTH);

    /** Display the current date in the TextView */
    updateDisplay();
}

/**
 * Create a new dialog for date picker
 * 
 * @Override protected Dialog onCreateDialog(int id) { switch (id) { case
 *           DATE_DIALOG_ID: return new DatePickerDialog(this,
 *           pDateSetListener, pYear, pMonth, pDay); } return null; }
 */

protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:

        return new DatePickerDialog(LessonDetailsActivity.this,
                dateListener, pYear, pMonth, pDay);

    }
    return null;

}
}

LessonListArrayAdapter.java

 public class LessonListViewAdapter extends ArrayAdapter<LessonRowItem> {

Context context;
static final int DATE_DIALOG_ID = 0;

public LessonListViewAdapter(Context context, int resourceId,
        List<LessonRowItem> items) {
    super(context, resourceId, items);
    this.context = context;

}

public long getItemId(int position) {
    return position;
}

@Override
public int getPosition(LessonRowItem item) {
    // TODO Auto-generated method stub
    return super.getPosition(item);
}

public static int getDateDialogId() {
    return DATE_DIALOG_ID;
}

/* private view holder class */
private class ViewHolder {
    TextView textviewLessonTitle;
    TextView textviewLessonId;
    ProgressBar progressBarLessonLevel;
    TextView textviewLessonGrade;
    TextView textviewLessonRetakeGrade;
    TextView textviewPlanExamDate;
    TextView textviewActualExamDate;
    TextView textviewRetakePlanExamDate;
    TextView textviewRetakeActualExamDate;

}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = new ViewHolder();
    LessonRowItem rowItem = getItem(position);

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.my_lesson_list_item, null);

        holder.textviewLessonTitle = (TextView) convertView
                .findViewById(R.id.label_lesson_title);
        holder.textviewLessonId = (TextView) convertView
                .findViewById(R.id.label_lesson_id_value);
        holder.progressBarLessonLevel = (ProgressBar) convertView
                .findViewById(R.id.progressbar_lesson_level);
        holder.textviewLessonGrade = (TextView) convertView
                .findViewById(R.id.label_lesson_grade_value);
        holder.textviewLessonRetakeGrade = (TextView) convertView
                .findViewById(R.id.label_lesson_retake_grade_value);
        holder.textviewPlanExamDate = (TextView) convertView
                .findViewById(R.id.label_lesson_plan_exam_date_value);
        holder.textviewActualExamDate = (TextView) convertView
                .findViewById(R.id.label_lesson_actual_exam_date_value);
        holder.textviewRetakePlanExamDate = (TextView) convertView
                .findViewById(R.id.label_lesson_retake_plan_exam_date_value);
        holder.textviewRetakeActualExamDate = (TextView) convertView
                .findViewById(R.id.label_lesson_retake_actual_exam_date_value);

        convertView.setTag(holder);
    } else

        holder = (ViewHolder) convertView.getTag();

    holder.textviewLessonTitle.setText(rowItem.getLessonTitle());
    holder.textviewLessonId.setText(rowItem.getLessonId());
    holder.progressBarLessonLevel.setProgress(rowItem.getLessonProgress());
    holder.textviewLessonGrade.setText(rowItem.getLessonGrade());
    holder.textviewLessonRetakeGrade
            .setText(rowItem.getRetakeLessonGrade());
    holder.textviewPlanExamDate.setText(rowItem.getPlanExamDate());
    holder.textviewActualExamDate.setText(rowItem.getActualExamDate());
    holder.textviewRetakePlanExamDate.setText(rowItem
            .getRetakePlanExamDate());
    holder.textviewRetakeActualExamDate.setText(rowItem
            .getRetakeActualExamDate());

    holder.textviewPlanExamDate
            .setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Log.d("Date Picker", "Shown");
                    ((Activity) LessonListViewAdapter.this.context)
                            .showDialog(DATE_DIALOG_ID);

                }
            });

    holder.textviewPlanExamDate.setText(String.valueOf(new StringBuilder()
            // Month is 0 based so add 1
            .append("77").append("/").append("77").append("/").append("77")
            .append(" ")));

    /*
     * holder.textviewCousreTitle.setText(rowItem.getCourseTitle());
     * holder.progressBarModuleLevel
     * .setProgress((rowItem.getTotalCompleteLesson() * 100) /
     * rowItem.getTotalLesson());
     * holder.textviewModuleStatus.setText(rowItem.getTotalCompleteLesson()
     * + "/" + rowItem.getTotalLesson() + " lessons");
     * holder.textviewModuleAverage.setText(rowItem.getModuleAverage() +
     * ""); holder.textviewStartDate.setText(rowItem.getStartDate());
     * holder.textviewEndDate.setText(rowItem.getEndDate());
     */

    return convertView;
}

}

Solution

  • You're already using a custom array adapter, so not too much else needs to be done. what you need to do is set up a method in your adapter to store this date String that you want to use in it. Then you get to perform your actions right in the listener. For example:

    In your listener:

    DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
    
        @Override
        public void onDateSet(DatePicker view, int yr, int monthOfYear,
                int dayOfMonth) {
    
            ...
    
    
            String dateSet = String.valueOf(monthOfYear + 1) + "/"
                    + String.valueOf(dayOfMonth) + "/"
                    + String.valueOf(yr) + " ";
    
            adapter.setDateSet(dateSet);
        }
    };
    

    Then in your adapter:

    public class LessonListViewAdapter extends ArrayAdapter<LessonRowItem> {
    
        Context context;
        static final int DATE_DIALOG_ID = 0;
        String dateSet;
    
        public void setDateSet(String dateSet) {
            this.dateSet = dateSet;
        }
    
            ...
    

    Now you have the opportunity to set the String on the button in the array adapter that you had in mind, taking caution of the condition when the string is null. For more on this kind of stuff, check out this link

    EDIT:

    private Button pPickDate;
    private int pYear;
    private int pMonth;
    private int pDay;
    private LessonListViewAdapter adapter; // <-- add this
    

    Change this:

    LessonListViewAdapter adapter = new LessonListViewAdapter(this,
                    R.layout.my_lesson_list_item, rowItems);
    

    to:

        adapter = new LessonListViewAdapter(this,
                R.layout.my_lesson_list_item, rowItems);