Android - DateTimePicker - android

im quite new to android programming. Im am trying to make use of google's latest datetimepicker function. I downloaded the source code from https://android.googlesource.com/platform/frameworks/opt/datetimepicker/+/e91a5dcdcc786074be1f6a9f2a4d79b99e34e18e and i imported it into my own project. So far i dont have any errors but i dont know how to make use of this function and test it into my project. I want to have a dialog box that will provide to the user the ability to select hours and minutes and a button click will save these data into my application.
Example: https://scontent-b-lhr.xx.fbcdn.net/hphotos-ash3/t1.0-9/10157365_10203642451081150_8056765662416057326_n.jpg

The Calendar app has the code to call the DatePickerDialog in the EditEventFragment (I think)
it looks about like this:
private class DateListener implements DatePickerDialog.OnDateSetListener {
View mView;
public DateListener(View view) {
mView = view;
}
#Override
public void onDateSet(DatePickerDialog view, int year, int month, int monthDay) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mFromDateButton) {
startTime.year = year;
startTime.month = month;
startTime.monthDay = monthDay;
startMillis = startTime.normalize(true);
setDate(mFromDateButton, startMillis);
} else {
endTime.year = year;
endTime.month = month;
endTime.monthDay = monthDay;
// Do not allow an event to have an end time before the start
// time.
if (endTime.before(mStartTime)) {
endTime.set(mStartTime);
}
endMillis = endTime.normalize(true);
setDate(mToDateButton, endMillis);
}
}
}
private DatePickerDialog mDatePickerDialog;
private class DateClickListener implements View.OnClickListener {
private Time mTime;
public DateClickListener(Time time) {
mTime = time;
}
#Override
public void onClick(View v) {
final DateListener listener = new DateListener(v);
if (mDatePickerDialog != null) {
mDatePickerDialog.dismiss();
}
mDatePickerDialog = DatePickerDialog.newInstance(listener,
mTime.year, mTime.month, mTime.monthDay);
mDatePickerDialog.setFirstDayOfWeek(PickerUtils.getFirstDayOfWeekAsCalendar( getActivity()));
mDateRangePickerDialog.setYearRange(mToday.year, mToday.year + 2);
mDateRangePickerDialog.show(getActivity().getFragmentManager(), "datePicker");
}
}

Related

Need to change variable name in a for loop everytime in Java Android Studio

I am a beginner level programmer and I am again here to take everybody's help and solve my problem. Actually I don't have an error this time but I need to do something which I am not able to,
The thing is that I want to use a for loop 3 times and everytime I have a condition to check if my Quantity1 = 0 or not, again if my Quantity2 is = 0 or not and same for the third time. I can also repeat the code 3 times but I need to do this is because, I am uploading my data to a realtime database. And I am uploading my SelectedDate1 if Quantity1 != 0 and same for the three times, but to read them I have to know that how many Quantities and SelectedDates are uploaded and for that I have created a variable OrderQuantity. But the problem is if the user has selected the 1st date and the 3rd date and not the 2nd one as its quantity is 0, so when it is uploaded it shows OrderQuantity=2and the selectedDate1 comes under 1 but the 3rd date comes under 2nd node with name 3, but it should come with the name of variable+i, I hope you understand my question. And if not, please comment and I'll provide you an english video for what I want. Hoping your help as soon as possible.-
I think there is no use of main_activity.xml as it will make my question very big.
But here goes my MainActivity.java (without imports as it was very big)
public class MainActivity extends AppCompatActivity implements DatePickerFragment.applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
//I need help here in these three if-else statements
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/1" + "/Date");
dateOne.setValue(itemOneDate);
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/2" + "/Date");
dateOne.setValue(itemTwoDate);
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/3" + "/Date");
dateOne.setValue(itemOneDate);
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString() + "/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
}
});
}
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1) {
itemOneDate = CurrentDateString;
} else if (buttonNumber == 2) {
itemTwoDate = CurrentDateString;
} else if (buttonNumber == 3) {
itemThreeDate = CurrentDateString;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Here is the image of the data saved on realtime database when 1st and 3rd date are selected.-
Also see that what I have selected on the virtual device.
And here is the link from where I learnt to make a datePickerFragment for selecting date.
Edit: go object-oriented
Edit: since my first two suggestions didn’t work for you, I am suggesting using some abstraction. Declare a class to hold a spinner and its related data, and iterate a list of such objects. Your list can hold a variable number of objects so there will be a variable number of spinners. Caveat: I don’t know Android UI programming, so may be missing a detail or two there. And I still have not compiled my code myself.
public class MySpinner {
private FirebaseDatabase database;
private Spinner quantity;
private String number;
private String itemDate;
public MySpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
this.database = database;
this.quantity = quantity;
this.number = number;
this.itemDate = itemDate;
}
/* #return true if there was a positive quantity to process, false otherwise */
public boolean processQuantity() {
if (quantity.getSelectedItem().toString().equals("0")) {
return false;
}
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
return true;
}
}
I have also object-orientedly fitted the class with a method to do the work for each spinner. Now with a list of objects of your class you may process each in turn in a loop like this:
for (MySpinner mySpinner : yourListOfMySpinners) {
if (! mySpinner.processQuantity()) { // quantity was 0
OrderQuantity -= 1;
}
}
I am leaving to yourself to fill objects into your list. There will probably also be some adjusting and tailoring that you will want to do.
Original answer follows.
Use an array or list
It’s not uncommon for beginners in programming to ask that question. It’s not quite the right question to ask. What you need is to iterate over your quantities in a loop. The solution to that is to put them into an array or list and iterate over that array or list. Code is not tested.
Spinner[] quantities = { Quantity1, Quantity2, Quantity3 };
for (int i = 0; i < quantities.length; i++) {
if (quantities[i].getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders/" + (i + 1) + "/Date");
dateOne.setValue(itemTwoDate);
}
}
While it would be possible to select a variable the way you describe, it’s neither the best, the easiest nor the nicest solution.
Or use a method
An alternative is to declare a method that does the job for each quantity and call it three times without using any loop. In your case the method may need to take quite many arguments, though, which is not ideal.
processSpinner(database, Quantity1, "/1", itemOneDate);
processSpinner(database, Quantity2, "/2", itemTwoDate);
processSpinner(database, Quantity3, "/3", itemThreeDate);
Your method may be declared like:
private void processSpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
if (quantity.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
}
}

