looping the time with time picker in android - javascript

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.

Related

Attempting a Binary Search on a Object Array (Comparable)

I've been struggling a couple days now attempting to write this code. Basically,we have to perform a binarySearch based on the SSN of Comparable "Student" objects in a Student array. After performing the binarySearch on the SSN, the student who is associated with that SSN's first and last name should print out. I am finding difficulty in writing the binarySearch.
Here's my code so far:
my Student class:
public class Student implements Comparable<Student>{
private String firstName, lastName, SSN, bankAccount;
public Student(String first, String last, String ssn, String bkacct) {
this.firstName = first;
this.lastName = last;
this.SSN = ssn;
this.bankAccount = bkacct;
}
//toString method
public String toString() {
return "Employee: [FirstName = " + firstName + ", LastName = " + lastName + ", SSN = " + SSN + ", BankAccount = "
+ bankAccount + "]";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) &&
firstName.equals(((Student)other).getFirstName())&&
SSN.equals(((Student)other).getSSN()) &&
bankAccount.equals(((Student)other).getBankAccount()));
}
//Sorting the array based on SSN
public int compareTo(Student target) {
int result;
if (lastName.equals(target.getLastName()))
result = SSN.compareTo((String) target.getSSN());
else
result = SSN.compareTo((String) target.getSSN());
return result;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Object getSSN() {
return SSN;
}
public String getBankAccount() {
return bankAccount;
}
and my class where i perform my binarySearch
public class ObjectBubbleSortTest {
//setting up binarySearch to find Array
public static <Student extends Comparable<Student>> int binarySearch(Student[] student, Student target) {
int low = 0;
int high = student.length - 1;
int middle = (low+high + 1)/2;
int location = -1;
while((low <= high) && (location == -1)) {
if (student[middle].compareTo(target) == 0 ) {
location = middle;
}
else if (student[middle].compareTo(target) < 0) { //middle element too high
high = middle - 1;
}
else {
low = middle + 1;
}
middle = (low + high + 1)/2;
}
return location;
}
public static void main(String[] args) {
//EMPLOYEES OF BURGER KING
Student[] student = new Student[5];
//order: First Name, Last Name, SSN, Bank_Account_Number
student[0] = new Student("Adam", "Sarrone", "1234567", "9022345");
student[1] = new Student("Ryan", "Petrowvoksi", "4345123", "0120345");
student[2] = new Student("Jenn", "Henderson", "8124512", "564214");
student[3] = new Student("Ricky", "Jean", "3512345", "612345");
student[4] = new Student("Dare", "Ogun", "421451", "198213");
System.out.println("Original array order: \n");
for (Student element : student)
System.out.print(element + "\n");
ObjectBubbleSorter.bubbleSort(student);
System.out.println();
System.out.println("\nSorted array order: \n");
for (Student element : student)
System.out.print(element + "\n");
System.out.println();
//need helping figuring out why the binary search is not printing out
int studentName = binarySearch(student, "421451");
System.out.print(studentName);
}
}
I am also getting an error on "int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String). I understand what it means but struggling to make my binarySearch adaptable to fix that error.
Any help would be greatly appreciated. Thank you.
It would be clear if you read the error message once again carefully.
"int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String).
So basically the method signature you have is int binarySearch(Student[] student, Student target), but when you call it in main() it's binarySearch(student, "421451");
You may want to instead call the method like binarySearch(student, student[4]);

Code keeps running without proper sequence of input

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

Substring function crashes app on device (but not on emulator)

My app works fine in an emulator, but when I install it on a real device it crashes.
After some debugging I found the error was in the sub-string function.
Here's the code that I think is causing problem.
if(text.indexOf(" ")>0 && text.indexOf("d")>0) {
a = text.indexOf(" ");
b = text.indexOf("d");
}
ccs = text.substring(0,a);
crs = text.substring(a+1,b);
days = text.substring(b + 1);
For example, if text = "30 100d27";
ccs = "30", crs = "100" and days = "27"
Why would something like this work as expected on an emulator but crash on a real device?
I'll try this code in lenovo k900 its working fine.
if you have a doubt then put it into the try block like this.
try {
text = "30 100d27";
if (text.indexOf(" ") > 0 && text.indexOf("d") > 0) {
a = text.indexOf(" ");
b = text.indexOf("d");
}
ccs = text.substring(0, a);
crs = text.substring(a + 1, b);
days = text.substring(b + 1);
} catch (Exception e) {
Log.e("mye", "exception " + e);
}
and if your data is like this text = "30100d27" than its gives you java.lang.StringIndexOutOfBoundsException so ultimatly check your input.
I don't know the exact crash-cause since you haven't provided any error-logs or equal
But i can give you this:
Image a string "dexample01 " (a space at the end).
Now run your code an you will run into an exception:
text = "dexample01 ";
if (text.indexOf(" ") > 0 && text.indexOf("d") > 0) {
a = text.indexOf(" "); //a = 9
b = text.indexOf("d");
}
ccs = text.substring(0,a);
crs = text.substring(a+1,b); // a+1 = 10 -> 10 causes INDEX OUT OF BOUNDS
days = text.substring(b + 1);
Maybe you run into this exact special case and because of that your app crashes.
Try this as an example (It uses split() not indexof()):
public class Demo3 extends AppCompatActivity {
private EditText edt;
private Button b;
private TextView tv;
private String ccs;
private String crs;
private String days;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo3);
edt = (EditText) findViewById(R.id.edt);
tv = (TextView) findViewById(R.id.tv);
b = (Button) findViewById(R.id.b);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!edt.getText().toString().isEmpty()){
String[] split_space = edt.getText().toString().split(" ");
if(split_space.length==2){
ccs = split_space[0];//TODO: check ccs is a number
if(!split_space[1].isEmpty()){
String[] split_d = split_space[1].split("d");
if(split_d.length ==2 ){
crs = split_d[0];//TODO: check crs is a number
days = split_d[1];//TODO: check days is a number
}else{
crs = "null";
days = "null";
}
}else{
crs = "null";
days = "null";
}
}else{
ccs = "null";
crs = "null";
days = "null";
}
}else{
ccs = "null";
crs = "null";
days = "null";
}
tv.setText("ccs = " + ccs +"---" + "crs = " + crs + "---" + "days = " + days);
}
});
}
}
demo3.xml:----
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="null"
android:id="#+id/tv"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check"
android:layout_marginTop="50dp"
android:id="#+id/b"/>
</LinearLayout>

