1

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

}
mango
  • 5,577
  • 4
  • 29
  • 41
user1160329
  • 135
  • 5
  • 16
  • Am not able to get the date value from activity to the arrayadapter class........... – user1160329 Nov 28 '12 at 08:00
  • As i need to settext of button from arrayadapter class..that cannot be done from the activity itself becoz listview is getting populated from arrayadapter class. – user1160329 Nov 28 '12 at 08:01
  • Show us your code that you tried, the error statements that you got, and any more pertinent information.................. – mango Nov 28 '12 at 08:02

3 Answers3

2

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);
mango
  • 5,577
  • 4
  • 29
  • 41
  • Thanks mango..one last question is that..i am not able to make instance of adapter in the datelisterner.as shown by you – user1160329 Nov 28 '12 at 09:15
  • you have to change the original adapter you had from a local variable to a field, much like these were in your code: `ListView listView; private Button pPickDate; .. etc` it wouldn't make much sense to be working on 2 different instances anyway, right? – mango Nov 28 '12 at 09:18
  • LessonListViewAdapter ad = new LessonListViewAdapter(this, R.layout.my_lesson_list_item); ad.setDateset(dateSet); this is how i doing it in datelistener – user1160329 Nov 28 '12 at 09:25
  • Did it the way you suggested....LessonListViewAdapter adapter adapet.setdate(dateset); getting a nullpointer exception – user1160329 Nov 28 '12 at 09:30
  • i edited my post. If you do that you can access that same adapter throughout. adjust the constructor how you see fit. – mango Nov 28 '12 at 09:31
  • thanks..i have done the same changes.now i m not getting any exception but the date is not shown on the button after i m clicking the set button on the date picker. – user1160329 Nov 28 '12 at 09:38
  • holder.textviewPlanExamDate.setText(getDateset()); this is how i am setting the text..is it right? – user1160329 Nov 28 '12 at 09:40
  • holder.textviewPlanExamDate.setText(dateset); – user1160329 Nov 28 '12 at 09:42
  • use the second method for in your adapter, the first for outside it. have you called `notifyDataSetChanged();` on your adapter yet? if you haven't put it in after the date is set, **BUT** you can't just put it in `getView` without any event handler or everything will lock up. call it from your activity with `adapter.notifyDataSetChanged();` if you need another way. – mango Nov 28 '12 at 09:44
  • No i haven't called any notifyDateSetchanged(). – user1160329 Nov 28 '12 at 09:50
  • One more thing..the date that will be set on the button..that will be set for each button in every item of listview regardless of on which button i have clicked for the adte picker..how i will havndle this issue..?i want only the button which was clicked to get the date from date picker. – user1160329 Nov 28 '12 at 09:56
  • the answer to this isn't a sentence long. i'll be happy to help, but you need to know that this will require more time from you. see if you get the idea from my answer here: http://stackoverflow.com/questions/13563146/changing-background-color-of-list-items-in-custom-list-view/13564133#13564133. in very short, you need to set up an ordered-list (array or otherwise) to hold which listview row was clicked, then act on it's position. – mango Nov 28 '12 at 10:01
  • Thanks for all the help..:) the link you told me to go through has got me all confused.i have got your point and now i am trying what you have suggested.Will surely need your help in as i learn.thanks once again. – user1160329 Nov 28 '12 at 10:12
0

You can directly call the datepicker

new DatePickerDialog(context, pickerListener, year, month,
                                day).show();

private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        @Override
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;    
            Log.d("@DatePickerDialog","Time:"+year);    
            date_dialog.setText(day + "-" + (month + 1) + "-" + year);    
        }    
    };
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Ram
  • 11
  • 2
0

May this one Help someone, I used this inside Recyclerview Adapterclass

 Calendar mcurrentTime = Calendar.getInstance();
        int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mcurrentTime.get(Calendar.MINUTE);

        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(CurrentActivity.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                textview.setText( selectedHour + ":" + selectedMinute);//your view here
            }
        }, hour, minute, true);
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();

I used this as following

holder.othrs.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /*DialogFragment newFragment = new TimePickerFragment();
            newFragment.show(((Dashboard2)context).getSupportFragmentManager(), "timePicker");*/

           // Calendar mcurrentTime = Calendar.getInstance();
            //int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            //int minute = mcurrentTime.get(Calendar.MINUTE);

            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    holder.time.setVisibility(View.VISIBLE);
                    holder.time.setText( selectedHour + ":" + selectedMinute);
                }
            }, 0, 0, true);
            mTimePicker.setTitle("Over Time in (Hrs:Mins)");
            mTimePicker.show();
        }

    });
Rajesh Naddy
  • 1,120
  • 12
  • 17