How can I reset the calendarchangeobserver in singlerowcalendar library?

I'm using a library called singlerowcalendar in my app. My app contains a toggle button that will change the calendar mode form showing days of month to showing months of year.
days of month view
months of year view
The thing is I'm including the calendar setup code in the toggle change listener, and as a consequence the app keeps piling up calendar selection change listeners, and now I get the calendar change callback to fire multiple times.
Is there a way to keep only one calendar change listener and removing the others.
here is the code of the toggle button where I call setCalendar();
toggle.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
#Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if (isChecked && checkedId == R.id.btn_day) {
selectedTimeFrame = "day";
tvChartTitleDay.setVisibility(View.VISIBLE);
tvChartTitleMonth.setVisibility(View.GONE);
Log.d("pongo2", "day selecteeeeed");
}
if (isChecked && checkedId == R.id.btn_month) {
selectedTimeFrame = "month";
tvChartTitleDay.setVisibility(View.GONE);
tvChartTitleMonth.setVisibility(View.VISIBLE);
Log.d("pongo2", "month selecteeeeed");
}
setCalendar();
}
});
Here is the calendar setup code.
private void setCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
ArrayList<Date> list = new ArrayList<>();
if(selectedTimeFrame.equals("day")) {
calendar.add(Calendar.DAY_OF_MONTH , -700);
for (int i = 0; i < 30; i++) {
list.add(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH , -1);
}
tvMonth.setVisibility(View.VISIBLE);
tvMonth.setText(DateUtils.INSTANCE.getMonth3LettersName(calendar.getTime()));
tvYear.setText(DateUtils.INSTANCE.getYear(calendar.getTime()));
} else {
calendar.add(Calendar.MONTH , -24);
for (int i = 0; i < 30; i++) {
list.add(calendar.getTime());
calendar.add(Calendar.MONTH , -1);
}
tvMonth.setVisibility(View.GONE);
tvYear.setText(DateUtils.INSTANCE.getYear(calendar.getTime()));
}
myCalendar.setDates(list);
myCalendar.init();
myCalendar.select(5);
}
calendar change observer is here:
private void initCalendar() {
myCalendarChangesObserver = new CalendarChangesObserver() {
#Override
public void whenWeekMonthYearChanged(String s, String s1, String s2, String s3, Date date) {
}
#Override
public void whenSelectionChanged(boolean b, int i, Date date) {
if (b) {
tvMonth.setText(DateUtils.INSTANCE.getMonth3LettersName(date));
tvYear.setText(DateUtils.INSTANCE.getYear(date));
Log.d("pongo", date.toString());
loadNewData();
}
}
#Override
public void whenCalendarScrolled(int i, int i1) {
}
#Override
public void whenSelectionRestored() {
}
#Override
public void whenSelectionRefreshed() {
}
};
myCalendar.setCalendarChangesObserver(myCalendarChangesObserver);
}

