hoping someone can help with this as it's frying my brain now. I am new to RMI so this could be a basic amateurish mistake .
So I have a layered system where a userinterface creates an interface for an application layer and calls a getRecord function using RMI. This in turn creates an interface to a datalayer which retrieves the information from a database returning it to the appLayer which returns it to the userinterface. This works fine and the JTextFields are updated perfectly.
The problem is when i then try to send this information back through the applayer to another interface. When it gets to the new interface i can output the information to the console but it WILL NOT update the JTextFields on this interface and i cannot for the life of me understand why not.
My Main Interface:
IPatientRecord testRecord;
IAppLayer appLayer;
public class MainOffice extends JFrame {
private JPanel MainPanel;
private JPanel Background;
private JPanel TopPanel;
private JPanel LeftPanel;
private JPanel RightPanel;
private JTextField searchTextBox;
private JButton searchButton;
private JTextField NHSRegistrationNoTextField;
private JTextField patientNameTextField;
private JTextField addressTextField;
private JTextField postCodeTextField;
private JTextField conditionTextField;
private JButton confirmAndSendButton;
public MainOffice() {
add(MainPanel);
setSize(400, 400);
try {
Registry patientRegistry = LocateRegistry.getRegistry(1096);
Registry registry = LocateRegistry.getRegistry(1099);
testRecord = (IPatientRecord) patientRegistry.lookup("patientRecord");
appLayer = (IAppLayer) registry.lookup("appLayer");
System.out.println("Patient Record Interface Ready");
}
catch (Exception ex) {
System.out.println("Exception Creating Patient Record Interface: " + ex.getMessage());
}
searchButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
testRecord = appLayer.getPatientRecord(Integer.parseInt(searchTextBox.getText()));
System.out.println("Test Record " + testRecord.getName());
updateForm();
System.out.println("Patient returned to Main Office " + testRecord.getName());
}
catch (Exception ex) {
System.out.println("Exception in Search Button: " + ex.getMessage());
}
}
});
confirmAndSendButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("Patient: " + testRecord.getName());
System.out.println("Confirm and send pressed/nDetails sent: " + testRecord.getName());
appLayer.sendToAmbulance(testRecord);
}
catch (Exception ex) {
System.out.println("confirm and Send Exception: " + ex.getMessage());
}
}
});
}
public void updateForm() {
try{
NHSRegistrationNoTextField.setText(String.valueOf(testRecord.getNhsRegistrationNo()));
patientNameTextField.setText(testRecord.getName());
addressTextField.setText(testRecord.getAddress());
postCodeTextField.setText(testRecord.getPostCode());
conditionTextField.setText(testRecord.getCondition());
}
catch (RemoteException rex) {
System.out.println("Update form exception: " + rex.getMessage());
}
}
public static void main (String args[] ) {
MainOffice mainOffice = new MainOffice();
mainOffice.setVisible(true);
}
My App LAyer:
public class AppLayer implements IAppLayer {
List ambulances;
List hospitals;
Dictionary ambulanceDictionary;
IPatientRecord patientRecord;
public AppLayer() throws RemoteException{
ambulances = new ArrayList();
hospitals = new ArrayList();
ambulanceDictionary = new Hashtable();
}
#Override
public IPatientRecord getPatientRecord(int nhsNo) throws RemoteException {
try {
Registry registry = LocateRegistry.getRegistry(null,1098);
IDataLayer dataLayer = (IDataLayer) registry.lookup("dataLayer");
patientRecord = dataLayer.getPatientRecord(nhsNo);
System.out.println("Patient returned: " + patientRecord.getName());
//sendToAmbulance(patientRecord);
return patientRecord;
}
catch (Exception ex) {
System.out.println("Error in AppLayer: " + ex.getMessage() + " /n/nSee getPatientRecord in AppLayer");
return null;
}
}
The Function i Used to send to the other UI: The UI registers with the applayer first using another function. This uses that information to send the record to the right client essentially. The Main office UI calls this on through the applayer interface
public void sendToAmbulance(IPatientRecord patientRecord) {
Enumeration keys = ambulanceDictionary.keys();
Enumeration elements = ambulanceDictionary.elements();
int port = Integer.parseInt(keys.nextElement().toString());
String callSign = ambulanceDictionary.get(port).toString();
try {
System.out.println("Searching on port: " + port);
Registry registry2 = LocateRegistry.getRegistry(port);
System.out.println("Looking up callSign: " + callSign);
System.out.println("made it here");
IAmbulance ambulance = (IAmbulance) registry2.lookup(callSign);
System.out.println("and here");
ambulance.Update(patientRecord);
System.out.println("maybe here");
if (ambulance.Update(patientRecord)){
ambulanceDictionary.remove(port);
System.out.println(callSign + "removed from list");
System.out.println("");
}
else{
System.out.println("Failed to update ambulance " + callSign);
}
}
catch (Exception ex) {
System.out.println("Exception in sendToAmbulance: " + ex.getMessage());
}
}
The above function the calls Update on the Ambulance
public Boolean Update(IPatientRecord patientRecord) {
try {
NHSRegistrationNoTextField.setText(String.valueOf(patientRecord.getNhsRegistrationNo()));
patientNameTextField.setText(patientRecord.getName());
addressTextField.setText(patientRecord.getAddress());
postCodeTextField.setText(patientRecord.getPostCode());
conditionTextField.setText(patientRecord.getCondition());
ReadyStatusTxt.setText("ON CALL");
return true;
}
catch (Exception ex) {
System.out.println("Exception in Update: " + ex.getMessage());
return false;
}
}
It doesn't even update the ReadyStatusTxt.setText("On Call") yet returns true!
I've tried so many things. Originally i wasnt using the Patient record interface between the layers, I was being lazy but I've updated it so each different layer has to go through the Patient Interface and it still works the same way as before.
I added a seperate function to ambulance that would then call the database again pull the details for itself and then update it with this and it still will not update.
Is It as simple as I cant drive the update from an external class
Oh and another thing is if i put System.out.Println(patientRecord.getName()); in the above function it prints out the ******* name that i want to update the above aforementioned JtextField. I've tried saving that into Strings first and then adding it to the JtextField but that doesn't work either
Related
I read a couple questions related to pausing main and both gave answers I didn't understand, and frankly I don't think are applicable.
I have a JFrame that makes use of a database I'm setting up in my driver class.
The JFrame will launch and the window opens; however when I try to make use of the database it fails; because back in main the program just keeps running and shuts down the connection, and closes it.
I tried just removing the connection.close() code just to see if my database methods work in the JFrame, and they do, so I just need to learn how to halt main while my JFrame is running.
public static void main(String[] args) {
File dbPropertiesFile = new File(DbConstants.DB_PROPERTIES_FILENAME);
if (!dbPropertiesFile.exists()) {
showUsage();
System.exit(-1);
}
try {
new Lab9(dbPropertiesFile).run(args);
} catch (Exception e) {
LOG.error(e.getMessage());
e.printStackTrace();
} finally {
shutdown();
}
}
private static void configureLogging() {
ConfigurationSource source;
try {
source = new ConfigurationSource(new FileInputStream(LOG4J_CONFIG_FILENAME));
Configurator.initialize(null, source);
} catch (IOException e) {
System.out.println(
String.format("Can't find the log4j logging configuration file %s.", LOG4J_CONFIG_FILENAME));
}
}
private static void shutdown() {
LOG.info("Shutting down");
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOG.error(e.getMessage());
e.printStackTrace();
}
}
}
private static void showUsage() {
System.err.println(
String.format("Program cannot start because %s cannot be found.", DbConstants.DB_PROPERTIES_FILENAME));
}
private Lab9(File file) throws IOException {
properties = new Properties();
properties.load(new FileInputStream(file));
database = new Database(properties);
}
/**
* Where the computer start making a lot of noise.
*
* #param args
* #throws Exception
*/
private void run(String[] args) throws Exception {
LOG.info("Running");
LOG.info("Loading database properties from: " + DbConstants.DB_PROPERTIES_FILENAME + ".");
LOG.info(properties.getProperty("db.driver"));
LOG.info("Driver loaded");
LOG.info("DB URL = " + properties.getProperty("db.url"));
LOG.info("DB USER = " + properties.getProperty("db.user"));
LOG.info("DB PASSWORD = " + properties.getProperty("db.password"));
connect();
Statement statement = connection.createStatement();
try {
// If the user enters the -drop switch
if (args[0].equalsIgnoreCase(DROP_COMMAND)) {
LOG.info("Table " + CustomerDao.TABLE_NAME + "is being DROPPED!");
customerDao.drop();
LOG.info("Table has been DROPPED!");
}
// Check to see if the table is already made; if its not then make it, and fill
// it.
if (Database.tableExists(CustomerDao.TABLE_NAME) == false) {
createTables(statement);
LOG.info("Created the table: " + CustomerDao.TABLE_NAME + ".");
LOG.info("Inserting Customer objects into table: " + CustomerDao.TABLE_NAME + ".");
insertCustomers();
LOG.info("Inserted customer info into table from file: [" + CUSTOMER_DATA + "].");
}
createUI();
// I NEED MAIN
// TO STOP
// AROUND HERE!
}catch(SQLException e){
e.printStackTrace();
LOG.error(e.getMessage());
}finally{
connection.close();
}
}
public static void createUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseControlFrame frame = new DatabaseControlFrame(customerDao);
frame.setVisible(true);
// OR MAYBE I NEED MAIN
// TO STOP
// AROUND HERE!
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void connect() throws SQLException {
connection = database.getConnection();
customerDao = new CustomerDao(database);
}
}
Any ideas? I tried using a while(frame.isVisilbe()){ wait(600) }; But the compiler had a spas when I tried to use wait().
You'll note I'm passing a customerDAO object to my JFrame constructor; but I'm beginning to wonder could I make a connection inside the JFrame so that when main's connection closes; my JFrame's doesn't? Is that a good idea? Is that even possible I'm not super SQL savvy I'm going to need to study up on it more.
You could use Thread.sleep() - I've found that useful with JFrame before, though I'm not 100% sure it would fit what you're looking for. If you want it to wait indefinitely, put it in a while loop:
while(//condition)
{
Thread.sleep(500); //pauses for .5 sec, then loops back to check condition
}
JFrame event handler runs on a different thread than main thread, so you need to shutdown on that thread.
Here is a example, Using JDBC with GUI API.
This example call connection.close() on received window-closing-event.
public class MyFrame extends JFrame {
public MyFrame() {
// ...
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(final WindowEvent e) {
shutdown();
System.exit(0);
}
});
}
// ...
}
I am currently making a boardgame that allows two player through a socket. I am also trying to add in a game chat, but reguardless I need a way for the Frame class to act as normal (Jbuttons, enter text into a jscroll area, etc) but also send & look for incoming objects. I figured implementing runnable would be the best option.
here is my run method:
public void run() {
while(running){
Object obj = null;
try {
obj = connection.receiveObjects();
} catch (ClassNotFoundException) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
running = false;
if(obj != null){
if(obj instanceof String){
showMessage((String)obj);
}
}
}
}
My connection class is just a server or a client, and uses these methods:
public void sendObjects(Object obj) throws IOException{
output.writeObject(obj);
output.flush();
}
public Object receiveObjects() throws IOException, ClassNotFoundException{
return input.readObject();
}
At the Frame class's constructor I call
Thread thread = new Thread(this);
thread.start();
In hopes that the run method will not interfere with the actionPerformed method. But to my dismay, when I click a jbutton (all it does is call the send() method), the program freezes, and nothing is sent over.
Here is the other necessary code:
private JTextArea textBox;
private JScrollPane pane;
private JTextArea userText;
private JScrollPane userPane;
private void send(){
String message = "YOU- " + userText.getText();
userText.setText("");
String totalMessage = textBox.getText();
textBox.setText(totalMessage + "/n" + message);
try {
connection.sendObjects(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showMessage(String s){
String totalMessage = "Opponent- " + textBox.getText();
textBox.setText(totalMessage + "/n" + s);
}
My hope is that once I get the chat working, I can also add in sending over the pieces and calling other methods to do everything else I need (via instanceof). I could probably make a separate class that implements runnable to just deal with data transfer, but I was hoping I could do it all in one class, and do not see why I cannot. I did spend at least an hour and a half looking up multithreading, but I could not figure my problem out. I apologize If I am looking over anything apparent, but mutithreading and sockets are far beyond my comfort zone and AP Comp sci class education.
Besides the UI thread, you need:
one thread to constantly listen for incoming data
one thread to send data
You have #1 but not #2, so modify send() method as follows:
private void send() {
// Do the UI tasks on the UI thread
final String message = "YOU- " + userText.getText();
userText.setText("");
String totalMessage = textBox.getText();
textBox.setText(totalMessage + "\n" + message);
// Start new thread to do the networking (send data)
new Thread(new Runnable() {
#Override
public void run() {
try {
connection.sendObjects(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Now basically I have created three classes.
public void run() {
int seqId = 0;
while(true) {
List<KamMessage> list = null;
try {
list = fullPoll(seqId);
} catch (Exception e1) {
e1.printStackTrace();
}
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingMessages.addAll(list);
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
}
try {
Thread.sleep(3000);
System.out.println("new incoming message");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public List<KamMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 and SEQ >" +
lastSeq + "order by SEQ DESC");
List<KamMessage> pojoCol = new ArrayList<KamMessage>();
while (rs.next()) {
KamMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KamMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
return pojoCol;
}
The following are the classes:
1.Poller- does the Polling and Passes the new data from db to controller
2.Controller- this class has a thread Pool, which simultaneously calls the Poller and has the new data to be requested from processor
3.Processor- this class has to look for new data, process it and return it to controller.
So now my problem is how to implement the third phase...
Here is my controller class:
public class RunnableController {
/** Here This Queue initializes the DB and have the collection of incoming message
*
*/
private static Collection<KpiMessage> incomingQueue = new ArrayList<KpiMessage>();
private Connection dbConncetion;
public ExecutorService threadExecutor;
private void initializeDb()
{
//catching exception must be adapted - generic type Exception prohibited
DBhandler conn = new DBhandler();
try {
dbConncetion = conn.initializeDB();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initialiseThreads()
{
try {
threadExecutor = Executors.newFixedThreadPool(10);
PollingSynchronizer read = new PollingSynchronizer(incomingQueue, dbConncetion);
threadExecutor.submit(read);
}catch (Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unused")
private void shutDownThreads()
{
try {
threadExecutor.shutdown();
//DB handling should be moved to separate DB class
dbConncetion.close();
}catch (Exception e){
e.printStackTrace();
}
}
/** Here This Queue passes the messages and have the collection of outgoing message
*
*/
//private Collection<KpiMessage> outgingQueue = new ArrayList<KpiMessage>();
//have to implement something here for future
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
System.out.println(incomingQueue.size());
controller.initializeDb();
controller.initialiseThreads();
Thread.sleep(3000);
System.out.println("Polling");
}
}
I would recommend using a BlockingQueue for doing so, instead of a simple ArrayList. Just change the type of your incomingQueue variable. Then you can have another thread (or a thread pool) doing something like
//pseudocode
while (true) {
// it polls data from the incomingQueue that shares with the producers
KpiMessage message = this.incomingQueue.take()
//Then process the message and produces an output... you can put that output in a different queue as well for other part of the code to pick it up
}
A good example on BlockingQueues can be found here http://www.javamex.com/tutorials/blockingqueue_example.shtml
This pertains to my earlier post "http://stackoverflow.com/questions/8788825/linux-udp-server-unreachable-from-window-7", which has been solved. Now I am moving to my original job of connecting AVD to Linux server.
I am using the following code for connecting to the server
import java.net.*;
class UDPClient {
public final static int DesitnationPort = 9999;
private int mCounter;
private DatagramSocket mClientSocket;
private InetAddress mServerIPAddress;
private byte[] mDataBuffer;
private DatagramPacket mSendPacket;
private DatagramPacket mReceivePacket;
//Constructor
public UDPClient() {
//Time to make the private data good one
mCounter =1;
try {
mServerIPAddress = InetAddress.getByName("192.168.2.2");
}
catch(UnknownHostException e)
{
System.out.println("Host cannot be resolved :( ");
}
System.out.println("Host has been resolved The IP is valid one ");
try {
mClientSocket = new DatagramSocket();
}
catch(SocketException e)
{
System.out.println("Socket could not be created :( ==> " + e.getMessage());
}
System.out.println("Socket has been created ");
String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
mDataBuffer = temp.getBytes();
mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
System.out.println("Datagram has been made now ");
System.out.println("Data ==>"+ mSendPacket.getData());
System.out.println("Data ==>"+ mSendPacket.getPort());
System.out.println("Data ==>"+ mSendPacket.getSocketAddress());
System.out.println("Data ==>"+ mSendPacket.getLength());
}
public void SendDataToServer(){
try {
if(!mClientSocket.isClosed()) {
String temp = "This is from the Client == To my Dear Sever :) counter = " + mCounter;
mDataBuffer = temp.getBytes();
mSendPacket = new DatagramPacket(mDataBuffer, mDataBuffer.length, mServerIPAddress, DesitnationPort);
mClientSocket.send(mSendPacket);
System.out.println("Send the packet");
mCounter++;
}
else {
System.out.println("Socket is closed");
}
}
catch(Exception e)
{
System.out.println("Could not send the data :( ==> " + e.getMessage());
}
}
public void ReceiveDataFromServer() {
byte[] tembuff = new byte[1024];
mReceivePacket = new DatagramPacket(tembuff, tembuff.length);
try {
if(!mClientSocket.isClosed()) {
mClientSocket.receive(mReceivePacket);
}
else {
System.out.println("Socket is closed");
}
}
catch(Exception e)
{
System.out.println("Could not Receive the data :( ");
return;
}
String data = new String(mReceivePacket.getData());
System.out.println(" Received the Data => " + data);
}
}
This code works well when I simply use the class in java program like this :-
class TryingWithClient {
public static void main(String a[]) {
UDPClient mClient = new UDPClient();
while(true) {
System.out.println("While Starting");
mClient.SendDataToServer();
mClient.ReceiveDataFromServer();
}
}
}
When I use the same code in AVD project I get a Null pointer exception at the following line :-
public void SendDataToServer(){
try {
if(!mClientSocket.isClosed()){ //<==# this call Null exception occurs
After browsing internet & android development sites I came to conclusion that I am missing the GMS / GPS functionality which I added to my AVD. Still I am unable to get any clue about this.
Here is my code which calls the above UDPClient.
public class StreamingProjectActivity extends Activity {
/** Called when the activity is first created. */
//All buttons
//private static final String LOG_TAG = "StreamingTest";
private StreamButton mStreamButton = null;
private UDPClient mClient= null;
class StreamButton extends Button {
boolean mStartStreaming = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onStream(mStartStreaming);
if (mStartStreaming) {
setText("Stop Streaming");
} else {
setText("Start recording");
}
mStartStreaming = !mStartStreaming;
}
};
public StreamButton(Context ctx) {
super(ctx);
setText("Start Streaming");
setOnClickListener(clicker);
}
}//class StreamButton Ends
#Override
public void onCreate(Bundle icicle) {
try {
mClient = new UDPClient();
System.out.println("==========> Client created sucessfully :) <====== ");
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mStreamButton = new StreamButton(this);
ll.addView(mStreamButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
System.out.println("Trying Step 2 now ");
}
catch(Exception e)
{
System.out.println("Activity could not be launched :( ");
}
}
//public StreamingTest()
public StreamingProjectActivity(){
System.out.println("Constructor ====>");
System.out.println("Constructor <====");
}//Constructor
private void onStream(boolean start) {
if (start)
{
mClient.SendDataToServer();
mClient.ReceiveDataFromServer();
try
{
Thread.sleep(4000);
}catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
}//onStream
}
Kindly help.
Ok, first of all: never ever print a catched exception with System.out.println("some msg " + e.getMessage()); Please use Log.e(TAG, "my message", e); for that. So you will actually see a stack trace.
Second: I bet that this code throws an error (check if you see the print in your LogCat output):
try {
mClientSocket = new DatagramSocket();
} catch(SocketException e) {
System.out.println("Socket could not be created :( ==> " + e.getMessage());
}
That is the only reason that mClientSocket still might be null. As this call might go wrong, you should consider checking for null before you check if the socket is closed.
The problem in my earlier solution was that I was mixing the GUI & network operations in the same thread which is called "StricMode.ThreadPolicy" (although, my problem is only part of what is mentioned in the jargon).
I was getting these exceptions "android.os.NetworkOnMainThreadException & android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) " which I could make out only after I applied WarrenFaith's suggestion (Thanks Warren).
These are thrown only on violation of "StricMode".
Solution : Simply separate the UI work from the network. I had to write the following code for this :
enum ClientThreadStates {
eUndefined,
eStopped,
eRunning,
eIdle,
eSendToServer,
eReadFromServer
}
public class ClientThread extends Thread {
private UDPClient mClient= null;
private ClientThreadStates mStateOfTheThread = ClientThreadStates.eUndefined;
private static String mLOG_TAG;
public ClientThread(String s){
mLOG_TAG = s;
mStateOfTheThread = ClientThreadStates.eStopped;
mClient = new UDPClient(s);
start();
}//constructor
public void SetState(ClientThreadStates paramState) {
mStateOfTheThread = paramState;
}
public ClientThreadStates GetState() {
return mStateOfTheThread;
}
private void Action(ClientThreadStates s) {
synchronized(s) {
switch(mStateOfTheThread) {
case eRunning: //fall
case eIdle: break;
case eSendToServer: mClient.SendDataToServer(); break;
case eReadFromServer: mClient.ReceiveDataFromServer(); break;
}
try {
mStateOfTheThread.wait();
}
catch( InterruptedException e ){
Log.e(mLOG_TAG, "Got Exception at wait <==", e);
}
}
}
public void run() {
mStateOfTheThread = ClientThreadStates.eRunning;
System.out.println("In Thread.run .. The State is " + mStateOfTheThread);
while(ClientThreadStates.eStopped.compareTo(mStateOfTheThread) < 0){ //state >stopped
Action(mStateOfTheThread);
}//while
}//run
}//class ClientThread
Finally synchronize on the two threads on the state like this :
private void onStream(boolean start) {
ClientThreadStates State = mClientThread.GetState();
synchronized(State) {
if (start) {
mClientThread.SetState(ClientThreadStates.eSendToServer);
}
else {
mClientThread.SetState(ClientThreadStates.eReadFromServer);
}
try {
State.notify();
}
catch( IllegalMonitorStateException e ) {
Log.e(LOG_TAG, "Got Exception # notify <==", e);
}
}
}//onStream
}//StreamingProjectActivity
Now the code runs perfectly.
Thanks.
Ashutosh
It's me again and I just can't seem to get this code to work. I'm basically asking for any advice on why the button does nothing when clicked. Would you like me to attach the source code?
The method I'm trying to implement:
public static void UserInput() {
try {
stmt = connect.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
while (res.next()) {
if (res.getString("Username").equals(usernameField.getText())) {
if (res.getString("Password").equals(passwordField.getPassword())) {
JOptionPane.showMessageDialog(null, "Correct", "Correct",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Error. Incorrect "
+ "username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Error. Incorrect "
+ "username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
res.close();
stmt.close();
connect.close();
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
And here's how I'm calling it:
if(firstTime == false) {
JavaDB jdb = new JavaDB();
}
JavaDB window = new JavaDB("");
window.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
And here's the actionListner:
submit = new JButton("Submit");
c.add(submit);
submit.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
if(e.getSource().equals(submit)) {
UserInput();
}
}
}); ;
If you need anymore let me know. I've been teaching myself Java and I don't really know what to learn so any tips will be welcomed. I'm also new to stack overflow and posting code so any thing you can give me will be more than appreciated. Thanks in advance.
Edit: I now added a class for event handling with the Thread inside of it like this;
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(submit)){
Thread th = new Thread(new JavaDB());
th.start();
th.run();
try {
th.wait();
} catch (InterruptedException e1) {
}
}
else{
System.exit(0);
}
}
And I changed UserInput to run(). However,now when I click the submit button,The GUI disappears. Just for a reference you might need, here's my main method:
public static void main(String args[]) throws SQLException,
InterruptedException {
createConnection();
boolean firstTime = firstTime();
if (firstTime) {
JavaDB db = new JavaDB("");
db.createAccount();
try {
connect = DriverManager
.getConnection("jdbc:derby:\\KeithDB;shutdown=true");
} catch (SQLException XJ015) {
}
}
if (firstTime == false) {
JavaDB jdb = new JavaDB();
Thread th = new Thread();
}
JavaDB window = new JavaDB("");
window.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
Anything else you need,let me know
PasswordDemo, as shown in How to Use Password Fields, would be a good starting point for your study, and it would make an effective sscce.
Addendum: Absent a complete example or knowledge of what database you are using, I got the following result,
Version: H2 1.3.157 (2011-06-25) 1.3
by running the following modification to PasswordDemo against H2 Database:
if (isPasswordCorrect(input)) {
try {
Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:", "sa", "secret");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Version:"
+ " " + metaData.getDatabaseProductName()
+ " " + metaData.getDatabaseProductVersion()
+ " " + metaData.getDatabaseMajorVersion()
+ "." + metaData.getDatabaseMinorVersion());
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
} ...
Addendum: I got the following result,
Version: Apache Derby 10.6.2.1 - (999685) 10.6
by running the following modification to PasswordDemo against Apache Derby:
if (isPasswordCorrect(input)) {
try {
EmbeddedDataSource ds = new EmbeddedDataSource();
ds.setDatabaseName("/home/trashgod/.netbeans-derby/dbtest");
Connection conn = ds.getConnection("sa", "secret");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Version:"
+ " " + metaData.getDatabaseProductName()
+ " " + metaData.getDatabaseProductVersion()
+ " " + metaData.getDatabaseMajorVersion()
+ "." + metaData.getDatabaseMinorVersion());
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
} ...
I finally got it to work! I had another constructor with the same variable names and my call to the JTextFields were mistaken to be the call to the other constructor. The foo statements really helped!!! Thank you everyone!