Java Class's property not getting set when passing through parameter - java

I have two classes
here's code
public class LoginServiceImplementation implements LoginService {
public boolean validateLogin(Login login)
{
LoginDao loginDao=DaoFactory.getLoginDao();
boolean b=loginDao.validateLogin(login);
System.out.println("id=="+login.getLoginId()+" uname=="+login.getuName()+" pass== "+login.getPassword());// values reset to null
return b;
}
}
public class LoginDaoImplementation implements LoginDao {
#Override
public Login validateLogin(Login login) {
Session session= Hibernate.getHibernateSession();
Query query= session.createQuery("from Login where uName= 'user' and password= 123");
//query.setParameter("uname", login.getuName());
//query.setParameter("pwd", login.getPassword());
//System.out.print(login.getuName());
//System.out.print(login.getPassword());
try
{
List<Login> logins=query.list();
System.out.print(logins.size());
if(logins.size()>0)
{
Login l=new Login();
l=logins.get(0);
login=l;
System.out.println("id=="+login.getLoginId()+" uname=="+login.getuName()+" pass== "+login.getPassword());/// ALL values getting printed
return login;
}
session.close();
return null;
}
catch(HibernateException x)
{
x.printStackTrace();
session.close();
return null;
}
}
}
when calling validatemethod of DaoImplementation class from serviceImplementation class, DaoImplementation class sets the values in the login object which is passed as parameter, but in serviceimplementation class i'm getting same old object with all values set to null.
Please reply with reason and solution.
thank you

login=l;
That does not work. You are just assigning a new object to the local variable login. This has no effect on the object that was previously stored in that variable (and that is visible to the outside world). Java does not support pass-by-reference, so you cannot re-assign variables outside of your scope.
You need to either copy all the data into that object (using setters), or (my preference) return a Login object from the method that the caller can use. (It is not clear if you are already doing that, part of the sample seems to return boolean, part seems to return a Login object).

Related

spring entity : return id of created record

I have this AccountantRepository class
#Repository("accountantRepository")
#Transactional
public interface AccountantRepository extends JpaRepository<Accountant, Long>
In AccountantServiceImpl
#Service("accountantService")
public class AccountantServiceImpl implements AccountantService{
#Autowired
private AccountantRepository accountantRepository;
#Override
public Accountant saveAccountant(Accountant newAccountant, String role) {
return accountantRepository.save(newAccountant);
}
}
when i do this accountantRepository.save(newAccountant);
how do I obtain the id of the newly created record?
Use the returned instance by JpaRepository.save(). It will contain the id valued.
The CrudRepository.save() method (where save() is declared) specifies :
Use the returned instance for further operations as the save operation
might have changed the entity instance completely.
You can directly take the id from the entity itself. newAccountant.getId()( or what ever be the field) will return the data after save method has been called .
Shown below-
#Override
public int saveAccountant(Accountant newAccountant, String role) {
accountantRepository.save(newAccountant);
return newAccountant.getId();
}
This reference will be available in hibernate session and hibernate will set the id to the persisited object.

Accessing objects that have already been created of the same class Android

So I am creating a chat app for android and I'm using Java and I need some help wrapping my head around some things. Whenever the user first registers, I am creating a new object of a class named User. When they enter the next layout, I need to access that objects data.
public class User {
public String username;
public User() {}
public User(String username) {
this.username = username;
}
public String getUsername(){
return username;
}
}
This is my User class. When they send a message, I need to be able to grab their username from this User object from an entirely different method without passing the object through a parameter. I can't seem to wrap my head around how to access their information and none of my methods seem to work. Any help is appreciated
If you do
User myUser = new User();
the variable myUser contains a reference to the newly created object. You must keep this reference around in order to later access the object. How exactly you do this depends on the logic of your program. Sometimes you would keep it in a field of another object or pass it around as parameter. For example
un = myUser.getUsername();
or
void myMethod(User theUser) {
...
String un = theUser.getUsername();
}
...
// call the method passing the user reference
myMethod(myUser);
in the main class make the data object... static
public static Model obj;
obj= new Model();
then from other class access it with your class name
example
main.obj;
I solved this issue by just using SharedPreferences. I stored the username associated with the key of each user. This way, I can always search the username for each user.

Extend Application Class for ParseUser