How to change the appearance of an android view with a click listener and background worker?

I have an android app that users can use to check into a course at a certain time. Their daily schedule shows up on a RecyclerView as a series of CardViews. Each CardView has basic information about each class, including instructor name, course title, attendance status, etc..
The app communicates with a MySQL database through a php script which is called from an AsyncTask background worker. In the PostExecute method, the app receives a result from the php script ("Present" if checking in on time, "Tardy" if late, "Absent" if totally missed) to show in an AlertDialog. The PostExecute method also sets a String variable to equal the result.
The background worker is called from a click listener like so:
baf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int bright = status.getResources().getColor(R.color.colorPresent);
status.setBackgroundColor(bright);
lol = getAdapterPosition()+1;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Calendar c = Calendar.getInstance();
String time = sdf.format(c.getTime());
Log.d("Current Time",time);
String type="checkin";
PresentBackgroundWorker presentBackgroundWorker = new PresentBackgroundWorker(getActivity());
presentBackgroundWorker.execute(type,date,time, "t"+String.valueOf(lol));
String aaa = ontime;
status.setText(aaa);
}
});
The variable ontime (global variable) is the result from the php script, and its value is set from the background worker like so:
protected void onPostExecute(String result) {
writeitout(result);
alertDialog.setMessage(result);
alertDialog.show();
}
private void writeitout(String string) {
ontime = string;
Log.d("STATS",ontime);
}
Based on the Log.d() commands, the ontime variable is changing appropriately, but the change to the 'status' TextView is delayed by one click. That is, the result for the previous course, shows up for the present course. How do I make sure the changes in the ontime variable show up on time?
EDIT: ADDED ORIGINAL COURSEADAPTER
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.MyViewHolder> {
private List<Course> courseList;
public CourseAdapter(List<Course> sc) { this.courseList = sc; }
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title, teacher, type, status;
FloatingActionButton baf;
View subIten;
int lol;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.texttitle);
teacher = (TextView) view.findViewById(R.id.textteach);
type = (TextView) view.findViewById(R.id.texttype);
baf = (FloatingActionButton) view.findViewById(R.id.fab);
status = view.findViewById(R.id.textstatus);
subIten = (View) view.findViewById(R.id.sub_item);
}
private void bind(Course course) {
title.setText(course.getTitle());
teacher.setText(course.getTeacher());
type.setText(course.getType());
baf.setImageResource(course.getPhotoID());
baf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int bright = status.getResources().getColor(R.color.colorPresent);
status.setBackgroundColor(bright);
lol = getAdapterPosition()+1;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Calendar c = Calendar.getInstance();
String time = sdf.format(c.getTime());
Log.d("Current Time",time);
String type="checkin";
PresentBackgroundWorker presentBackgroundWorker = new PresentBackgroundWorker(getActivity());
presentBackgroundWorker.execute(type,date,time, "t"+String.valueOf(lol));
}
});
}
}
#Override
public CourseAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cardview, parent, false);
MyViewHolder viewHolder = new MyViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(final CourseAdapter.MyViewHolder holder, final int position) {
final Course course = courseList.get(position);
holder.bind(course);
}
public int getItemCount() {
return courseList.size();
}
}
The problem is you are saving the asynctask result in a variable and then later accessing it on button click.
So, what basically is happening here:
You click on a button
you start asynctask
your asynctask is still working. So, onTime still has no string. And, status.setText() is being called even before the asynctask produce result and save it in onTime.
your asynctask has finished it's job and saved the result in onTime, but the button has already finished it's rest of the code, so textview doesn't get the latest change.
you again click on the button
your asynctask again starts to work, but this time onTime has a value because previous asynctask saved it's result in it. so when status.setText() is being called, it set's the value of onTime (which holds the result from previous asynctask)
So, to fix the issue, you shouldn't update the textview on button click, rather update them inside asynctask's onPostExecute()
Just change your onPostExecute() like this and you have your solution.
protected void onPostExecute(String result) {
writeitout(result);
status.setText(result); //updating the textview directly here
alertDialog.setMessage(result);
alertDialog.show();
}
Also, remove this two lines from your baf clickListener
String aaa = ontime;
status.setText(aaa);

Handle data between different fragments using ViewModel and update