Sorting array-list of objects

Wanted to sort the data presented using comparative method but I can't seem to find a way to do that. I'm new to Java and so far, I'm not able to do that effectively. I only know bubble sort and it doesn't seem to function rpoperly whe trying to sort the information that the activity displays on the screen after the user presses on the button "Enter"/
public class MainActivity extends AppCompatActivity {
int quantity = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
EditText nameField = (EditText) findViewById(R.id.name_field);
String name = nameField.getText().toString();
// Figure out if the user wants whipped cream topping
CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox);
boolean hasWhippedCream = whippedCreamCheckBox.isChecked();
// Figure out if the user wants chocolate topping
CheckBox chocolateCheckBox = (CheckBox) findViewById(R.id.chocolate_checkbox);
boolean hasChocolate = chocolateCheckBox.isChecked();
// Calculate the price
int price = calculatePrice(hasWhippedCream, hasChocolate);
// Display the order summary on the screen
String message = createOrderSummary(name, price, hasWhippedCream, hasChocolate);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); //Only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for " + name);
intent.putExtra(Intent.EXTRA_TEXT, message);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
/**
* Calculates the price of the order.
* #param addhasChocolate whether or not the user wants chocolate
* #param addWhippedCream whether or not the user wants whipped cream
*/
private int calculatePrice(boolean addWhippedCream, boolean addhasChocolate)
{
int basePrice = 5;
if (addWhippedCream) {
basePrice = basePrice + 1;
}
if (addhasChocolate) {
basePrice = basePrice + 2;
}
return quantity * basePrice;
}
/**
* Create summary of the order.
*
* #param price of the order
* #param addWhippedCream is whether or not to add whipped cream to the coffee
* #param addChocolate is whether or not to add chocolate to the coffee
* #return text summary
*/
private String createOrderSummary(String name, int price, boolean addWhippedCream, boolean addChocolate) {
String priceMessage = "Name: " + name;
priceMessage += "\nAdd whipped cream? " + addWhippedCream;
priceMessage += "\nAdd chocolate? " + addChocolate;
priceMessage += "\nQuantity: " + quantity;
priceMessage += "\nTotal: $" + price;
priceMessage += "\nThank you!";
return priceMessage;
}
/**
* This method displays the given quantity value on the screen.
*/
private void displayQuantity(int numberOfCoffees) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + numberOfCoffees);
}
/**
* This increments the order number
* #param view shows the view
*/
public void increment(View view) {
if (quantity == 100) {
Toast.makeText(this, "You cannot have more than 100 coffees", Toast.LENGTH_SHORT).show();
return;
}
quantity++;
displayQuantity(quantity);
}
/**
* This decrements the order number
* #param view shows the view
*/
public void decrement(View view) {
if (quantity ==1) {
Toast.makeText(this, "You cannot have less than 1 coffee", Toast.LENGTH_SHORT).show();
return;
}
quantity--;
displayQuantity(quantity);
}
}
Use Comparator like this.
Collections.sort(mList, new Comparator<Item>() {
#Override
public int compare(Item palaceOrderModel, Item t1) {
return palaceOrderModel.getPlaceName().compareTo(t1.getPlaceName());
}
});
Use above code after adding data to your list.

