When I place the getters and setters in a method, then call that method in the main method, I get a value of null despite having set the value to something else! Additionally, I'm not receiving any errors from the compiler, so I'm sure it's a logical error somewhere but I cannot figure it out.
This is from the class containing the methods in question:
public class URTest {
UserRegistration _user = new UserRegistration();
public static void main(String[] args) {
String fieldName;
UserRegistration _user = new UserRegistration();
URTest _run = new URTest();
Scanner input = new Scanner(System.in);
fieldName = input.nextLine();
_run.test(fieldName);
System.out.println(_user.getUsername());
}
public void test(String fieldName) {
UserRegistration _user = new UserRegistration();
Scanner input = new Scanner(System.in);
String result;
System.out.print("Enter " + fieldName + ": ");
result = input.nextLine();
while(true) {
if(result.equals("")) {
System.out.print("Please enter a value for the " + fieldName + ": ");
result = input.nextLine();
} else {
break;
}
if(fieldName.equals("username")) {
_user.setUsername(result);
}
}
}
}
Here is the class containing my getters and setters:
import java.io.Serializable;
public class UserRegistration implements Serializable {
private String username;
private int userId;
private String firstName;
private String lastName;
private String password;
private String email;
public UserRegistration() {
this.username = username;
this.userId = userId;
}
public UserRegistration(String uName, int id, String uPassword) {
this.username = uName;
this.userId = id;
this.password = uPassword;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
String name = getFirstName() + getLastName();
String output = name + "has the user id " + getUserId() +
"username " + getUsername() + " and email " + getEmail();
return output;
}
}
You are calling
UserRegistration _user = new UserRegistration();
And in your class
public UserRegistration() {
this.username = username;
this.userId = userId;
}
When the above constructor gets called, there is no value to be set to the member variable and therefore you are getting null
In your calling method,
UserRegistration _user = new UserRegistration("name","id1");
OR
set default values in your constructor:
public UserRegistration() {
this.username = "name";
this.userId = "id1";
}
Related
Hello I'm trying to display the Student data with his corresponding subject based on the subject_id foreign key and displaying the result on GET REQUEST. I don't know how I need to rewrite the SQL command to remove the error. Here is the Error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN subject ON student.subject_id=subject.id WHERE user_id=3' at line 1Retrieve not successful
Here is my DB schema:
Here is my code:
public ArrayList<Object> getStudentSubject(int id) throws Exception {
Connection connection = null;
ArrayList<Student> data = new ArrayList<>();
ArrayList<Subject> data2=new ArrayList<>();
ArrayList<Object> data3 = new ArrayList<>();
try {
connection = new MysqlDbConnectionService().getConnection();
String select ="SELECT student.user_id, student.username, student.password, student.fullname,student.email, subject.id,subject.name" +
"FROM student INNER JOIN subject ON student.subject_id=subject.id WHERE user_id=?";
PreparedStatement ps = connection.prepareStatement(select);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Student model = new Student();
Subject model2 = new Subject();
while (rs.next()) {
model.setId(rs.getString("user_id"));
model.setUsername(rs.getString("username"));
model.setPassword(rs.getString("password"));
model.setFullName(rs.getString("fullname"));
model.setEmail(rs.getString("email"));
model2.setId(rs.getInt("id"));
model2.setName(rs.getString("username"));
data.add(model);
data2.add(model2);
data3.add(data);
data3.add(data2);
}
} catch (Exception e) {
System.out.println(e + "Retrieve not successful");
}
return data3;
}
Jersey Code:
#Path("subject/{id}")
#GET
public Response getStudentwithSubject(#PathParam("id") int id) throws Exception {
return Response.ok(new Gson().toJson(studentService.getStudentSubject(id))).build();
}
Student Model:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Student {
#SerializedName("id")
private String id;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("fullname")
private String fullName;
#SerializedName("email")
private String email;
public Student()
{
}
public Student(String id, String username, String password, String fullName, String email)
{
super();
this.id=id;
this.username = username;
this.password = password;
this.fullName = fullName;
this.email = email;
}
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;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Subject Model:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Subject {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
public Subject() {
this.id = id;
this.name=name;
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
It is a simply wrong SQL formed because of string concatenation, if you observe there is no space between subject.name and FROM student. Add space either after subject.name or before FROM like below.
String select ="SELECT student.user_id, student.username, student.password, student.fullname,student.email, subject.id,subject.name " +
" FROM student INNER JOIN subject ON student.subject_id=subject.id WHERE user_id=?";
Let me know if this helps.
This is the screenshot of my firestore structure
I want to get the data from my model stored in my firestore documents to my local variable
final EmployeeModel model = new EmployeeModel();
firebaseFirestore.collection("USERS").document(firebaseUser.getUid()).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
String username = documentSnapshot.getString(model.getUsername());
String email = documentSnapshot.getString(model.getEmail());
String location = documentSnapshot.getString(model.getLocation());
String phonenumber = documentSnapshot.getString(model.getPhonenumber());
String genderS = documentSnapshot.getString(model.getGender());
// Map<String, Object> userInfo = documentSnapshot.getData();
fragmentname.setText(username);
welcomeUser.setText(email);
employeeID.setText("1610225");
city.setText(location);
number.setText(phonenumber);
gender.setText(genderS);
} else {
Toast.makeText(getActivity(), "Document does not exist", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error ", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
please correct my syntax I'm really new at this
This is EmployeeModel.class
And please show how to pass the .getUsername to a variable String username
public class EmployeeModel {
public static final String MFIELD_USERNAME = "username";
public static final String MFIELD_EMAIL = "email";
public static final String MFIELD_PASSWORD = "password";
public static final String MFIELD_LOCATION = "location";
public static final String MFIELD_PHONENUMBER = "phonenumber";
public static final String MFIELD_GENDER = "gender";
public static final String MFIELD_TYPE = "type";
private String username;
private String email;
private String password;
private String location;
private String phonenumber;
private String gender;
private String type;
private #ServerTimestamp Date timestamp;
public EmployeeModel() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public EmployeeModel(String username, String email, String password, String location, String phonenumber, String gender, String type, Date timestamp) {
this.username = username;
this.email = email;
this.password = password;
this.location = location;
this.phonenumber = phonenumber;
this.gender = gender;
this.type = type;
this.timestamp = timestamp;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}}
This is my EmployeeModel.class
and my Firestore screenshot, please help! Thank you
what you are missing is to get the model from the document
if(documentSnapshot.exists()){
EmployeeModel model = documentSnapshot.toObject(EmployeeModel.class);
//
just add the line after if statement to your existing code the rest seems fine.
Currently trying to set User u object by using JSON data from response.body() (retrofit). However, I am not able to do that. loginOperation(email,psswd) returns a boolean value which states whether a successful logged-in or not. When I try to execute this outer method, it returns check before the overridden method onResponse().
Is there any advice? Thanks in advance!
AuthenticationCheck class ----------
public class AuthenticationCheck {
RetrofitConnection rc = new RetrofitConnection();
Retrofit retrofit = rc.getRetrofit();
private static boolean check = false;
private static User u = new User();
synchronized public boolean loginOperation(String email, String password){
LoginService loginService = retrofit.create(LoginService.class);
Call<ResponseBody> call = loginService.loginWithCredentials(new
LoginCredentials(email, password));
call.enqueue(new Callback<ResponseBody>() {
#Override
synchronized public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
check=true;
final JSONObject obj;
try {
obj = new JSONObject(response.body().string());
final JSONObject userObj = obj.getJSONObject("user");
u.setSurname(userObj.getString("surname"));
u.setPhone(userObj.getString("phonenumber"));
u.setUser_id(userObj.getInt("user_id"));
u.setName(userObj.getString("name"));
u.setEmail(userObj.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
synchronized public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("FAIL","onFailure ");
}
});
return check;
}
public User getAuthenticatedUser(){
return u;
}
LoginCredentials
public class LoginCredentials {
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
public LoginCredentials(String email, String password) {
this.email = email;
this.password = password;
}
}
LoginInterface
public interface LoginService {
#POST("mlogin")
Call<ResponseBody> loginWithCredentials(#Body LoginCredentials data);
}
User Class
public class User {
#SerializedName("user_id")
#Expose
private int user_id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("phonenumber")
#Expose
private String phone;
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
public User(int user_id, String name, String surname, String phone,String email,String pass){
this.user_id = user_id;
this.name = name;
this.surname = surname;
this.phone = phone;
this.email = email;
this.password = pass;
}
public User(){
this.user_id = 0;
this.name = null;
this.surname = null;
this.phone = null;
this.email = null;
this.password = null;
}
public String getEmail() { return email; }
public String getName() { return name; }
public String getPasswd() { return password; }
public String getPhone() { return phone; }
public String getSurname() { return surname; }
public int getUser_id() { return user_id; }
public void setEmail(String email) {
this.email = email;
}
public void setName(String name) {
this.name = name;
}
public void setPasswd(String password) {
this.password = password;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setUser_id(int user_id) { this.user_id = user_id; }
#Override
public String toString() {
return "Post{" +
"user_id='" + user_id + '\'' +
", name='" + name + '\'' +
", surname=" + surname +
", phone=" + phone +
", email='" + email + '\'' +
", pass=" + password +
'}';
}
}
call.enqueue is an asynchronous operation, so rest of the code in loginOperation() after this call will continue to execute. If you want to block till response is received you need use synchronous call.execute
Use Rest Template instead of your call, it will be a blocked http call, see examples here
I have two types of user, LibraUsers and GenesysUser. Each have their own properties, but some are similar.
I need to find the differences between two lists of these types of users. Made a small program to illustrate my problem - My issue is that I have duplicate entries in my difference list, the compare method on the list does not seem to do its job. I've read that I should override the equals method, and also the hashcode (in this case of the LibraUser). I tried that using an apache function, but it did not work.
The question therefore is, what are the alternatives for solving this problem?
import java.util.ArrayList;
import java.util.List;
// one class needs to have a main() method
public class HelloWorld {
public static List<LibraUser> libraUsers = new ArrayList<LibraUser>();
public static List<GenesysUser> genesysUsers = new ArrayList<GenesysUser>();
public static List<LibraUser> difference = new ArrayList<LibraUser>();
public static void initialiseGenesysUsers() {
// GenesysUser(String alias, String firstname, String lastname, String email)
genesysUsers.add(new GenesysUser("Donna", "Donna", "Paulsen", "donna#gmail.com", true));
genesysUsers.add(new GenesysUser("TheHarv", "Harvey", "Specter", "harvey#gmail.com", true));
genesysUsers.add(new GenesysUser("Rache", "Rachel", "Zane", "rachel#gmail.com", true));
genesysUsers.add(new GenesysUser("Mike", "Mike", "Ross", "mike#gmail.com", true));
}
public static void initialiseLibraUsers() {
// LibraUser(String name, String email, String telephone) {
libraUsers.add(new LibraUser("Louis", "louis#gmail.com", "0447521082"));
libraUsers.add(new LibraUser("Jessica", "jessica#gmail.com", "0447521044"));
libraUsers.add(new LibraUser("Mike", "mike#gmail.com", ""));
}
public static void getDifference() {
for (LibraUser librauser : libraUsers) {
for (GenesysUser genesysuser : genesysUsers) {
String genusername = genesysuser.getFirstname();
LibraUser dummy = new LibraUser(genusername, genesysuser.getEmail(), "");
if (!difference.contains(dummy)) {
// do the actual comparison using the relevant keys and insert into a new list
if (!librauser.getUsername().equals(genusername)) {
difference.add(dummy);
}
}
} // inner for loop
}// outer for loop
}
public static void printDifference() {
for (LibraUser usr : difference) {
System.out.println(usr.getUsername());
}
}
// arguments are passed using the text field below this editor
public static void main(String[] args) {
initialiseGenesysUsers();
initialiseLibraUsers();
getDifference();
printDifference();
}
}
public class GenesysUser {
private String Alias;
private String Firstname;
private String Lastname;
private String Email;
private boolean Active;
public GenesysUser(String alias, String firstname, String lastname, String email, boolean active) {
Alias = alias;
Firstname = firstname;
Lastname = lastname;
Email = email;
Active = active;
}
public String getAlias() {
return Alias;
}
public String getFirstname() {
return Firstname;
}
public String getLastname() {
return Lastname;
}
public String getEmail() {
return Email;
}
public void setAlias(String alias) {
Alias = alias;
}
public void setFirstname(String firstname) {
Firstname = firstname;
}
public void setLastname(String lastname) {
Lastname = lastname;
}
public void setEmail(String email) {
Email = email;
}
public void setActive(boolean active) {
Active = active;
}
public boolean getActive() {
return Active;
}
}
public class LibraUser {
private String username;
private String email;
private String telephone;
public LibraUser(String username, String email, String telephone) {
this.username = username;
this.email = email;
this.telephone = telephone;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public String getTelephone() {
return this.telephone;
}
public void setName(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof LibraUser)) {
return false;
}
LibraUser user = (LibraUser) o;
return new EqualsBuilder()
.append(username, user.getUsername())
.append(email, user.getEmail())
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(username)
.append(email)
.toHashCode();
}
}
You need to use .equals instead of == to test the equality
if(librauser.getUsername() != genusername)
should be replaced with
if(!librauser.getUsername().equqls(genusername))
I have one REST Call as
List<User> userList = (List<User>) iplUtil.getResult(user, mongoGetURL);
System.out.println("userList === "+userList);
output as
userList = [{_id={$oid=571903dae4b085317593a0d3}, nickName=aa, email=aa, password=aa, userId=1}]
No complile time error..
but this line failing in runtime
User u =userList.get(0);
getting exception at this line as
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.ipl.model.User
and model as
package com.ipl.model;
import java.io.Serializable;
import java.util.Map;
#SuppressWarnings("serial")
public class User implements Serializable {
private Map<String, String> _id;
private String nickName;
private String email;
private String password;
private int userId;
public User(String nickName,String password) {
this.nickName=nickName;
this.password=password;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User() {
// TODO Auto-generated constructor stub
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Map<String, String> get_id() {
return _id;
}
public void set_id(Map<String, String> _id) {
this._id = _id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User [_id=" + _id + ", nickName=" + nickName + ", email=" + email + ", password=" + password
+ ", userId=" + userId + "]";
}
}
Im not getting any complie time error..why its failing in runtime