Why my label shows "String called name" Null - javafx

I have an assignment project for my collage and when i try to show Welcome Label it shows the string as Null. Maybe because it's the initial value of the string which being saved when i run the program yet i can solve that and it faces me a lot
public void getData() {
String username = crntUsername.passUsername();
i = crntCustomer.search(username);
name = crntCustomer.passName(i);
}
#Override
public void initialize(URL location, ResourceBundle resources) {
welcomeLabel.setText("Welcome "+ name);
}
I expect that my String should be shown instead of Null

Related

Changing JavaFX nodes in Firebase onDataChange not working

I'm working on a JavaFX admin application that works with Firebase Realtime Database. I've created a ValueEventListener that acquires the data I need in onDataChange. With this data I want to call a call a method that does something with this data. The problem I ran into is that changing JavaFX elements from inside this onDataChange method isn't working at all.
I've tried narrowing the problem down by putting everything in one class and put all the functionality in the onDataChange method, but that wouldn't work either.
What's confusing me the most about this is that reading these elements is working just fine, while changing them doesn't result in anything. It does work when I execute this code from outside onDataChange.
Code in database helper class:
public void startDropsListener() {
dropsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
OverviewController.getInstance().changeNodes();
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Reading from database failed: " + databaseError.getCode());
}
});
}
Method for changing nodes:
public void changeNodes() {
System.out.println(title.getText()); // This does return the node's text.
title.setText("New title"); // Does not update the node's text.
}
UPDATE:
Printing the title after changing seems to be working, so the value appears to update despite it not showing. Here's the instance related code in case that might be the issue:
private static OverviewController instance;
public OverviewController() {
instance = this;
}
public static OverviewController getInstance() {
if(instance == null){
instance = new OverviewController();
}
return instance;
}
Don't make the controller a singleton.
and do like this...
public class OverviewController implements Initializable{
#FXML
public Label label;
#Override
public void initialize(URL location, ResourceBundle bundle){
DatabaseReference dropsRef = FirbaseDatabase.DatabaseReference("Node");
dropsRef.addValueEventListener(valueEventListener);
}
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Plateform.runLater(()->label.setText(dataSnashot.getValue(SomeClass.class).getLabel());
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Reading from database failed: " + databaseError.getCode());
}
});
}

Depending on Data on Firebase - build buttons including Images and Data

