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.
Related
My mat-paginator in app.component.html:
<mat-paginator [pageSizeOptions]="[5, 15, 30]" [pageSize]="5" [length]="totalElements"
(page)="nextPage($event)">
</mat-paginator>
app component:
totalElements = 5;
// tslint:disable-next-line:typedef
nextPage(event: PageEvent) {
const request = {};
// #ts-ignore
request.page = event.pageIndex.toString();
// #ts-ignore
this.totalElements = request.size = event.pageSize.toString();
// #ts-ignore
this.getDevelopers(request);
}
getDevelopers:
public getDevelopers(request: {page: string, size: string}): void {
this.loading = true;
this.developerService.getAllUsers(request)
.subscribe(data => {
// #ts-ignore
this.users = data.content;
// #ts-ignore
this.totalElements = data.totalElements;
this.loading = false;
}
}
My controller:
#GetMapping
#ResponseBody
#ApiOperation(value = "Get list of all developers")
public Page<GetByIdDeveloperResponse> getAllDevelopers(
#RequestParam(name = "page", defaultValue = "0") int page,
#RequestParam(name = "size", defaultValue = "4") int size,
#RequestParam(name = "sort_by", defaultValue = "id") String sortBy
) {
Page<GetByIdDeveloperResponse> developers = developerMapper.getDeveloperResponseListFromDeveloperList(developerService.getAllDevelopers(page, size, sortBy));
return new PageImpl<GetByIdDeveloperResponse>(developers.getContent(), PageRequest.of(page, size), developers.getTotalElements());
}
I can change size of page, but i can't open other page.
< > are not aviable for me
In postman everything in is ok, but here it doesn't work.
How looks my service method:
public List<Developer> getAllDevelopers(int page, int size, String sortValue) {
logger.info("Get all developers was called, page: " + page + " size: " + size + " sort by: " + sortValue);
Pageable paging = PageRequest.of(page, size, Sort.by(sortValue));
Page<Developer> pagedResult = developerRepository.findAll(paging);
return pagedResult.getContent();
}
How repository looks:
#Repository
public interface DeveloperRepository extends PagingAndSortingRepository<Developer, String> {
Developer findById(String id);
}
How json looks:
When i am trying to GET .../developers?size=10
I got 10 total elements, i think problem is related to "totalPages": 1,
Because even if i get all elements, there will be only 1 page
Debug:
You lose your paged result data (page number, page size, etc.) in your service method when you do return pagedResult.getContent().
Consider the following:
Service method:
public Page<Developer> getAllDevelopers(int page, int size, String sortValue) {
logger.info("Get all developers was called, page: " + page + " size: " + size + " sort by: " + sortValue);
Pageable paging = PageRequest.of(page, size, Sort.by(sortValue));
return developerRepository.findAll(paging);
}
Controller method:
#GetMapping
#ApiOperation(value = "Get list of all developers")
public Page<GetByIdDeveloperResponse> getAllDevelopers(
#RequestParam(name = "page", defaultValue = "0") int page,
#RequestParam(name = "size", defaultValue = "4") int size,
#RequestParam(name = "sort_by", defaultValue = "id") String sortBy
) {
return this.developerService.getAllDevelopers(page, size, sortBy)
.map(this.developerMapper::mapToGetByIdDeveloperResponse)
}
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]);
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.
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.
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);