Java create a dynamic ObservableList - java

is it possible to create a dynamic ObservableList with relative StringProperty?
For example, using the code below, how is it possible to recreate it dynamically and add new StringProperty if necessary?
private final ObservableList<Record> recordList = FXCollections.observableArrayList();
public static class Record {
private static int trackId;
private final SimpleIntegerProperty id;
private final SimpleStringProperty name;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private Record(String name, String lastName, String email) {
this.id = new SimpleIntegerProperty(trackId);
this.name = new SimpleStringProperty(name);
this.lastName = new SimpleStringProperty(lastName);
this.email = new SimpleStringProperty(email);
trackId++;
}
public int getId() {
return this.id.get();
}
public void setId(int id) {
this.id.set(id);
}
public String getName() {
return this.name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getLastName() {
return this.lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public String getEmail() {
return this.email.get();
}
public void setEmail(String email) {
this.email.set(email);
}
}

You can't add fields to class even if will use Reflection. Maybe is better to change architecture? Let's see next class:
class Property <T> {
private final T propertyValue;
private final String propertyName;
public Property (String name, T value) {
this.propertyName = name;
this.propertyValue = value;
}
public T getValue(){
return propertyValue;
}
public String getName(){
return propertyName;
}
}
This class helps you to create new property and store it. Now, you can create List of properties and store it in class Record. And now you can dynamically add new properties. It is more flexible in my opinion.

Related

JsonMappingException: N/A when trying to deserialize JSON file

I have a User class and a Json file containing an array of Users. When trying to deserialize those users and get a List I'm getting a JsonMappingException, I don't understand what's wrong.
This is my User class:
public class User {
private StringProperty username;
private StringProperty password;
private StringProperty name;
private StringProperty surname;
private StringProperty email;
private StringProperty company;
private StringProperty phone;
private BooleanProperty canMonitorize;
private BooleanProperty canCreateProject;
private BooleanProperty canOpenProject;
private BooleanProperty admin;
public User() {}
public User(String user, String pass, String name, String surname, String email, String company, String phone,
boolean monitorize, boolean createP, boolean openP, boolean admin) {
this.username = new SimpleStringProperty(user);
this.password = new SimpleStringProperty(pass);
this.name = new SimpleStringProperty(name);
this.surname = new SimpleStringProperty(surname);
this.email = new SimpleStringProperty(email);
this.company = new SimpleStringProperty(company);
this.phone = new SimpleStringProperty(phone);
this.canMonitorize = new SimpleBooleanProperty(monitorize);
this.canCreateProject = new SimpleBooleanProperty(createP);
this.canOpenProject = new SimpleBooleanProperty(openP);
this.admin = new SimpleBooleanProperty(admin);
}
public String getUsername() {
return username.get();
}
public void setUsername(String username) {
this.username.set(username);
}
public String getPassword() {
return password.get();
}
public void setPassword(String password) {
this.password.set(password);
}
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public String getSurname() {
return surname.get();
}
public void setSurname(String surname) {
this.surname.set(surname);
}
public String getEmail() {
return email.get();
}
public void setEmail(String email) {
this.email.set(email);
}
public String getCompany() {
return company.get();
}
public void setCompany(String company) {
this.company.set(company);
}
public String getPhone() {
return phone.get();
}
public void setPhone(String phone) {
this.phone.set(phone);
}
public boolean canMonitorize() {
return canMonitorize.get();
}
public void setCanMonitorize(boolean canMonitorize) {
this.canMonitorize.set(canMonitorize);
}
public boolean canCreateProject() {
return canCreateProject.get();
}
public void setCanCreateProject(boolean canCreateProject) {
this.canCreateProject.set(canCreateProject);
}
public boolean canOpenProject() {
return canOpenProject.get();
}
public void setCanOpenProject(boolean canOpenProject) {
this.canOpenProject.set(canOpenProject);
}
public boolean isAdmin() {
return admin.get();
}
public void setAdmin(boolean isAdmin) {
this.admin.set(isAdmin);
}
}
And this is an example of the Json file:
[{"username":"admin","password":"blablabla","name":"admin","surname":"admin","email":"admin#admin.com","company":"admin","phone":"admin","admin":true}]
This is the method that should obtain the list of users:
public static List<User> getUsers(String jsonArrayStr) {
ObjectMapper mapper = new ObjectMapper();
List<User> ret;
try {
User[] userArray = mapper.readValue(jsonArrayStr, User[].class);
ret = new ArrayList<>(Arrays.asList(userArray));
} catch (IOException e) {
return new ArrayList<User>();
}
return ret;
}
The error I get when executing the code:
com.fasterxml.jackson.databind.JsonMappingException: N/A (through reference chain: object.User["username"])
When you have a public 0-args constructor it is used by default to create new POJO instance. But in your case you should not allow to create instance with default constructor because all internal fields are null and when Jackson tries to set first property, username, NullPointerException is thrown. Try to declare your constructor as below and remove default one:
#JsonCreator
public User(#JsonProperty("username") String user,
#JsonProperty("password") String pass,
#JsonProperty("name") String name,
#JsonProperty("surname") String surname,
#JsonProperty("email") String email,
#JsonProperty("company") String company,
#JsonProperty("phone") String phone,
#JsonProperty("monitorize") boolean monitorize,
#JsonProperty("createP") boolean createP,
#JsonProperty("openP") boolean openP,
#JsonProperty("admin") boolean admin) {
//your code;
}
Also, your getUsers method could look like this:
public static List<User> getUsers(String json) {
final ObjectMapper mapper = new ObjectMapper();
try {
final JavaType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, User.class);
return mapper.readValue(json, collectionType);
} catch (IOException e) {
//You should not hide exceptions. Try to log it at least.
//But probably application should not start when app configuration is missing or wrong.
e.printStackTrace();
return Collections.emptyList();
}
}

Android Simple Adapter

I am getting this error when I am trying to compile. This used to work when I was using sdk 23 but now that I have upgraded to 26 I cant get it to compile.
Error:(41, 13) error: cannot find symbol class SimpleAdapter
This is my code that goes and gets a list of contacts off a website and displays them in a list view.
public class ContactsActivity extends Activity {
private SimpleAdapter adpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
adpt = new SimpleAdapter(new ArrayList<Contact>(), this);
adpt.setStyle(R.layout.contact_list_item);
ListView lView = (ListView) findViewById(R.id.listview_contacts);
The contact class is as follows this is what I cast the returned xml into once it gets returned.
public class Contact implements Serializable {
private String Name;
private String Phone;
private String Cell;
private String Email;
private String Address;
private String Work;
public Contact() {
super();
}
public Contact(String name, String phone, String cell, String email, String address,String work) {
super();
this.Name = name;
this.Phone = phone;
this.Cell = cell;
this.Email = email;
this.Address = address;
this.Work = work;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
this.Phone = phone;
}
public String getCell() {
return Cell;
}
public void setCell(String cell) {
this.Cell = cell;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
this.Email = email;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
this.Address = address;
}
public String getWork() {
return Work;
}
public void setWork(String work) {
this.Work = work;
}
}
Please let me know where I am going wrong.
You need create a SimpleAdapter, can extend from ArrayAdapter, BaseAdapter,...

Create list with unique id in Java and manipulate it

I want to create a programm that creates a list that looks like this
ID: 1
Name: Example
Surname: Example
email: example
//New list
ID: 2
Name: Example
Surname: Example
email: example
and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2
You should use a HashMap.
Create a class (let's class it YourClass) that contains ID, name, surname and email instance variables.
Then create a HashMap where the key is the identifier and the value is YourClass:
Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}
you can create class like this
public class Record{
private int id;
private String name;
private String Surname;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and then use it like this:
Record record1 = new Record();
record1.setId(1);
record1.setName("example");
record1.setSurname("example");
record1.setEmail("example");
Record record2 = new Record();
record2.setId(2);
record2.setName("example");
record2.setSurname("example");
record2.setEmail("example");
Map<Integer,Record> recordMap = new HashMap<Integer, Record>();
recordMap.put(record1.getId(),record1);
recordMap.put(record2.getId(),record2);]
recordMap.get(2).getName();//example
recordMap.get(2).setName("ebi");
recordMap.get(2).getName();//ebi
import java.util.ArrayList;
import java.util.List;
public class Person {
private int id;
private String name;
private String Surname;
private String email;
public Person(int id, String name, String surname, String email) {
super();
this.id = id;
this.name = name;
Surname = surname;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person(1, "example", "example", "example"));
list.add(new Person(2, "example", "example", "example"));
}
}

Sort Array list using POJO class with particular status [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 5 years ago.
I have status like "In consultation","Waiting in Queue". all the data coming from json API and add all that data into array list using Pojo class.then how to sort this array list by Consultation status.
Patient Class:
public class Patient_Get_Set implements Serializable {
private String fullName;
private String age;
private String waitTime;
private String sex;
private String patientID;
private String gender;
private String dateOfBirth;
private String phoneNo;
private String Diagnosis;
private String Email;
private String token_id;
private String priority;
private String consultation_status;
private String case_number;
public String getCase_number() {
return case_number;
}
public void setCase_number(String case_number) {
this.case_number = case_number;
}
public String getConsultation_status() {
return consultation_status;
}
public void setConsultation_status(String consultation_status) {
this.consultation_status = consultation_status;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getToken_id() {
return token_id;
}
public void setToken_id(String token_id) {
this.token_id = token_id;
}
public String getConsultationstatus() {
return consultationstatus;
}
public void setConsultationstatus(String consultationstatus) {
this.consultationstatus = consultationstatus;
}
private String consultationstatus;
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getVisitorType() {
return visitorType;
}
public void setVisitorType(String visitorType) {
this.visitorType = visitorType;
}
private String visitorType;
public String getDiagnosis() {
return Diagnosis;
}
public void setDiagnosis(String diagnosis) {
Diagnosis = diagnosis;
}
private String patientJsonArray;
public void setFullName(String fullName) {
this.fullName = fullName;
}
public void setAge(String age) {
this.age = age;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public String getFullName() {
return fullName;
}
public String getAge() {
return age;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public String getWaitTime() {
return waitTime;
}
public void setPatientID(String patientID) {
this.patientID = patientID;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPhoneNo() {
return phoneNo;
}
public String getPatientID() {
return patientID;
}
public void setPatientJsonArray(String patientJsonArray) {
this.patientJsonArray = patientJsonArray;
}
public String getPatientJsonArray() {
return patientJsonArray;
}
public String getGender() {
return gender;
}
}
Here is code what you can use for your custom need -
Collections.sort(list, new Comparator<Patient_Get_Set>() {
#Override
public int compare(final Patient_Get_Set object1, final Patient_Get_Set object2) {
List<String> statusList = new ArrayList();
statusList.add("consultation");statusList.add("queue"); statusList.add("waiting");
return new Integer(statusList.indexOf(object1.getConsultation_status())).compareTo(new Integer(statusList.indexOf(object2.getConsultation_status())));
}
});
add elements in statusList in same order in which order you want pojo class to be sorted.
You can use Collections to sort your array list objects.
for example your list as below.
ArrayList<Patient> list = new ArrayList<Patient>();
Then you can sort list using below code.
Collections.sort(list, new Comparator<Patient>() {
#Override
public int compare(final Patient object1, final Patient object2) {
return object1.getConsultation_status().compareTo(object2.getConsultation_status());
}
});
OR
If you are using Java version 1.8 then you can sort list using below code.
list.stream()
.sorted((object1, object2) -> object1.getConsultation_status().compareTo(object2.getConsultation_status()));
import static java.util.Comparator.comparing;
Collections.sort(list, comparing(MyObject::getStartDate));
compare data with comparing in java8 follow http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

Subclass instance to Superclass

How do I create subclass objects, based on an superclass objects?
eg:
class Super {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Sub extends Super {
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Super sup = new Super();
sup.setId(1);
sup.setName("Super");
Sub sub = new Sub();
System.out.println(sub.getName());
}
}
How can I create a 'Sub' object with the properties of a 'Super' created earlier?
Or should I pass the properties manually, like:
sub.setName(sup.getName());
sub.setId(sup.getId());
you could add a copy constructor to Super Class
public class Super {
private int id;
private String name;
public Super(String id, String name) {
this.id = id;
this.name = name;
}
public Super(Super other) {
this.id = other.id;
this.name = other.name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and then use this constructor in Sub class
class Sub extends Super {
public Sub(Super other) {
super(other);
}
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
and you can call
Sub sub = new Sub(sup);
I would go with creating a static method in Sub:
Sub.fromSuper(Super s, String last)
I would use apache commons
BeanUtils.copyProperties(toBean, fromBean);
I wouldn't add a method to the class itself unless its really needed on every object. BeanUtils seem appropriate as it appears like something needed only in a specific situation.
In case that you really need the behaviour on every object, than implementing a copy constructor is a way to go

Categories

Resources