this is simple login handler, i never have problem like this when put it on same class. then i try to put it on child class and i don't know what happening.
this is the GUI class
final static Functions.F_Koneksi F_K = new Functions.F_Koneksi();
final static Functions.F_Process F_P = new Functions.F_Process();
final static GUIController F_GUI = new GUIController();
protected javax.swing.JPasswordField jPasswordFieldPasswordLoginPane;
protected javax.swing.JTextField jTextFieldUsernameLoginPane;
...
private void jButtonLoginLoginPaneActionPerformed(java.awt.event.ActionEvent evt) {
switch (F_GUI.DoLogin()) {
case 1:
cl.show(MainPane, "BuyMovie");
break;
...
default:
LoginLabel.setText("username or password ... ");
}
}
and this is the GUIController class
int DoLogin(){
try {
System.err.println(jTextFieldUsernameLoginPane.getText());
char[] PassChars = jPasswordFieldPasswordLoginPane.getPassword();
String Pass = new String(PassChars);
return F_P.F_Login(jTextFieldUsernameLoginPane.getText(), Pass);
} catch (SQLException ex) {
LoginLabel.setText("connection error");
}
return 3;
}
and this is the F_Login method on F_Process
public int F_Login(String User, String Pass) throws SQLException {
ResultSet RS = Select("select * from blablabla"); //this query work already
int level = 8;
if (RS.next()) {
level = RS.getInt("Level");
}
return level;
}
the problem is when i set user and password textfield with right user pass its work but when user put it its not. i know something wrong with my OOP logic but i don't understand where. thank you
this is picture to make you understand what i mean
http://i.stack.imgur.com/1DsrF.png
http://i.stack.imgur.com/uXmGZ.png
Maybe its because the GUIController doesn't access the same jPasswordFieldPasswordLoginPane that the other gui access, to do it, you must pass the object to the GUIController class, like pass the reference in the constructor or setter method, and in the GUIController you access the correct jPasswordFieldPasswordLoginPane.
Related
Here is the code of my HomePage.java file in which I have created the object of LoginPageService class to call its methods.
public class HomePage extends javax.swing.JFrame {
CardLayout cl;
private LoginPageService service;
/**
* Creates new form trial
*/
public HomePage() {
initComponents();
cl = (CardLayout) (jPanel6.getLayout());
service = new LoginPageService();
JTable jTable = service.getScheduledLectureList(jTable1, ScheduleLecture.class);
jTable.setRowHeight(45);
jTable.getColumnModel().getColumn(0).setPreferredWidth(1);
JTableHeader tableHeader = jTable.getTableHeader();
tableHeader.setBackground(new java.awt.Color(119, 124, 168));
tableHeader.setForeground(Color.black);
Font headerFont = new Font("Verdana", Font.PLAIN, 19);
tableHeader.setFont(headerFont);
}
private void jLabel26MouseClicked(java.awt.event.MouseEvent evt) {
service = new LoginPageService();
String id = getId1().getText();
char ch[] = getPassword1().getPassword();
String password = new String(ch);
String value = (String) jComboBox2.getSelectedItem();
Boolean result = service.checkCredential(id, password, value);
if (result == true) {
JOptionPane.showMessageDialog(this, "Welcome " + id);
if ("Student".equals(value)) {
new SignInAsStudent().setVisible(true);
dispose();
}
if ("Instructor".equals(value)) {
new main.java.com.lecture_backup.view.SignInAsInstructor().setVisible(true);
dispose();
}
} else {
JOptionPane.showMessageDialog(this, "Invalid Id or Password");
getPassword1().setText("");
getId1().setText("");
}
}
}
this is the code of LoginPageService:
public class LoginPageService {
private HomePage hm;
public LoginPageService(){
hm = new HomePage();
}
public JTable getScheduledLectureList(JTable jTable1, Class sdl) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
Date date = new Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
hm.getPassword1().setText("");
hm.getjLabel13().setText("" + df.format(date));
Criteria crit1 = session.createCriteria(sdl);
Criteria crit = session.createCriteria(ScheduleLecture.class);
crit.add(Restrictions.ge("date", df.format(date)));
List<ScheduleLecture> data = crit.list();
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
for (ScheduleLecture sl : data) {
Object obj[] = {sl.getSerialNo(), sl.getSubject(), sl.getTopic(), sl.getName(), sl.getDate(), sl.getTime()};
dtm.addRow(obj);
}
return jTable1;
}
Can you please tell me is this the right way to declare the reference object first private variable, then instantiate it in the respective methods to call the methods of LoginPageService class?
I have added the code of both the files. can someone tell me now where s the problem. Why after running the code it is not directing me to HomePage.
Instance variables (declared inside the class and outside methods) are kept in each object with their own reference. Unless you need reference for the instance variable across multiple methods of the same class, you can declare it locally (inside method when needed) alone.
Since you are using it only once and have no further reference to it (as far as it is show in the snippet) you may move it locally as follows:
public class HomePage extends javax.swing.JFrame {
...
// private LoginPageService service; // remove this
...
//service = new LoginPageService(); // remove this
...
JTable jTable = new LoginPageService().getScheduledLectureList(jTable1, ScheduleLecture.class);
...
//service = new LoginPageService(); // remove this
...
Boolean result = new LoginPageService().checkCredential(id, password, value);
}
Else you can instantiate it only once via the constructor (not reccommended if you may not use it but if you will use it in every case, then proceed with this)
private LoginPageService service;
HomePage() {
service = new LoginPageService();
}
I have an activity on my app where a user can update their registered information stored in a remote database. When the update button is pressed the information in the database is being updated but the static variable is not changing. Here is my code thanks in advance for any help!
btUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String first_name = First_name.getText().toString();
final String last_name = Last_name.getText().toString();
final String email = Email.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
LoginActivity.first_name = jsonResponse.getString("first_name");
LoginActivity.last_name = jsonResponse.getString("last_name");
LoginActivity.email_address = jsonResponse.getString("email");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(UpdateInfoActivity.this);
builder.setMessage("Submission Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
UpdateInfoRequest updateInfoRequest = new UpdateInfoRequest(first_name, last_name, email, userID, responseListener);
RequestQueue queue = Volley.newRequestQueue(UpdateInfoActivity.this);
queue.add(updateInfoRequest);
Intent intent = new Intent(UpdateInfoActivity.this, MainActivity.class);
UpdateInfoActivity.this.startActivity(intent);
}
});
Change your code to this
if (success) {
LoginActivity.first_name = first_name;
LoginActivity.last_name = last_name;
LoginActivity.email_address = email;
}
and I wouldn't be using static variables like that if you want to have a global user profile you could do this
class User {
private static User user = null;
public String firstName = "";
private User() {}
public static synchronized User getInstance() {
if (user == null) user = new User();
return user;
}
}
to retrieve data from anywhere in project call this
String name = User.getInstance().firstName;
And to modify the data do this
User.getInstance().firstName = UserName;
First Understand that static variables are shared by all objects and methods of the class.
So we only have one instance of the static variable.
The ways to Update static variable from other class -
1.Through object.
2.Through Class name.
Enclosing the code sample.
class A{
static int val;
public A(){val=0; }
//....
}
class B{
A obj= new A();
public void updateStatic(){
obj.val=10; // updates values through object to 10
A.val=100; //updates values through class name to 100
}
//..
}
Hope it Helps
Transfer of data between activities using the static variable is not a better way in my opinion. It is bad practice. Transferring data using intents or save data in storage media and accessing from there will be the better solution.
but the static variable is not changing.
Should be... You told the code to do that
if (success) {
LoginActivity.first_name = jsonResponse.getString("first_name");
LoginActivity.last_name = jsonResponse.getString("last_name");
LoginActivity.email_address = jsonResponse.getString("email");
}
Just want to mention...
1) You update a String, not any TextView or EditText in your question, so if you expected to see a "visual change" in your app, then no, nothing will happen unless you call setText.
2) That code is wrapped in a try-catch, and could error, so check the logs for a JSONException. If those keys aren't sent back from the server, then sure, they won't update. For example, the JSON is only {"success": true }
Still, SharedPrefences should largely be preferred over static variables here.
In my Java Application Im trying to create user groups and assign permission to users depending on the user group they belongs to. This is how I programmed. When User Login to the system, grab the user name and store in a static variable. When user opens any Form, get the user name from static variable and check its group and permissions. Depending on the permissions disable and enable some components of the form. Here Im having problem retrieving the value from static variable stgroupName. Method checkuserrights() at ItmMgt class not getting the current user's name. Can someone please assist me to understand whats the wrong here. I guess, there should be many better ways to do this. So any suggestions welcome.
public class Login extends javax.swing.JInternalFrame {
public static String USERNAME;
USERNAME = txtUserName.getText(); // get the user name to static variable
}
public class ItemMgt extends javax.swing.JInternalFrame {
public ItemMgt() {
initComponents();
checkuserrights();
genarateID();
}
private void checkuserrights() {
try {
Usergroup usergroup = UserGroupController.getUserRights(Login.USERNAME);// check the user's rights passing user name from static variable.
if (usergroup != null) {
btnDelete.setEnabled(usergroup.isDeleteItem());
btnAdd.setEnabled(usergroup.isAdditem());
btnUpdate.setEnabled(usergroup.isUpdateitem());
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(ItemMgt.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ItemMgt.class.getName()).log(Level.SEVERE, null, ex);
}
}
public class UserGroupController {
public static Usergroup getUserRights(String username) throws ClassNotFoundException, SQLException {
Connection conn = DBConnection.conn();
String sql = "select * from UserGroup where uGroupName = ?";
Object[] values = {username};
ResultSet res = DBHandller.getData(sql, conn, values);
while (res.next()) {
String grpName = res.getString("uGroupName");
boolean additem = res.getBoolean("addItem");
boolean delitem = res.getBoolean("delteItem");
boolean upitem = res.getBoolean("editItem");
Usergroup ugroup = new Usergroup(grpName, additem, delitem, upitem);
return ugroup;
}
return null;
}
}
A static variable is by definition a gloabl object. When you change the value in one instance, then the value of all other instances of that object will have the same value. That's the point of using a static.
It sounds to me that your object design is wrong and you should use an object having information about a user which would include the groupname. This object you can pass around in your code.
Okay, so I have a java file which is loading another class and I want the java file to be able to edit and read variables from the class which is running.
For example:
I have a button which when pressed it sets a variable (This is the class file). I want the java file which is loading this class to be able to see the new value of the variable read it, set it and do whatever is needed. And I want the new value which is set to show up on the running java class.
This is what I have tried so far but when I try to edit the values like getting baseX it doesn't show up on the running class. Also, the baseX value should change when I do stuff on the running class but the stuff is not printed to the screen when I change them. It's as if reflection can't read stuff on runtime. So what does?
Class c = Class.forName("Client");
for (Method m : c.getMethods()) {
if (m.getName().contentEquals("main")) {
Object[] passedArgs = { args };
m.invoke(null, passedArgs);
}
}
Object instance = c.newInstance();
Field baseX = c.getField("baseX");
Field loggedIn = c.getField("loggedIn");
boolean gotValues = false;
while(!gotValues) {
boolean loggedin = loggedIn.getBoolean(instance);
if(loggedin) {
System.out.println(baseX.get(instance));
} else {
System.out.println(loggedin);
loggedIn.setBoolean(instance, true);
}
}
Also yeah getter/setter methods would work if they worked on runtime and I could make it so that when button x is pressed variable y changes on screen. What is a java bean? Also what if I wanted to just invoke a method and not get a value? Or what if I wanted to add my own methods/code?
Try this:
public class Client {
public Object baseX = new Object();
public boolean loggedIn;
}
-----
public class Main {
public static void main(String[] args) throws Exception {
Class c = Class.forName("Client");
/*for (Method m : c.getMethods()) {
if (m.getName().contentEquals("main")) {
Object[] passedArgs = {args};
m.invoke(null, passedArgs);
}
}*/
Object instance = c.newInstance();
Field baseX = c.getField("baseX");
Field loggedIn = c.getField("loggedIn");
boolean gotValues = false;
//while (!gotValues) {
boolean loggedin = loggedIn.getBoolean(instance);
if (loggedin) {
System.out.println("Logged in!");
System.out.println(baseX.get(instance));
}
else {
System.out.println("NOT Logged in!");
System.out.println(loggedin);
loggedIn.setBoolean(instance, true);
System.out.println(loggedIn.getBoolean(instance));
}
//}
}
}
Is it possible to lazily instantiate a final field?
The following code does not compile:
public class Test{
private final Connection conn;
public Connection getConnection(){
if(conn==null){
conn = new Connection();
}
return conn;
}
}
Is there an alternative?
No. The point of a final field is that it's set once, during construction, and will never change thereafter. How could the compiler or the VM know anything useful about conn in your case? How would it know that only that property should be able to set it, and not some other method?
Perhaps if you explained what you want the semantics to be, we could come up with an alterative. You could potentially have a "provider" interface representing a way to fetch a value, and then a MemoizingProvider which proxies to another provider, but only once, caching the value otherwise. That wouldn't be able to have a final field for the cached value either, but at least it would only be in one place.
Here's one way you can do it using Memoisation (with Callables):
Class Memo:
public class Memo<T> {
private T result;
private final Callable<T> callable;
private boolean established;
public Memo(final Callable<T> callable) {
this.callable = callable;
}
public T get() {
if (!established) {
try {
result = callable.call();
established = true;
}
catch (Exception e) {
throw new RuntimeException("Failed to get value of memo", e);
}
}
return result;
}
}
Now we can create a final conn!
private final Memo<Connection> conn = new Memo<Connection>(
new Callable<Connection>() {
public Connection call() throws Exception {
return new Connection();
}
});
public Connection getConnection() {
return conn.get();
}
Source
dhiller's answer is the classic double checked locking bug, do not use.
As Jon Skeet said, no, there isn't.
Interpreting your code sample you may want to do something like this:
public class Test{
private final Object mutex = new Object(); // No public locking
private Connection conn;
public Connection getConnection(){
if(conn==null){
synchronized (mutex) {
if(conn==null){
conn = new Connection();
}
}
}
return conn;
}
}
As a side note, it's possible to change a final field. At least instance fields. You just need some reflection:
import java.lang.reflect.Field;
public class LazyFinalField {
private final String finalField = null;
public static void main(String[] args) throws Exception {
LazyFinalField o = new LazyFinalField();
System.out.println("Original Value = " + o.finalField);
Field finalField = LazyFinalField.class.getDeclaredField("finalField");
finalField.setAccessible(true);
finalField.set(o, "Hello World");
System.out.println("New Value = " + o.finalField);
}
}
Original Value = null
New Value = Hello World