I would like to extend my Application class in order to globally access the logged in ParseUser without repeatedly calling .getCurrentUser() and accessing it's fields in every activity.
Currently my Application class is already extended to initialize Parse and ParseFacebookUtils. As per this thread, it says to make an instance of the ParseUser in the Application class however I'm not sure how to do so.
Note: I do not want to use intents as ParseUser is not serializable.
Thank you for your help. I can't see the relevance for code inclusion but please ask if you require any.
Method ParseUser.getCurrentUser() doesn't perform any network operations so it can't block UI. Also it is static, so by some means it already gives you global access.
I think it is not the best idea to duplicate it's value somewhere and it could cause bugs
What you can do is have 2 attributes in the existing application class.
isLoggedIn(boolean) - initialise it as false
user(ParseUser)
And place getters and setters.
When the user logs into the system you can set the isLoggedIn to true and set the user as well in the loginActivity. Suppose extended Application class is MyApplication.
((MyApplication)getApplication).setIsLoggedIn(true)
((MyApplication)getApplication).setUser(parseUser) .
After that you can in other activities you can simply check the isLoggedIn boolean value and do the necessary actions.
You can retrieve the set user by
ParseUser currentUser = ((MyApplication)getApplication).getUser()
Hope this helps.
I have implemented a Singleton to solve my problem. I have extended the Application class to initialize a Singleton so that an instance of this Singleton exists whether an activity is destroyed or othewise. I can access this instance via any activity and as such access all the fields of the current ParseUser.
// Application Class
public class Application extends android.app.Application{
#Override
public void onCreate() {
Parse.initialize(this, "redacted", "redacted");
ParseFacebookUtils.initialize(this);
initSingleton();
}
protected void initSingleton() {
ParseUserSingleton.initInstance();
}
}
// Singleton Class
public class ParseUserSingleton {
private static ParseUserSingleton instance;
public ParseUser user;
public HashMap<String, String> userFields = new HashMap<>();
public static void initInstance() {
if (instance == null) {
// Create the instance
instance = new ParseUserSingleton();
}
}
public static ParseUserSingleton getInstance() {
// Return the instance
return instance;
}
private ParseUserSingleton() {
// Constructor hidden because this is a singleton
}
public void customSingletonMethod() {
try {
user = ParseUser.getCurrentUser().fetch();
} catch (ParseException e) {
e.printStackTrace();
}
userFields.put("name", user.get("availability").toString());
// repeat for other fields
}
}
// Activity access
ParseUserSingleton.getInstance().customSingletonMethod();
userHashMap = ParseUserSingleton.getInstance().userFields;

Struts 2 textfield displays the value even without the value attribute

I have a Struts 2 textfield tag where I just need to get a user enter value and send to the action.
<s:textfield name="user.firstAnswer" size="110" cssClass="FormObjectCompulsary" autocomplete="off" />
Even when this page loads user object contains value for first answer, I don't want to display it in the text field instead I want the text field to be blank.
But with out specify the value attribute still the value in user object shows in this field.
If you are adding a new object user, then you should create this object with new operator before you show it in the JSP. It will contain null references that are not displayed. If the value attribute is not specified, then name is used to show the value.
Make your user object null after inside the execute(). So again it will not show value inside text box.
eg. user = null;
I am showing you piece of code, may be it will help you.
See the execute().
package online.solution;
import com.opensymphony.xwork2.Action;
public class MyAction implements Action {
UserBean user = new UserBean();
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
#SuppressWarnings("finally")
#Override
public String execute() throws Exception {
String result = "";
try {
user.setGuest("Bye bye");
System.out.println(user.getUsername() + " " + user.getPassword());
if (user.getUsername().equals(user.getPassword())) {
result = SUCCESS;
}
else {
result = ERROR;
}
user = null; //Make it null when all task completed.
}
catch (Exception exception) {
System.out.println("Exception -> " + exception);
}
finally {
return result;
}
}
#Override
protected void finalize() throws Throwable {
super.finalize();
}
}
By looking at name="user.firstAnswer" I am thinking that you are implementing ModelDriven<> to your action class. What might be happening is that when you return success in your action class and come to the jsp page, and if in action your user model had some values on it.. model driven will set those fields for your on your JSP page.
I have used this approach for update form functionality while learning struts2. Just make sure that user object contains nothing before you return...

How to set the values in session?

If I'm getting empty session I need to setup some values to play the action class. So, here is the method
public SearchFilters getFilters() {
return (SearchFilters) getSession().get("Filters");
}
I would like to check the session, if it's null, then I need to set the some values over here.
public SearchFilters getFilters() {
if(getSession().get("Filters").equals(null)){
---- //How to set the values and return ?
}
return (SearchFilters) getSession().get("Filters");
}
Use the code:
public SearchFilters getFilters() {
if(getSession().get("Filters") == null){
//How to set the values
getSession().put("Filters", new Filters());
}
// and return.
return (SearchFilters) getSession().get("Filters");
}
assumed you have injected the session into the action via implementing SessionAware.
The value is a free hand object which contains no value, but you could create a constructor to it and pass the value directly.
getSession() will return a new session if an existing session is not found. So you don't need to worry about this one ever returning null. Take note though, there's no get() method under HttpSession, it's getAttribute().
So you can do this:
public SearchFilters getFilters() {
if(getSession().getAttribute("Filters") == null) {
getSession().setAttribute("Filters", new SearchFilters());
}
return (SearchFilters) getSession().getAttribute("Filters");
}

Categories