I am trying to use a constructor in class that extends the BaseModel in DBFlow but i get this in the console.
/home/christoandrew/Documents/Trumeter/app/build/generated/source/apt/debug/com/iconasystems/android/trumeter/models/Session_Table.java:144: error: constructor Session in class Session cannot be applied to given types;
return new Session(); ^
required: String,String
found: no arguments
reason: actual and formal argument lists differ in length
and this is my Session.java
#Table(database = TrumeterDatabase.class)
public class Session extends BaseModel{
#PrimaryKey
#Column
#SerializedName("username")
String username;
#Column
#SerializedName("password")
String password;
public Session(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Now when i check the table class generated it has no arguments in the instantiation. I have been checking around and all tutorials don't seem to be having constructors in their classes. Is the mistake mine or thats how its supposed to be done.
You must implement a default constructor for your model classes.
public Session() {
}
Because DBflow processor generated code (YourModel_Table) use this default constructor.
Related
This question already has answers here:
Java default constructor
(13 answers)
Closed 2 years ago.
I know that a similar question has been answered before in other questions but all the ones i found does not apply to my situation so i decided that i ask it.
This line gives an error:
User users = new User();
Error message:
constructor User in class User cannot be applied to given types;
required: String,String,String,String
found: no arguments
reason: actual and formal argument lists differ in length
Below is my java class file.
public class User {
private String username;
private String pwd;
private String email;
private String role;
public User(String username, String pwd, String email, String role) {
this.username = username;
this.pwd = pwd;
this.email = email;
this.role = role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
Your User constructor takes 4 arguments: username, pwd, email, and role, and you're trying to construct it with new User(), which provides none of the arguments. You should actually provide them:
User user = new User("username here", "pwd here", "email here", "role here");
Or, create a constructor with no arguments of the form:
public User() {
this.username = /* some default value */;
this.pwd = /* some default value */;
this.email = /* some default value */;
this.role = /* some default value */;
}
Or, to reuse your constructor:
public User() {
this(/* username default */, /* pwd default */, /* email default */, /* role default */);
}
You could use null as the default value, but that will probably just lead to NullPointerExceptions down the line.
Just create another constructor:
public User(){}
When you make a class this constructor is made for you by default. When you create a constructor yourself, this default constructor isn't made for you anymore and you have to add it in yourself.
I am doing a program that involve creating an account, I need to create so that it will scan specific data to carry out an assigned command. is the getter and setter function suitable for it?
public class Account {
//data
private int userId;
private String password;
private char type;
public Account(int userId, String password, char type) {
this.userId = userId;
this.password = password;
this.type = type;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public char getType() {
return type;
}
public void setType(char type) {
this.type = type;
}
//methods
public boolean verifyLogin(int usrid , String pass)
{
if((usrid == userId) & (pass == password)){
return true;
}
else{
return false;
}
}
Your getters and setters look fine for accessing the data of this class.
Something you need to be very careful with is how you check if the password is correct.
In your implementation you use pass == password for comparing two strings. This is NOT correct and you should rather use pass.equals(password).
It looks fine, but you need to rethink if Setters for some values are necessary. In example it is not very common use case that UserID will change somehow. If you want to keep it persistant, setter is not necessary. Set it once in constructor.
Additionally you can take a look on the Lombok Project and #Getter & #Setter annotation. It will minimalize your code to 3 lines.
My User POJO looks like the following:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "User")
public class User {
#Id
private String id;
private String username;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I am able to get all document based on the query:
List<User> testBedsFromDB = mongoOperations.findAll(User.class);
I want to skip some of the fields like password. I want to get all the document with values only in id and username, password may be null or empty. How I can achieve this?
I was able to get all field excluding one field. Code spinet bellow:
Query searchQuery = new Query();
searchQuery.fields().exclude("password");
List<User> userList = mongoOperations.find(searchQuery, User.class);
With above code password field value will be null.
You can use multiple exclude like:
searchQuery.fields().exclude("username").exclude("password");
I defined an object "User" in server and client end. The "User" in server end only has a constructor and getter and setter, but the one in client end has some other method.
My project structure is following:
Project structure
The code is following:
The server:
class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String password;
private String role;
User(String name, String password, String role) {
this.setName(name);
this.setPassword(password);
this.setRole(role);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String toString() {
return this.name + this.password + this.role;
}
}
The client:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String password;
private String role;
User(String name, String password, String role) {
this.name = name;
this.password = password;
this.role = role;
}
/*=====================getter and setter========================*/
public void set(String name, String password, String role) {
this.name = name;
this.password = password;
this.role = role;
}
public String get() {
return this.name + " " + this.password + " " + this.role;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return this.password;
}
public void setRole(String role) {
this.role = role;
}
public String getRole() {
return this.role;
}
/*==================Method===================*/
public void showMenu(String title) {
}
}
And I want to send a User object from client to server. But an ClassNotFoundException is thrown.
java.lang.ClassNotFoundException: pers.yangxujie.RecordMangerServer.main.User
Why? Do I have to user the same "User" object?(But I have to define them in both ends, because it is c/s model)
Based on what you have shown us, I think that the problem is that there is no class called pers.yangxujie.RecordMangerServer.main.User on the classpath on the server side.
If the problem was due to differences in the versions of the class on the client and server side, then I would expect to see different exceptions. It is (IMO) generally a bad idea to use different versions of a class when serializing and deserializing, because the differences can cause all sorts of problems (if you are not careful). However, sometimes this is unavoidable.
The class should be the same on both ends. Not different classes with the same name. Here 'same' means same name, same package, same serialVersionUID.
If you really know what you're doing, the classes can have minor disagreements about their fields, subject to the provisions of the Versioning chapter of the Object Serialization Specification: this can be handy as a solution to a deployment problem where you can't update server and client at the same time.
However it doesn't make sense to set out from the beginning to have two different classes called User in the same system. In this case it strongly appears that they are in different packages, which makes them different classes. This will not work for Serialization purposes.
Is the server class in its own separate file? Make sure neither one of them is an inner class
I have this Enum:
public enum Role {
Manager("manager"),
Customer("customer");
private String role;
Role(String role){
this.role = role;
}
}
And I have this POJO which I get from an Http request (using Jerey and Jackson):
public class UserCredentials {
private String username;
private String password;
private Role role;
public UserCredentials() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
The last setter creates an error as Jackson don't really knows how to convert
{
"username": "shikloshi",
"password": "password",
"role": "admin"
}
To an object (specifially the "role" Enum).
I was trying to change the setter to:
public void setRole(String role) {
this.role = new Role(role);
}
which cannot be done.
Is there a way to invoke enum constructor (or any other way of creation - Jackson for instance) in a more Object Oriented manner (the alternative is to use a switch-case inside the setter)?
A common solution in this situation is to add a public static Role fromString(String) method in the Role enum. Internally it might use a switch, or a Map<String, Role> cache.
Example using a simple switch:
public static Role fromString(String string) {
switch (string) {
case "manager": return Manager;
case "customer": return Customer;
}
throw new IllegalArgumentException("Invalid role: " + string);
}
Example using a cache:
private static Map<String, Role> cache = new HashMap<>();
static {
for (Role value : values()) {
cache.put(value.role, value);
}
}
public static Role fromString(String string) {
Role role = cache.get(string);
if (role == null) {
throw new IllegalArgumentException("Invalid role: " + string);
}
return role;
}
Actually, as #realskeptic pointed out in a comment,
if you renamed your enum values to all-caps, MANAGER, CUSTOMER,
as recommended by convention,
then you could benefit from the .valueOf method which uses a cache behind the scenes:
public static Role fromString(String string) {
return valueOf(string.toUpperCase());
}
In this case you don't need to worry about building the cache yourself.
If you supply an invalid string value,
this will raise a IllegalArgumentException just like the examples above (with slightly different text).