简体   繁体   中英

How to access a Variable value from a class in java

I am trying to Show UserName in my MainDashboard. i am retriving it in methods class and storing the userName in a Variable and accessing that Variable from Dashboard but all i am receiving is nothing my Dashboard Code is

         String Query="SELECT `FirstName` FROM `localuserregisteratin` WHERE 
           `Email`='"+a.Email+"' AND  `Password`='"+a.Password+"' ";
            Statement stmtt=con.createStatement();
            ResultSet rst=stmtt.executeQuery(Query);

            while (rst.next()) {           
               PartnerFirstName=rst.getString("Firstname");
               frmLocalUser frm=new frmLocalUser();
               frm.UserFirstName=PartnerFirstName;
            }

and my dashboard form code is

              txtUserName.setText(this.m.PartnerFirstName);

any help would be appreciated.

Use getter/ setter to access variables. Like getPartnerFirstName(). And also in this case you can return your value.

Backticks on column names should be avoided. They are not ANSI-SQL compliant, means it won't work when the same query gonna run with sql server. I suspect there is a typo in localuserregisteratin, that's why you are not getting any data out of the table. To access data member from a class, getter is a good choice.

txtUserName.setText(this.m.UserFirstName); or txtUserName.setText(this.UserFirstName);

will help if m object is mapped to frm If you are assigning to UserFirstName of frm object you should retrieve that parameter( UserFirstName ) only.
Best Practice would be using Getter and Setters while assigning and accessing the states of an object in Java.

Most of the above answers should guide you through, however i just added the code snippet for you to be familiar with.

This call be your class with prepared statements to get data from DB

/* Class #1 */
public class VariableWriteClass {
    public VariableClass methodWriteClass(){
        VariableClass vClass = new VariableClass();
        vClass.setUserName("bob");
        return vClass;
    }
}

Getter and Setter

/* POJO class*/
public class VariableClass {
    String userName;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

This can be your MainDashboard class

/* Class #2 */
public class VariableAccessClass {

    public static void main(String[] args) {
        callMethod();
    }
    private static void callMethod() {
        VariableWriteClass vWrite = new VariableWriteClass();
        VariableClass name = vWrite.methodWriteClass();
        System.out.println(" main class "+name.getUserName());      
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM