Android DatePickerDialog parameters - java

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

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.

Calling nonstatic function when TimePicker is done

I'm kind of new to Android, and I'm currently struggling with the TimePicker. So, I've got the TimePicker here:
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public String time;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
time = hourOfDay + ":" + minute;
//update global variable
MockDB.setCheckout(time);
}
}
This is working, but after the user selects a time I want to call a function in the activity the picker is in to change the button colors and text. This is in a function called ReserveProduct that extends AppCompatActivity.
public void animateButtons() {
//picker disappears until next button is clicked
Button picker = (Button) findViewById(R.id.button6);
picker.setVisibility(View.GONE);
Button picker1 = (Button) findViewById(R.id.button7);
picker1.setVisibility(View.GONE);
if (settingReturn == false) {
//first button turns gray
Button bttn1 = (Button) findViewById(R.id.buttonCheckIn);
bttn1.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getCheckout();
bttn1.setText("Check Out: 12:27 PM");
//new button appears
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setVisibility(View.VISIBLE);
settingReturn = true;
} else {
//make 2nd button inactive
Button bttn2 = (Button) findViewById(R.id.buttonCheckOut);
bttn2.setBackgroundResource(R.drawable.button_inactive);
String time = ((MockDB) this.getApplication()).getReturn();
bttn2.setText("Return: 1:27 PM");
//show new buttons
Button set = (Button) findViewById(R.id.buttonSet);
set.setVisibility(View.VISIBLE);
Button home = (Button) findViewById(R.id.buttonHome);
home.setVisibility(View.VISIBLE);
}
}
My issue is that this function is not static, so I'm not able to simply call it from the TimePicker class. I can't move the button changing functionality to the TimePicker class because I need to be able to extend AppCompatActivity, but AppCompatActivity and DialogFragment have a conflicting class. I also can't make the animateButtons() class static because then the findViewById() functionality throws an error.
Please help!!
Instantiate the class first, i.e.
(new SomeClass()).someMethod();

android AlertDialog return date value

In Mike Dalasay's examples found here:
http://www.codeofaninja.com/2011/07/android-alertdialog-example.html
He presents AlertDialog examples. I am wanting to use the Time and Date Dialogs in these examples, making the functions return the value that was set by the Time and Date Pickers.
As a newbee to Java and Android, I know how the change the return void to String, but I don't know how to pass the picker values to the return value.
Here is his original code:
Show AlertDialog with date picker.
public void alertDatePicker() {
/*
* Inflate the XML view. activity_main is in res/layout/date_picker.xml
*/
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.date_picker, null, false);
// the time picker on the alert dialog, this is how to get the value
final DatePicker myDatePicker = (DatePicker) view.findViewById(R.id.myDatePicker);
// so that the calendar view won't appear
myDatePicker.setCalendarViewShown(false);
// the alert dialog
new AlertDialog.Builder(MainActivity.this).setView(view)
.setTitle("Set Date")
.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
/*
* In the docs of the calendar class, January = 0, so we
* have to add 1 for getting correct month.
* http://goo.gl/9ywsj
*/
int month = myDatePicker.getMonth() + 1;
int day = myDatePicker.getDayOfMonth();
int year = myDatePicker.getYear();
showToast(month + "/" + day + "/" + year);
dialog.cancel();
}
}).show();
}
Where the showToast is i would set String myDate and somehow get the return value out of the function:
public String alertDatePicker() {
Thanks.
At the moment you have the variables month day and year declared in the AlertDialog class. If you move then to the calling method, or class then the scope of them will be different.
eg
int month = 0;
int day = 0;
new AlertDialog.Builder .....
}).show ();
System.out.println (month);

Unable to call object method

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.

How to change the content of the layout?

