Unable to call object method - java

I'm working on an android app. That uses a 'datepicker' as part of a data entry form. I've written a getter method "onDateSet" to return data from the object but i'm unable to call the method from the instance of the class.
line: datePicker.getSelectedDate(); I'm getting a 'method cannot be resolved' error
I get the same message when I try and access the variable directly. datePicker.selecteddate
I would be grateful if someone could point me in the right direction.
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
int selectedDate;
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
selectedDate = day+month+year;
}
public int getSelectedDate() {
return selectedDate;
}
}
public void showDatePickerDialog(View view) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "datePicker");
int output = datePicker.getSelectedDate();
}

You have:
DialogFragment datePicker = new DatePickerFragment();
You mean:
DatePickerFragment datePicker = new DatePickerFragment();
This is because your methods are members of your subclassed DatePickerFragment, not of the base class DialogFragment.
Essentially, when you refer to an object through its base type, the compiler only knows about the methods the base type declares. It has no way of knowing that an arbitrary DialogFragment is actually a DatePickerFragment (or any other derived type).
An alternative, if you know it is a DatePickerFragment, is to explicitly cast datePicker to a DatePickerFragment:
DialogFragment datePicker = new DatePickerFragment();
...
int output = ((DatePickerFragment)datePicker).getSelectedDate();
This, of course, will fail with a ClassCastException if datePicker isn't actually a DatePickerFragment.

Related

Waiting for TimePickerFragment to return time