c# linq SELECT list inside another list

Here My Classes
public class EmployeeProjectMaster
{
public int EmployeeProjectMasterId { get; set; }
//Class Variables
//Here i wants to get list of EmployeeProjectTransaction
//this is the way i tried
public EmployeeProjectMasterModelClient()
{
this.EmployeeProjectTransactionModel = new HashSet<EmployeeProjectTransactionModelClient>();
}
public virtual IEnumerable<EmployeeProjectTransactionModelClient> EmployeeProjectTransactionModel { get; set; }
}
public class EmployeeProjectTransaction
{
public int EmployeeProjecTransactiontId { get; set; }
public int EmployeeProjectMasterId { get; set; }
public int EmployeeId { get; set; }
public string EmployeeName {get;set;}
//Class Variables
}
public class Employee
{
public int EmployeeId { get; set; }
public string Employeefullname {get;set;}
}
Then here my linq query
//Get All Employee Project Details To Grid
public ActionResult GetAllEmployeeProjectDetails()
{
//DataTable Parameter
var draw = Request.Form.GetValues("draw").FirstOrDefault();
//Paging parameter
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Paging parameter
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//filter parameter
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
List<EmployeeProjectMasterModelClient> allEmployeeProject = new List<EmployeeProjectMasterModelClient>();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//Database Query
using (InnoESolutionsDbEntities oInnoESolutionsDbEntities = new InnoESolutionsDbEntities())
{
var v = (from Epmm in oInnoESolutionsDbEntities.EmployeeProjectMasterModels
join Eptm in oInnoESolutionsDbEntities.EmployeeProjectTransactionModels
on Epmm.EmployeeProjectMasterId equals Eptm.EmployeeProjectMasterId
select new {Epmm, Eptm});
if (!string.IsNullOrEmpty(searchValue))
{
v = v.Where(b =>
b.Epmm.ProjectModel.ProjectName.Contains(searchValue)
);
}
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
//for make sort simpler we will add system.linq.dynamic reference
//v = v.OrderBy(sortColumn + " " + sortColumnDir);
v = v.OrderBy(a => a.Epmm.EmployeeProjectMasterId + " " + a.Eptm.EmployeeProjectMasterId);
}
recordsTotal = v.Count();
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee,
EmployeeProjectTransactionModel = *************************************How to Load Trnsaction Details As A list Here
}).ToList();
}
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = allEmployeeProject });
}
Above c# function and Linq query for load angular data table. it's needs to select List Inside a List. i Wrote linq query for join. I don't know whether If it is correct or not.when you answer my question please consider that query. Have tried lot of time but i have failed. in query when i try to get record into allEmployeeProject . how to load transaction Details As a list inside allEmployeeProject list asterisk symbol indicates what i need to do. i wants list of employee for particular master record.
Here output what i want
MasterId | TransactionId |Employee Id | Employee Name
---------+---------------+------------+---------------
1 | 1 | 4 | name 1
| 2 | 2 | name 3
I think what you need is GroupBy method.
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee
});
var allEmployeeProjectsByMaster = allEmployeeProject.GroupBy(x => x.EmployeeProjectMasterId).ToList();
Now you can have transaction list grouped by EmployeeProjectMaster with allEmployeeProjectsByMaster variable, just map it to relevant data model using Select.

Categories