Code keeps running without proper sequence of input - javascript

In the OnClickListener, addFood needs the date and time input from the datepicker fragment.
How can i make it wait till the input is done by the user?
Button breakfastAdd = findViewById(R.id.breakFastButton);
breakfastAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (breakfastSearch.getCount() == 0) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.emptySelectionLayout));
TextView text = layout.findViewById(R.id.toastText);
text.setText(R.string.selectedIsEmpty);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Log.d("list is", "empty");
} else {
new datePickerFragment().show(getSupportFragmentManager(), "datePicker");
addFood(context, breakfastDate, breakfastSearch, 1);
}
}
});

You should call your addFood(context, breakfastDate, breakfastSearch, 1); as an onChange in datePickerFragment instead.

You can put this code in you OnClickListener it will create DatePickerDialog and you will get date after you can put rest of the code:
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
int getMonth = month + 1;
int getDay = dayOfMonth;
String setMonth;
String setDay;
if (getMonth < 10)
setMonth = "0" + String.valueOf(getMonth);
else
setMonth = String.valueOf(getMonth);
if (getDay < 10)
setDay = "0" + String.valueOf(getDay);
else
setDay = String.valueOf(getDay);
String getDate = setMonth + "/" + setDay + "/" + year;
//You have date which user picked here you can continue with rest of your code, Inflate layout etc.
}
}, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_WEEK));
datePickerDialog.show();

Related

looping the time with time picker in android