New to JAVA and Android coding and trying my first practical project.
I don't understand how to make processing wait until timekeeperdialog returns a value.
In my Main Activity I have created getters and setters to variables (first time doing this btw):
private int pickhour;
private int pickminute;
public MainActivity(){
pickhour = 0;
pickminute = 0;
}
public void setpickhour(int pickhour) {
this.pickhour = pickhour;
}
public int getpickhour(){
return this.pickhour;
}
public void setpickminute(int pickminute) {
this.pickminute = pickminute;
}
public int getPickminute(int pickminute) {
return this.pickminute;
}
I call the dialog box with this, and then expecting processing to pause until the TimePicker returns a value, I have a Toast to show results. The Toast fires as soon as the Timepicker appears.
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(),"TimePicker");
Toast.makeText(getApplicationContext(), "Time Picker" + String.valueOf(pickhour) + ":" + String.valueOf(pickminute), Toast.LENGTH_LONG).show();
And my fragment looks like this :
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
private MainActivity ma = new MainActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(),this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
//Do something with the user chosen time
//Get reference of host activity (XML Layout File) TextView widget
ma.setpickhour(hourOfDay);
ma.setpickminute(minute);
}
}
I tried looping through a boolean set by the ontimeset method to force waiting on a return value, but my application just hung.
What fundamental concept am I missing? I'm on vacation, so spent a day & a half trying to figure this out.
You can try this -
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener{
private MainActivity ma = new MainActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
//Use the current time as the default values for the time picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Create and return a new instance of TimePickerDialog
return new TimePickerDialog(getActivity(),this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
//onTimeSet() callback method
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
//Do something with the user chosen time
//Get reference of host activity (XML Layout File) TextView widget
ma.setpickhour(hourOfDay);
ma.setpickminute(minute);
Toast.makeText(getApplicationContext(), "Time Picker" + String.valueOf(pickhour) + ":" + String.valueOf(pickminute), Toast.LENGTH_LONG).show();
}
}
And if you are only using fragment for timePicker there is no need of the fragment.
In this case you can try this in MainActivity -
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
cal.set(Calendar.MINUTE, minute);
setpickhour(hourOfDay);
setpickminute(minute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Time Picker");
mTimePicker.show();
Does your code work? Because you cannot pass "this" as second argument in TimePickerDialog constructor.

Open DatePicker with suggested date

I need to open a DatePicker with a default date based on the YEAR-MONTH-DAY_OF_MONTH properties of a GregorianCalendar.
Here is the code where I open the DatePicker:
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
For exemple, if my values are like this:
MyCalendar.YEAR = 2017
MyCalendar.MONTH = 2
MyCalendar.DAY_OF_MONTH = 22
The default value set when I open the DatePicker would be:
What do I have to add to do that?
Basically straight from Android | Pickers
Plus, just like any other Fragment, you can use set and get-Arguments to pass data into the fragment.
Details: Best practice for instantiating a new Android Fragment
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public static DatePickerFragment newInstance(int year,int month,int day) {
Bundle b = new Bundle();
b.putInt("year", year);
// put others...
Fragment f = new DatePickerFragment();
f.setArguments(b);
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Update using the arguments
Bundle args = getArguments();
if (args != null) {
year = args.getInt("year");
// get others...
}
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
And use that newInstance method.
DialogFragment newFragment = DatePickerFragment.newInstance(2017,02,07);
newFragment.show(getFragmentManager(), "datePicker");

How to pass date selected from CalendarView (current as default) into next Activity?

I currently have an activity with a CalendarView, I want the user to select the date from the CalendarView to be passed to the next fragment, whereby the date will be displayed in a TextView. I have looked all over, but I have no idea how to extract the date into a string, and then retrieve it again in the fragment the activity will pass the intent to.
I tried to refer to this answer: Android CalendarView: How do I get the date in correct format?
and I managed to get the date displayed in LogCat, but it doesn't pass to the fragment. If possible can someone show me how the code can be readjusted to pass it over to the fragment?
Thanks yall so much!
If you keep a reference to your Fragment in your MainActivity, you can interact with it just as any other object. An example:
MainActivity.java
MyFragment my_fragment;
...
public void onCreate() {
...
my_fragment = new MyFragment();
...
}
public void sendDateToFragment(Calendar date) {
my_fragment.setDate(date);
}
MyFragment.java
Calendar calendar;
...
public void setDate(Calendar date) {
// You can choose any type of object to accept,
// this is just an example.
calendar = date;
}
Hope this helps.
You can handle it via a Bundle:
public void send(int day, int month, int year){
Bundle date = new Bundle();
date.putInt("Day", day);
date.putInt("Month", month);
date.putInt("Year", year);
Intent in=new Intent(Activity.this,SecondActivity.class);
in.putExtras(date);
startActivity(in);
}
and in the second activity:
public Date get(){
Bundle second = getIntent().getExtras();
return new Date(second.getInt("Year"),
second.getInt("Month"),second.getInt("Day"));
}
it will return your date and you can call in the second activity Date date = get();

DateFormat produces incorrect output

I've got a couple of Buttons that initially display the current date and the current time, respectively. When clicking in the Button that displays the date, it shows a DatePickerFragment that allows the user to choose a date, and then changes the Button's text to the date selected by the user. The other Button does exactly the same but with a TimePickerFragment.
To initialize the Buttons I use the following code:
protected void onCreate(Bundle savedInstanceState){
...
df = DateFormat.getDateInstance();
tf = DateFormat.getTimeInstance();
initDate = new GregorianCalendar();
...
updateDateButtons();
updateTimeButtons();
}
private void updateTimeButtons() {
tf.setCalendar(initDate);
String text = tf.format(initDate.getTime());
btnIniTime.setText(text.substring(0, text.lastIndexOf(":")));
}
private void updateDateButtons() {
df.setCalendar(initDate);
btnIniDate.setText(df.format(initDate.getTime()));
}
Initially, both buttons behave in an expected manner: btnIniTime shows the current time, and btnIniDate shows the current date.
As I said, when the user clicks the btnIniTime button, it shows a TimePickerFragment that prompts the user to choose a time, and the selected time is correctly displayed in btnIniTime.
The problem starts with btnIniDate, that should do the same, but using a DatePickerFragment instead of a TimePickerFragment. When the user selects a date, the button then displays an incorrect date. For example, if I choose 2013 Aug 30, the displayed date turns to be 2013 Aug. 26. If I choose 2013 Sep 1, it then shows 2013 Sep 29!
The classes and methods that I use to change the date ara arranged in the following way:
public abstract static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
protected TaskActivity activity;
protected Calendar c;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (TaskActivity) activity;
}
#Override
public abstract Dialog onCreateDialog(Bundle savedInstanceState);
public void onDateSet(DatePicker view, int year, int month, int day) {
if(activity instanceof TaskActivity){
setDateResult(year, month, day);
}
}
protected abstract void setDateResult(int year, int month, int day);
}
public static class InitDatePickerFragment extends DatePickerFragment {
#Override
protected void setDateResult(int year, int month, int day) {
activity.setInitDate(year, month, day);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = activity.getInitDate();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
}
...
public Calendar getInitDate() {
return initDate;
}
public void setInitDate(int year, int month, int day){
Log.d("TaskActivity", "Year: " + year + "; Month: " + month + "; Day: " + day);
initDate.set(Calendar.YEAR, year);
initDate.set(Calendar.MONTH, month);
initDate.set(Calendar.DAY_OF_WEEK, day);
updateDateButtons();
}
When you push the button:
#Override
public void onClick(View v) {
if(v.equals(btnIniDate)){
DialogFragment newFragment = new InitDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "initDatePicker");
}
...
}
By the way, when setting the date, LogCat produces the following output (I've chosen 2013 Aug 30):
Year: 2013; Month: 7; Day:30
The Problem might be
initDate.set(Calendar.DAY_OF_WEEK, day);
in your setInitDate(). This updates only the day of the week. So your date jumps +-6
use
initDate.set(Calendar.DAY_OF_MONTH, day);

Android DatePickerDialog parameters

I'm creating button dynamically at runtime which their click event opens a datepickerdialog. So like this:
Button btnDate = new Button(this);
btnDate.setText("Date");
btnDate.setTag(new UDAControlItemTag(q.getiQuestionID(),-1,f.getiSectionID(),f.getiGroup(),-1,"Date",""));
btnDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button tempBtn = (Button)v;
UDAControlItemTag tempQ = (UDAControlItemTag)tempBtn.getTag();
showDialog(DATE_DIALOG_ID_Question);
//tempBtn.setText(Integer.toString(mTempMonth));
}
});
Then I have the listener where i can get the values and stuff but because I'm creating the controls dynamically, i keep these values of each control in an ArrayList with different properties. The issue I have is how to get the parameters i need to correctly determine which button was clicked in order to put in the correct properties for that question into the ArrayList.
private DatePickerDialog.OnDateSetListener mDateSetListenerQuestion =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mTempYear = year;
mTempMonth = monthOfYear;
mTempDay = dayOfMonth;
}
};
So in there i have the value of the dialog, but i need to have a QuestionID which is associated to the button that the user clicked, in order to put the value into the ArrayList of all the answers for all that dynamic controls on the activity. I'd really appreciate any ideas, thanks.
Instead of that listener you could use your own class that implements the DatePickerDialog.OnDateSetListener interface and also has a constructor that takes an int, the QuestionID. Something like this:
public class TheSpecialListener implements
DatePickerDialog.OnDateSetListener {
private int id;
public TheSpecialListener(int id) {
this.id = id;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mTempYear = year;
mTempMonth = monthOfYear;
mTempDay = dayOfMonth;
// id is the QuestionID so you now can identify the Button that started the dialog
}
};
Now when you click a Button you'll update a field with that Button's QuestionID that will be used in the onCreateDialog method(which I don't know how you implemented):
private int questionId;
and in the Button listener:
//...
Button tempBtn = (Button)v;
UDAControlItemTag tempQ = (UDAControlItemTag)tempBtn.getTag();
questionId = //here pass the Button's id or whatever
showDialog(DATE_DIALOG_ID_Question);
and in the onCreateDialog method instantiate the above special listener and pass it the questionId field which will hold the identifier, as it will be updated each time a Button is clicked:
DatePickerDialog spd = new DatePickerDialog(this,
new TheSpecialListener(questionId), 2012, 6, 16);

Categories

Resources