I'm trying to implement a datepicker fragment which then has to return the chosen date to the fragment (parent fragment) calling it. I've implemented an interface but it seems that the interface only gets called in the activity, not in the fragment (even if I explicitly call it). I checked this out with log files.
So then I proceeded to use ViewModel class to hold data. Now the problem is, I'm able to store the data in the ViewModel class but I don't know where to call the function of ViewModel in the parent fragment. Calling it on OnCreate/OnCreateView does not help since the fragment has already loaded. Calling it on OnResume/OnAttach crashes the app with null pointer reference.
public class ShareData extends ViewModel{
private int year, month, day;
private String date;
public void getDate(int y, int m, int d)
{
Log.d("Viewmodel is", Integer.toString(year) + " " + Integer.toString(month) + " " + Integer.toString(day));
year = y;
month = m;
day = d;
}
public String setDate()
{
return (Integer.toString(year) + "-" + Integer.toString(month) + "-" + Integer.toString(day));
}
}
This is the code from the DatePicker dialogfragment:
public void onDateSet(DatePicker view, int year, int month, int day) {
viewModel.getDate(year,month+1,day);
datePicked.onDatePicked(view, year, month+1, day);
// Do something with the date chosen by the user
}
And this is my parent fragment:
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.operations_static_new, container, false);
name = view.findViewById(R.id.patient_name);
id = view.findViewById(R.id.patient_id);
date_textview = view.findViewById(R.id.date_static);
date_textview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmDatePicker(); //this opens fragment to choose date
}
});
model = ViewModelProviders.of(getActivity()).get(ShareData.class);
date_textview.setText(model.setDate());
}
Where do I call date_textview.setText so that the date gets shown on the textview of the date picker?
I don't see any LiveData inside your ViewModel, which tells me you are not using it correctly. What you should do is bind LiveData inside the ViewModel to the fragment you want updated. After that it is trivial to recieve notification of changes in any fragment that is observing the ViewModel.
So to start with your ViewModel should look something like this:
// This will now notify the fragment that is observing of any changes made
public class SharedData extends ViewModel {
private int year, month, day;
private MutableLiveData<String> date = new MutableLiveData<>();
// This will notify observing fragments of changes
public void setDate(int y, int m, int d) {
year = y; month = m; day = d;
date.setValue(year + "-" + month + "-" + day);
}
// This is a factory method for getting the LiveData the fragment will bind to
public LiveData<String> getDate() {
return date;
}
}
Inside the fragment (parent) that updates on date change you do something like this to monitor getDate() from the example above. Which is what is needed for the update to happen after the child or anything else is done updating:
Replace
date_textview.setText(model.setDate());
with
viewModel.getDate().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String newDate) {
// Update your view with the new data
dateTextView.setText(newDate);
}
});
After the setup is done, you can call setDate(y,m,d) from wherever you want, and it will always update the fragments that are observing it.
https://developer.android.com/topic/libraries/architecture/viewmodelhttps://developer.android.com/topic/libraries/architecture/viewmodel

Getting Values from DatePicker and TimePicker

I have 2 datepickers and 2 timepickers on a screen and also a submit button. The user selects the start date, start time, end date, and end time. The program then takes these values and stores them into variables, however the variables only return the default values for these controls. Is there anyway to get the updated value from each of these controls?
My code looks like this for the edit screen:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.editscreen);
timepickerStart = (TimePicker)findViewById(R.id.timePicker1);
timepickerEnd = (TimePicker)findViewById(R.id.timePicker2);
datepickerStart = (DatePicker)findViewById(R.id.datePicker1);
datepickerEnd = (DatePicker)findViewById(R.id.datePicker2);
submitbutton = (Button)findViewById(R.id.submit);
locationText = (EditText)findViewById(R.id.locationText);
eventText = (EditText)findViewById(R.id.eventText);
}
public void DateStart(View v)
{
GlobalVariables.datepickerYearStart = datepickerStart.getYear();
GlobalVariables.datepickerMonthStart = datepickerStart.getMonth();
GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth();
}
public void DateEnd(View v)
{
GlobalVariables.datepickerYearEnd = datepickerEnd.getYear();
GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth();
GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth();
}
public void TimeStart(View v)
{
GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour();
GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute();
}
public void TimeEnd(View v)
{
GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour();
GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute();
}
public void submitClicked(View v)
{
startActivity(new Intent(this, AddToCalendar.class));
}
Rewrite
Looking at your current code, let's stick with the various get methods from DatePicker and TimePicker. However you never call DateStart() or any of the others, they look like you have them set up for an OnClickListener... Regardless, try this:
public void submitClick(View v) {
DateStart(null);
TimeStart(null);
DateEnd(null);
TimeEnd(null);
// Do what you please your GlobalVariables
}
Though I might leave out the multiple GlobalVariables and store one long value for each date/time:
public void submitClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(),
datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(),
timepickerStart.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
// And similar approach for the end time, then use them however you please
}
You need to set a listener to your DatePicker:
DatePicker picker = new DatePicker(this);
picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//set the value of the variable here
}
});

Categories

Resources