I am Selecting the time from the picker in android as 2:00
I want to loop the time, like save the values in database as 2 then 3 then 4 and goes on.
How can i achieve this.
This is the code i have so far:
Time = String.valueOf(hourOfDay).toString() + ":" + String.valueOf(minute).toString();
Hour = Integer.parseInt(String.valueOf(hourOfDay));
for (DataSnapshot history : dataSnapshot.getChildren()) {
MainService = history.getKey();
Hour = Hour + 1;
Time = Hour + ":00";
Log.d("OpDOoesnotexsist", "Create new");
Log.d("Time hfinal", "Time befoore is" +Time);
Log.d("Hour hfinal", "Hour befoore is" +Hour);
Log.d("Hour hfinal", "Main Service for no Op is" +MainService);
Log.d("Time here is", "Hour is" +Time);
DatabaseReference CreateOp=FirebaseDatabase.getInstance().getReference().child("Op").child(NameofSpa).child(SELETEDDATE).child(MainService).child(String.valueOf(Time));
CreateOp.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Map userInfo = new HashMap();
userInfo.put("Count", 1);
CreateOp.updateChildren(userInfo);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Log.d("Time ", "Time here is final" +Time);
when i select 2, It starts with 3 then 4 and goes on. and saving it also from 3 not from 2.
Any help would be appreciated.

What is the best and most efficient way to get data by JavaScript from EntityFramework database in my case?

Right now in my ASP.NET MVC Core2 project I have a model in EF database, that contains several properties:
public class SchoolEvents
{
public long ID { get; set; }
[Required]
[StringLength(40, ErrorMessage = "Max 40 characters")]
public string Title { get; set; }
[Required]
public string Description { get; set; }
[Required]
public DateTime WhenHappens { get; set; }
}
I have no problem to get data from the EF database by MVC Razor Views. But I am using JavaScript Calendar plugin in one of my Views, that will mark events from db on it. To do it, the script is taking data in format:
{ title: 'EventTitle', description: 'Few words about the event', datetime: new Date(2018, 8, 14, 16) }
It seems to be obvious, that I supposed to use a for loop in the script, iterating on db objects.
As I am still noob about JS, right now the only way I know to do it is:
-to create JSON file in the controller:
[Route("events")]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ActionResult Comments()
{
var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
return Json(_events);
}
-in JS file I can use kinf of loadEventsFromServer() function, that uses XMLHttpRequest or Fetch and parsing it (I do not know yet how to do the parsing, I will be happy to get some suggestions),
And that it is it. Do you have some other ideas how to do it?
EDIT:
Update with part of plugins code, for console error d is undefined:
for (var i = 0; i < 42; i++) {
var cDay = $('<div/>');
if (i < dWeekDayOfMonthStart) {
cDay.addClass('c-day-previous-month c-pad-top');
cDay.html(dLastDayOfPreviousMonth++);
} else if (day <= dLastDayOfMonth) {
cDay.addClass('c-day c-pad-top');
if (day == dDay && adMonth == dMonth && adYear == dYear) {
cDay.addClass('c-today');
}
for (var j = 0; j < settings.events.length; j++) {
var d = settings.events[j].datetime;
if (d.getDate() == day && d.getMonth() == dMonth && d.getFullYear() == dYear) {
cDay.addClass('c-event').attr('data-event-day', d.getDate());
cDay.on('mouseover', mouseOverEvent).on('mouseleave', mouseLeaveEvent);
}
}
cDay.html(day++);
} else {
cDay.addClass('c-day-next-month c-pad-top');
cDay.html(dayOfNextMonth++);
}
cBody.append(cDay);
}
I will suggest you to use ajax request.
Javascript : Ajax
$.ajax({
type: 'POST',
url: '#URL.Action("Comments","Controller")',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: {},
success: function (data) {
var events = new Object();
events = $.map(data.d, function (item, i) {
for (var j = 0; j < data.d.length; j++) {
var event = new Object();
var startDate = Date.parse(item.WhenHappens )
event.start = startDate;
event.title = item.Title;
event.backgroundColor = "#c6458c";
event.description = item.Description;
return event;
}
})
callCalender(events);
},
error:function(e){
}
});
Controller
[Route("events")]
[HttpPost]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public ActionResult Comments()
{
var _events= _context.Events.OrderBy(c => c.ProductID).ToList(); //yes, I know, I should use repository in the best practice
return Json(_events);
}

How to convert c# list to Jquery e-calendar events?

I have a jquery events calendar (e-calendar) in the front end and retrieving the events from SharePoint calendar (c#), how can I convert this c# code to be displayed in the jquery e-calendar events?
Jquery events calendar:
https://github.com/jhonis/e-calendar
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SPListItemCollection corporateCalendarListItems = GetCorporateCalendarItems();
if (corporateCalendarListItems != null) { AddCorporateCalendarEventsToUI(corporateCalendarListItems); }
}
}
private SPListItemCollection GetCorporateCalendarItems()
{
using (SPSite wadiSite = SPContext.Current.Site)
{
using (SPWeb wadiWeb = wadiSite.OpenWeb())
{
wadiWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList corporateCalendarList = wadiWeb.Lists.TryGetList("Corporate Calendar");
// Return the last item
if (corporateCalendarList != null)
{
DateTime todayDate = DateTime.Now;
string month = todayDate.ToString("MM");
string year = todayDate.ToString("yyyy");
string endOfMonthDate = year + "-" + month + "-30";
string startOfMonthDate = year + "-" + month + "-01";
SPQuery qry = new SPQuery();
qry.Query = #"<Where><And><And><Eq><FieldRef Name='Category' /><Value Type='Choice'>Holiday</Value></Eq><Geq><FieldRef Name='EventDate' /><Value Type='DateTime'>"+startOfMonthDate+"</Value></Geq></And><Leq><FieldRef Name='EventDate' /><Value Type='DateTime'>" + endOfMonthDate + "T12:00:00Z</Value></Leq></And></Where><OrderBy><FieldRef Name='EventDate' /></OrderBy>";
qry.ViewFields = #"<FieldRef Name='Title' /><FieldRef Name='EventDate' /><FieldRef Name='FileRef' /><FieldRef Name='EndDate' /><FieldRef Name='Category' />";
SPListItemCollection corporateCalendarListItems = corporateCalendarList.GetItems(qry);
return corporateCalendarListItems;
}
return null;
}
}
}
private void AddCorporateCalendarEventsToUI(SPListItemCollection corporateCalendarListItems)
{
List<CalendarEvent> calendarEvents = new List<CalendarEvent>();
foreach (SPListItem corporateCalendarListItem in corporateCalendarListItems)
{
CalendarEvent calendarEvent = new CalendarEvent();
calendarEvent.Title = corporateCalendarListItem["Title"].ToString();
if(corporateCalendarListItem["EventDate"] != null)
{
calendarEvent.StartDate = DateTime.Parse(corporateCalendarListItem["EventDate"].ToString());
}
if (corporateCalendarListItem["EndDate"] != null)
{
calendarEvent.EndDate = DateTime.Parse(corporateCalendarListItem["EndDate"].ToString());
}
calendarEvent.Category = "Test";
calendarEvent.AllDay = false;
calendarEvents.Add(calendarEvent);
}
}

How to disable function onclick programmatically button