In my Android application i have a tracker activity in which i retrieve the exercises information(name , period , burned calories) from the sqlite data base based on the selected date and display these information in a linear layout , and my problem that as the user select new date the retrieved data are displayed in another "new " layout appear above the old one but what actually i want to do is to display the new retrieved data on the same layout " change the layout content with the new retrieved data ", i have tried the remove all views method but it didn't work since the data appear for few minutes then dis appear
How i can do this: when the user select a new date the new retrieved data displayed on the same layout " refresh the old data by the new one " not to display them in anew layout . how i can do that ? please help me..
java code
public class Tracker extends BaseActivity
{
private Button date_btn;
private ImageButton left_btn;
private ImageButton right_btn;
private ImageView nodata;
private TextView ex_name;
private TextView ex_BCals;
private LinearLayout excercises_LL;
private LinearLayout content_LL ;
private LinearLayout notes;
private LinearLayout details;
private int year,month,day;
private double tot_excals_burned;
private Calendar localCalendar;
private static final int DATE_DIALOG_ID=0;
private boolean has_ex_details;
private boolean has_meal_details=false;
private Cursor exercises_cursor;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.tracker);
date_btn=(Button)findViewById(R.id.btn_date);
date_btn.setText(FormatDate());
date_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar = Calendar.getInstance();
year = localCalendar.get(1);
month= localCalendar.get(2);
day = localCalendar.get(5);
showDialog(DATE_DIALOG_ID);
}
});
left_btn=(ImageButton)findViewById(R.id.btn_left);
left_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, -1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
right_btn=(ImageButton)findViewById(R.id.btn_right) ;
right_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
localCalendar.add(5, 1);
date_btn.setText(FormatDate(localCalendar,"EEEE, d/MMM/yyyy"));
RefreshExercisesData();
RefreshNoDataImage();
}
});
details=(LinearLayout)findViewById(R.id.ll_details);
notes=(LinearLayout)findViewById(R.id.ll_notes);
excercises_LL=(LinearLayout)findViewById(R.id.ll_exercises);
nodata=(ImageView)findViewById(R.id.nodata_imgV);
RefreshExercisesData();
RefreshNoDataImage();
}
private String FormatDate()
{
localCalendar = Calendar.getInstance();
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(int year, int month, int day)
{
localCalendar = Calendar.getInstance();
localCalendar.set(year, month, day);
return new SimpleDateFormat("EEEE, d/MMM/yyyy").format(localCalendar.getTime());
}
private String FormatDate(Calendar calendar , String format)
{
return new SimpleDateFormat(format).format(calendar.getTime());
}
private void RefreshExercisesData()
{
tot_excals_burned=0;
DBAdapter db = new DBAdapter(this);
db.open();
String selected_date= date_btn.getText().toString();
Log.e("date", selected_date);
exercises_cursor = db.getExerciseInfo(selected_date);
if(exercises_cursor.getCount() !=0 )
{
has_ex_details=true;
details.setVisibility(0);
nodata.setVisibility(8);
notes.setVisibility(0);
//excercises_LL.removeAllViews();
excercises_LL.setWeightSum(1.0F);
excercises_LL.setVisibility(0);
excercises_LL.setOrientation(LinearLayout.VERTICAL);
LayoutInflater exc_LayoutInflater = (LayoutInflater)getApplicationContext().getSystemService("layout_inflater");
LinearLayout layout = (LinearLayout)exc_LayoutInflater.inflate(R.layout.tracker_header_item,null);
TextView tot_ex_cals_value=((TextView)(layout).findViewById(R.id.tv_tot_cals_value));
TextView exs_title=((TextView)(layout).findViewById(R.id.tv_item_title)) ;
exs_title.setText("Exercises ");
(layout).setPadding(0, 36, 0, 0);
excercises_LL.addView((View)layout, 0);
int i = 1;
if (exercises_cursor.moveToFirst())
{
do
{
content_LL=new LinearLayout(this);
ex_name=new TextView(this);
ex_name.setText( exercises_cursor.getFloat(1)+"," +exercises_cursor.getString(0) + "min ");
ex_name.setTextColor(R.color.black);
content_LL.addView(ex_name,0);
ex_BCals=new TextView(this);
ex_BCals.setText(Round(exercises_cursor.getFloat(2)) +" ");
ex_BCals.setTextColor(R.color.color_black);
content_LL.addView(ex_BCals,1);
tot_excals_burned = tot_excals_burned+exercises_cursor.getFloat(2);
excercises_LL.addView(content_LL, i);
i++;
}
while (exercises_cursor.moveToNext());
}
tot_ex_cals_value.setText(Round(tot_excals_burned) );
}
else if(exercises_cursor.getCount()==0 ||tot_excals_burned==0)
{
has_ex_details=false;
RefreshNoDataImage();
}
exercises_cursor.close();
exercises_cursor.deactivate();
db.close();
}
private void RefreshNoDataImage()
{
if(has_ex_details==false && has_meal_details==false)
{
notes.setVisibility(8);
excercises_LL.setVisibility(8);
nodata.setImageResource(R.drawable.bg_nodata);
nodata.setVisibility(View.VISIBLE);
}
else
nodata.setVisibility(8);
}
protected Dialog onCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, this.year, this.month, this.day);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker paramDatePicker, int year, int monthofYear, int dayofMonth)
{
Tracker.this.year=year;
month=monthofYear;
day=dayofMonth;
date_btn.setText(FormatDate(year,month,day));
RefreshExercisesData();
RefreshNoDataImage();
}
};
private String Round(double num) {
return String.format("%.1f%n", num);
}}
Looks like you need to edit your question, if you want us to see any code samples.
If this is only a few texts for an exercise, it should be sufficient to give those views ids in the layout xml, so they can be referenced in your activity.
Then you can just get your views with findViewById in OnCreate, and when you receive data for the new exercise, you update those views with e.g. TextView.setText().
If you have a layout, for example one like this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/calories_burned_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Then in your Activity where you have access to your data from your sqlite db, you can modify the existing textviews within this layout by finding the view and using the setText method.
// load new data occurs above, now want to set
TextView name = (TextView)findViewById(R.id.name_textview);
name.setText(newName);
TextView calsBurned = (TextView)findViewById(R.id.calories_burned_textview);
calsBurned.setText(newCalsBurned);
It's possible, from what it sounds like in your description, that you are adding these textviews to the Activity via code each time some load button is clicked. You can do this, just hold on to the reference to these textviews you added and use setText() later on when you load a new entry (but don't create the textviews a second time).

Categories

Resources