I'm quite new to programming and was looking quite a while now for a solution - but as I am not sure what exactly I am looking for, I decided to ask you.
Depending on the Data on Firebase I was looking to build a button including text and an image.
So for example I have a Database including:
User
Max (with the fields: University, Age, City)
Lena (with the fields: University, Age, City)
Is it possible to build a button with this Data but only if the Users are in the Database? So as there are 2 users - build 2 buttons including all the text (University, Age, City), if there would be 3 users - build 3 buttons.
Edit: Using Android Studio
I would recommend using recycler view and implementing onClick for recycler view.
This would take a lot of code:
Create xml for each item of recycler view
recycler_view_item.xml
Add recycler view to xml of current activity
3.Create a class MyUser.java like below:
public class MyUser {
private String University, City, Age;
public User(){}
public User(String University, String City) {
this.University = University;
this.City = City;
this.Age = Age;
}
public String getUniversity() { return University;}
public void setUniversity(String University) {
this.University = University;
}
public String getCity() {
return City;
}
public void setCity(String City) {
this.City = City;
}
public String getAge() {
return Age;
}
public void setAge(String Age) {
this.Age = Age;
}
}
Create adapter and view holder class
5.get user details from database in current activity :
private List<Book> userList;
userList = new ArrayList<>();
mRef = database.getReference().child("users");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> bookData = dataSnapshot.getChildren();
for(DataSnapshot d : bookData){
MyUser myUser = d.getValue(User.class);
userList.add(myUser);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Initialise the adapter with context and the userList
mAdapter = new MyRecyclerAdapter(getContext(), userList);
I have left out a lot of things like the adapter and view holder.
comment if u are stuck

Spring MVC checkboxes HTTP Status 400 The request sent by the client was syntactically incorrect

I have this simple form with 2 checkboxes and a submit button. When I submit the form, I get this error
HTTP Status 400 The request sent by the client was syntactically incorrect.
This is my POJO:
public class Menu{
private String day;
private String name;
private int price;
public Menu(){
}
public Menu(String day, String name, int price) {
this.day = day;
this.name = name;
this.price = price;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDay() {
return day;
}
public void setDay(String l) {
this.day = l;
}
#Override
public int hashCode() {
int hash = 3;
hash = 7 * hash + this.day.hashCode();
hash = 7 * hash + this.name.hashCode();
return hash;
}
#Override
public boolean equals(Object object) {
boolean result = false;
System.out.println("ARE YOU EVER CALLLED HOW MANY TIMES");
if (object == null || object.getClass() != getClass()) {
result = false;
} else {
Menu sc = (Menu) object;
if (this.day == sc.getDay() && this.name == sc.getName()
&& this.price == sc.getPrice()) {
result = true;
}
}
return result;
}
This is my Order class:
public class Order {
private List<Menu> menus = new ArrayList<Menu>();
public Order(){}
public Order(ArrayList<Menu> menus){
this.menus = menus;
}
public List<Menu> getMenus() {
return menus;
}
public void setMenus(ArrayList<Menu> menus) {
this.menus = menus;
}
}
And this is my controller:
#Controller
public class RestaurantController {
#RequestMapping(value = "/menu", method = RequestMethod.GET)
public String menuPage(Model model){
Order o = new Order();
ArrayList<Menu> m = new ArrayList<Menu>();
m.add(new Menu("Sunday", "Phir Aloo", 12));
m.add(new Menu("Sunday", "Phir Cholay", 9));
model.addAttribute("today", m);
model.addAttribute("order", o);
return "/menu";
}
#RequestMapping(value = "/confirm", method = RequestMethod.POST)
public String done(#ModelAttribute(value="order") Order order, Model model){
return "/confirm";
}
And this is my menu.jsp: (http://localhost:9080/res/menu)
<form:form modelAttribute="order" method="post" action="/res/confirm">
<c:forEach items="${today}" var="r">
<form:checkbox path="menus" value="${r}" label="${r.name } ${r.price }" />
</c:forEach>
<input type="submit" value="Submit Data">
</form:form>
Now I just expect Class Order's property 'menus' to be filled with selected checkboxes. Instead I get this error "The request sent by the client was syntactically incorrect. I have looked up every possible answer on this website but nothing seems to be solving the problem.
After #R Sawant's suggestion I was able to solve the problem. Here is my Property Editor.
public class MenuTypeEditor extends PropertyEditorSupport {
public void setAsText(String text) {
setValue(new Menu(text.toUpperCase()));
}
}
I kept this class inside the same package which has Menu.java and Order.java
Now inside my controller wrote this:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Menu.class, new MenuTypeEditor());
}
And voila! Magic happened.
I hope this answer can help someone.
The problem is with the value you are posting when the check box is ticked. Look at the below code
<form:checkbox path="menus" **value="${r}"** label="${r.name } ${r.price }" />
See what have assigned to value attribute in the above line. Its whole object of menu. It will essentially post the toString() representation of the object. Since you have not implemented toString() for Menu class, something like Menu#1ed2e55e gets posted for the check box value. Spring is unable to convert this to something meaningful and hence the problem.
You have to make use of property editor support to deal with these type of situations. Property editor will help you convert string to Object and vice versa. In your case String to Menu object and vice versa. Take a look at examples of property editors. Hope this helps
Edit:- a google search got this result. Take a look at it, may help you to understand.

How to use SimpleIntegerProperty in JavaFX

I tried to populate a tableView, I followed the tutorial given in docs.oracle, but in my table there are Integer fields, so I do the same thing to add them.
The code in the information class (like Person class):
private SimpleIntegerProperty gel;
public int getGel() {
return gel.get();
}
public void setGel(int pop) {
gel.set(pop);
}
The code in the Main class:
TableColumn gel = new TableColumn("Gel");
gel.setMinWidth(100);
gel.setCellValueFactory(new PropertyValueFactory<Information, Integer>("gel"));
gel.setCellFactory(TextFieldTableCell.forTableColumn());
gel.setOnEditCommit(new EventHandler<CellEditEvent<Information, Integer>>() {
#Override
public void handle(CellEditEvent<Information, Integer> t) {
((Information) t.getTableView().getItems()
.get(t.getTablePosition().getRow()))
.setGel(t.getNewValue());
}
});
but I have errors:
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at javafx.util.converter.DefaultStringConverter.toString(DefaultStringConverter.java:34)
at javafx.scene.control.cell.CellUtils.getItemText(CellUtils.java:100)
at javafx.scene.control.cell.CellUtils.updateItem(CellUtils.java:201)
at javafx.scene.control.cell.TextFieldTableCell.updateItem(TextFieldTableCell.java:204)
The problem is in your cell factory.
TableColumn should be typed to TableColumn<Information, Integer>. Then you will see an error here:
gel.setCellFactory(TextFieldTableCell.forTableColumn());
(the same error you have on runtime). The reason is the static callback forTableColumn is only for TableColumnof type String.
For other types you have to provide a custom string converter. This will solve your problems:
gel.setCellFactory(TextFieldTableCell.forTableColumn(new StringConverter<Integer>(){
#Override
public String toString(Integer object) {
return object.toString();
}
#Override
public Integer fromString(String string) {
return Integer.parseInt(string);
}
}));

HttpSessionAttributeListener Confusion

I am reading about HttpSessionAttributeListener and here is a small example i made.
I have one doubt though. The code is given below
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
Dog d = new Dog();
d.setName("Peter");
session.setAttribute("test", d);
/*Dog d1 = new Dog();
d1.setName("Adam");
*/
d.setName("Adam");
session.setAttribute("test",d);
}
}
Here is my Listener class
public class MyAttributeListener implements HttpSessionAttributeListener {
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
System.out.println("Attribute Added");
String attributeName = httpSessionBindingEvent.getName();
Dog attributeValue = (Dog) httpSessionBindingEvent.getValue();
System.out.println("Attribute Added:" + attributeName + ":" + attributeValue.getName());
}
#Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
String attributeName = httpSessionBindingEvent.getName();
String attributeValue = (String) httpSessionBindingEvent.getValue();
System.out.println("Attribute removed:" + attributeName + ":" + attributeValue);
}
#Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
String attributeName = httpSessionBindingEvent.getName();
Dog attributeValue = (Dog) httpSessionBindingEvent.getValue();
System.out.println("Attribute replaced:" + attributeName + ":" + attributeValue.getName());
}
}
Here is my model
public class Dog {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The confusion is when i run this program, the listener calls the attribute added and
replaced perfectly. When i uncomment the code in my servlet and comment
d.setName("Adam")
The attribute replaced does get called. But the value of name remains Peter only. Why
is that? What's the reason? Another question when do we use HttpSessionAttributeListener
and HttpSessionListener in particular. Any practical usages?
Thanks,
Peter
Because the javadoc says:
Returns the value of the attribute that has been added, removed or
replaced. If the attribute was added (or bound), this is the value of
the attribute. If the attribute was removed (or unbound), this is the
value of the removed attribute. If the attribute was replaced, this is
the old value of the attribute.
In the first case, the old value and the new value are the same, so you see the new dog name.
HttpSessionListener is used to be aware of session creation and destruction. HttpSessionAttributeListener is used to be aware of new, removed and replaced attributes in the session. They're very different.

Resources