this is my programmatically button, there is the error null pointer exception in logcat.
This is my way to loop the button.But the disable button for the button cannot function.When i click on "save" button the programmatically button will disable. is it my way to disable button is incorrect?
String CountQuery = "SELECT * FROM Category";
db = new DBController(getActivity());
SQLiteDatabase db2 = db.getReadableDatabase();
Cursor cursor1 = db2.rawQuery(CountQuery, null);
{
int num = cursor1.getCount();
Button[] valueB = new Button[num];
for (int i = 1; i < num; i++) {
String SelectQuery = "SELECT * FROM Category where CategoryID='" + i + "'";
db = new DBController(getActivity());
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor cursor = db1.rawQuery(SelectQuery, null);
if (cursor.moveToNext()) {
String categoryName = cursor.getString(1);
String coordinateX = cursor.getString(2);
String coordinateY = cursor.getString(3);
valueB[i] = new Button(getActivity());
valueB[i].setText("" + categoryName);
valueB[i].setId(i);
valueB[i].setOnTouchListener(this);
params = new RelativeLayout.LayoutParams(300, 100);
params.leftMargin = Integer.parseInt(coordinateX);
params.topMargin = Integer.parseInt(coordinateY);
final int finalI = i;
valueB[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "asdasd" + finalI, Toast.LENGTH_SHORT).show();
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
viewPager.setCurrentItem(finalI);
}
});
mRrootLayout.addView(valueB[i],params);
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (i[0] = 1; i[0] < num; i[0]++) {
valueB[i[0]].setOnTouchListener(null);
}
}
});
}
}
You can disable the onclick listener by using valueB[i].setOnClickListener(null);
you can disable the button by using setClickable method.
valueB[i].setClickable(false);
or you can user setEnabled method also like
valueB[i].setEnabled(false);

MVC4 Client Site Split Dropdowns Date Validation

I've been trying to get some custom client site date validation working and so far I cannot seem to get it to work properly.
I have a custom date editor defined like this:
#model DateTime?
#{
if (Model.HasValue)
{
int day = Model.Value.Day;
int month = Model.Value.Month;
int year = Model.Value.Year;
}
List<SelectListItem> days = new List<SelectListItem>();
for (int i = 1; i <= 31; i++)
{
days.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Day == i});
}
List<SelectListItem> months = new List<SelectListItem>();
for (int i = 1; i <= 12; i++)
{
months.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Month == i});
}
List<SelectListItem> years = new List<SelectListItem>();
var minYear = DateTime.Now.Year - 100;
var maxYear = DateTime.Now.Year - 18;
for (int i = maxYear; i >= minYear; i--)
{
years.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Year == i });
}
}
#Html.DropDownList("days", days, "Day", new { #class="form__select" } )
#Html.DropDownList("months", months, "Month", new { #class="form__select" } )
#Html.DropDownList("years", years, "Year", new { #class="form__select" } )
And I have a custom validation attribute defined like this:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class DoBValidatorAttribute : ValidationAttribute, IClientValidatable
{
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
List<ModelClientValidationRule> clientRules = new List<ModelClientValidationRule>();
ModelClientValidationRule validDateRule = new ModelClientValidationRule
{
ErrorMessage = "Please enter a valid date.",
ValidationType = "validdate"
};
validDateRule.ValidationParameters.Add("dayelement", metadata.PropertyName + ".days");
validDateRule.ValidationParameters.Add("monthelement", metadata.PropertyName + ".months");
validDateRule.ValidationParameters.Add("yearelement", metadata.PropertyName + ".years");
clientRules.Add(validDateRule);
return clientRules;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dateResult;
int day = Convert.ToInt32(validationContext.Items["days"]);
int month = Convert.ToInt32(validationContext.Items["months"]);
int year = Convert.ToInt32(validationContext.Items["years"]);
// Put date parts together and check is valid...
if (DateTime.TryParse(year + "/" + month + "/" + day, out dateResult))
{
return ValidationResult.Success;
}
// Not valid
return new ValidationResult(string.Format(ErrorMessageString, validationContext.DisplayName));
}
}
In order to (try) and wire all this together I also have this in my JavaScript:
jQuery.validator.unobtrusive.adapters.add(
'validdate', // notice this is coming from how you named your validation rule
['dayelement'],
['monthelement'],
['yearelement'],
function (options) {
options.rules['datepartcheck'] = options.params;
options.messages['datepartcheck'] = options.message;
}
);
jQuery.validator.addMethod('datepartcheck', function (value, element, params) {
var year = params[2];
var month = params[1];
var day = params[0];
var birthDate = year + '/' + month-1 + '/' + day;
var isValid = true;
try {
// datepicker is a part of jqueryUI.
// include it and you can take advantage of .parseDate:
$.datepicker.parseDate('yy/mm/dd', birthDate);
}
catch (error) {
isValid = false;
}
return isValid;
}, '');
I've put a breakpoint on all these methods but the GetClientValidationRules method is never called which I think means that the rules are never going to be applied to the HTML for one thing.
What am I doing wrong here? I just cannot figure it out. If I could I would ditch all of it and use a plain datepicker but the client is insistent on this format.
UPDATE
Just to be clear in the generated HTML the controls generated are three <select> inputs.
I'm wondering if it might be better to split this into three separate int properties on my model and use a range validator instead.

Categories