I am trying to get an alert to pop up when my program receives the letter "A" over jserialcomm from my Arduino. I can confirm that my program receives the letter "A", as I have the program print a string to the console when it does, but the alert does not pop up. Has anyone seen this before?
#Override
public void serialEvent(SerialPortEvent serialPortEvent) {
if (serialPortEvent.getEventType() == SerialPort.LISTENING_EVENT_DATA_RECEIVED) {
byte[] temp = serialPortEvent.getReceivedData();
String message = new String(temp);
message = message.trim();
doneMessage = message;
System.out.println(message);
showAlert();
}
public void showAlert () {
System.out.println("Hello");
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.showAndWait();
}
}
Related
Hi I am writing a custom login dialog. I want to display a progress indicator while my users credentials are verified. When I run my button handler the progress indicator does not appear even though I call the setVisible(true) method. Also the text is not visible either.
#FXML
private void handleLoginButton2(ActionEvent event) {
//username and password required
if (userNameTextField.getText().isEmpty() || passwordTextField.getText().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Login Validation");
alert.setHeaderText("Validation Failed");
String msg = "Please input user name and password.";
alert.setContentText(msg);
alert.showAndWait();
} else {
try {
loginProgressIndicator.setVisible(true);
loginStatusText.setText("Authorising...");
Class.forName(JDBC_DRIVER2);
String user = userNameTextField.getText();
String password = passwordTextField.getText();
Connection conn = DriverManager.getConnection(JDBC_URL2, user, password);
loginStatusText.setText("Authorisation Successful");
loginProgressIndicator.setVisible(false);
//close login window
windowManager.closeLoginWindow();
//open main screen
windowManager.showMainView();
} catch (ClassNotFoundException | SQLException | IOException ex) {
Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
loginStatusText.setText("Authorisation Failed");
loginProgressIndicator.setVisible(false);
}
}
}
Do the DB access from a task running in a seperate thread and handle the results in the onSucceeded/onFailed event handlers:
public class AuthorizeTask extends Task<Void> {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/victorydb?zeroDateTimeBehavior=convertToNull";
private final String user;
private final String password;
public AuthorizeTask(String user, String password) {
if (user == null || password == null) {
throw new IllegalArgumentException();
}
this.user = user;
this.password = password;
}
#Override
protected Void call() throws Exception {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(JDBC_URL, this.user, this.password);
return null;
}
}
Task<Void> task = new AuthorizeTask(userNameTextField.getText(), passwordTextField.getText());
task.setOnFailed(evt -> {
Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, task.getException());
loginStatusText.setText("Authorisation Failed");
loginProgressIndicator.setVisible(false);
});
task.setOnSucceeded(evt -> {
// you may need to add a try/catch here
loginStatusText.setText("Authorisation Successful");
loginProgressIndicator.setVisible(false);
//close login window
windowManager.closeLoginWindow();
//open main screen
windowManager.showMainView();
});
loginProgressIndicator.setVisible(true);
loginStatusText.setText("Authorising...");
// run this on background thread to avoid blocking the application thread
new Thread(task).start();
You may want to change the type parameter of Task to Connection though, since you probably need to work with the Connection later...
I am using a local notification in my application like this.
showNotification(this, "Title1", "Message One", 1);
showNotification(this, "Title2", "Message Two", 2);
showNotification(this, "Title3", "Message Three", 3);
showNotification(this, "Title4", "Message Four", 4);
public static void showNotification(Context con, String title,
String message, int id) {
NotificationManager manager = (NotificationManager) con
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.ic_noti_logo,title, System.currentTimeMillis());
Intent notificationIntent = new Intent(con,Result.class);
notificationIntent.putExtra("Message", message);
notificationIntent.putExtra("NotiId", id);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(con, 0,
notificationIntent, PendingIntent.FLAG_ONE_SHOT);
note.setLatestEventInfo(con, title, message, pi);
note.defaults |= Notification.DEFAULT_ALL;
note.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(id, note);
}
in Resut.java
message = getIntent().getStringExtra("Message");
notiId = getIntent().getIntExtra("NotiId", 0);
showAlert(message,notiId);
private void showAlert(String msg, int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish();
cancelNotification(Result.this,id);
}
});
AlertDialog alert = builder.create();
alert.show();
}
public static void cancelNotification(Context con, int id) {
NotificationManager manager = (NotificationManager) con
.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(id);
}
my problem is that, I am getting 4 notification message in notification bar and when I am clicking any of them I am redirecting to Result Activity but it hapens only ones when second time I clicked there was no effect. please help me.
The problem is that the four notifications share the same PendingIntent because they reference equivalent Intents (the docs for Intent.filterEquals() explain that to be considered distinct, Intents must differ in either action, data, class, type, or categories—note that extras are specifically not considered when determining whether Intents are equal). Furthermore, you're using PendingIntent.FLAG_ONE_SHOT which guarantees the PendingIntent can only be used once.
I am working on Push notifications for iPhone. I am sending notification on button click, but the iPhone developer is not receiving the alert message. Can anyone plz help me?
This is my method --
protected void btnPush_Click(object sender, EventArgs e)
{
string devicetoken = "bhsdse78 d52c6a34 273de5f7 27947945 24736e36 33d93a6c 3147a416 434995eb";
try
{
if (devicetoken != "")
{
//lblError.Visible = false;
string p12FileName = "D:/Worksapace/Coupzila/Certificates(3).p12"; // change this to reflect your own certificate
string p12Password = "seas"; // change this
bool sandBox = true;
int numConnections = 1; // you can change the number of connections here
var notificationService = new NotificationService(sandBox, p12FileName, p12Password, numConnections);
var deviceToken = devicetoken; // put in your device token here
var notification = new Notification(deviceToken);
notification.Payload.Alert.Body = "Hi this is push notification test message.";
notification.Payload.Sound = "default";
notification.Payload.Badge = 1;
notification.Payload.HideActionButton = true;
if (notificationService.QueueNotification(notification))
{ }
else
{ }
// This ensures any queued notifications get sent befor the connections are closed
notificationService.Close();
notificationService.Dispose();
}
else
{
//lblError.Visible = true;
}
}
catch (Exception ex)
{
}
}
This method is running successfully, but not getting notifications on iPhone, Whtz problem in my code?
Help me out, Thanks in advance
First, Remove the empty characters from your deviceToken.
Second, Put # sign for your fileName;
string p12FileName = #"D:/Worksapace/Coupzila/Certificates(3).p12";
And for the last step implement your catch, like;
catch (Exception ex)
{
MessageBox.Show("There is an error from push notification. Details:\n" + ex);
}
And good with Apple.
I'm trying to connect to SSH Unix server on button click (code written in actionPerformed() method). I'm using JSch for connecting to SSH server. The code is written in SwingWorker class as it is a network operation.
private void testConnectionButtonActionPerformed(java.awt.event.ActionEvent evt) {
SwingWorker<Boolean, Void> sw = new SwingWorker<Boolean, Void>(){
#Override
protected Boolean doInBackground() throws Exception {
JSch jsch = new JSch();
String host = "ServerHost";
String username = "username";
String password = "password";
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return true;
}
#Override
public void done(){
try {
System.out.println(get().toString());
} catch (Exception ex) {
System.out.err(ex);
}
}
};
sw.execute();
}
But after running the with correct host, username and password details, I get the below error all the time:
com.jcraft.jsch.JSchException: timeout: socket is not established
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
But whenever I run the same code in standalone program, I mean instead for writing actionPerformed() method, If I write it in normal method and calling from main() method. It will work. when I integrate the same code with Button Click's actionPerformed() method, it will give me above exception.
Can anyone suggest what I'm doing wrong here or any modification should be made to the code.
I tried to connect to SSH Server using "SSHJ" implementation, but I get the below error:
java.net.SocketException: Connection reset
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
Can someone help me - how to move forward?
I took your code, wrapped it in some GUI code (and converted it to non-generics to be able to compile it with the same settings as the rest of the JSch examples). It works for me. Try this, and report what exception you get (it has a bit more exception logging).
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import com.jcraft.jsch.*;
class SwingWorkerExample {
JTextField hostField;
JTextField userNameField;
JTextField passwordField;
JPanel panel;
public SwingWorkerExample() {
JPanel p = panel = new JPanel(new GridLayout(0,2));
hostField = new JTextField(20);
userNameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton testButton = new JButton("connect!");
testButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
testConnectionButtonActionPerformed(ev);
}
});
p.add(new JLabel("host:"));
p.add(hostField);
p.add(new JLabel("user:"));
p.add(userNameField);
p.add(new JLabel("password:"));
p.add(passwordField);
p.add(testButton);
}
public JPanel getPanel() {
return panel;
}
private void testConnectionButtonActionPerformed(ActionEvent evt) {
SwingWorker sw = new SwingWorker(){
protected Object doInBackground() throws Exception {
try {
JSch jsch = new JSch();
String host = hostField.getText();
String username = userNameField.getText();
String password = passwordField.getText();
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return session;
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static void main(String[] egal) {
EventQueue.invokeLater(new Runnable(){public void run() {
SwingWorkerExample ex = new SwingWorkerExample();
JFrame f = new JFrame("bla");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(ex.getPanel());
f.pack();
f.setVisible(true);
}});
}
}
I'm trying to send data from a midlet to a servlet and recieve back a response from the servlet but I don't get any value in response. I've tried to print it on command window and it seems to be null yet I expect only two values "ok" or "error". Please help me check the code and let me know what I should do to get the response right on the midlet. My code is below:
import javax.microedition.midlet.*;//midlet class package import
import javax.microedition.lcdui.*;//package for ui and commands
import javax.microedition.io.*;//
import java.io.*;
/**
* #author k'owino
*/
//Defining the midlet class
public class MvsMidlet extends MIDlet implements CommandListener {
private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;
private Form vCode;//vote code
private StringItem welStr;
private TextField phoneField;
private StringItem phoneError;
private Command quitCmd;
private Command contCmd;
//constructor of the midlet
public MvsMidlet() {
display = Display.getDisplay(this);//creating the display object
welForm = new Form("THE MVS");//instantiating welForm object
welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
+ "Please enter the your phone number below");//instantiating welStr string item
phoneError = new StringItem("", "");//intantiating phone error string item
phoneField = new TextField("Phone number e.g 0789834141", "", 10, 3);//phone number field object
quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
welForm.append(welStr);//adding welcome string item to form
welForm.append(phoneField);//adding phone field to form
welForm.append(phoneError);//adding phone error string item to form
welForm.addCommand(contCmd);//adding continue command
welForm.addCommand(quitCmd);//adding quit command
welForm.setCommandListener(this);
display.setCurrent(welForm);
}
//start application method definition
public void startApp() {
}
//pause application method definition
public void pauseApp() {
}
//destroy application method definition
public void destroyApp(boolean unconditional) {
}
//Command action method definition
public void commandAction(Command c, Displayable d) {
if (d == welForm) {
if (c == quitCmd) {
exitMidlet();//call to exit midlet
} else {//if the command is contCmd
//place a waiting activity indicator
System.out.println("ken de man");
Thread t = new Thread() {
public void run() {
try {
//method to connect to server
sendPhone();
} catch (Exception e) {
}//end of catch
}//end of ru()
};//end of thread
t.start();//starting the thread
}//end of else
}//end of first if
}//end of command action
//defining method to exit midlet
public void exitMidlet() {
display.setCurrent(null);
destroyApp(true);
notifyDestroyed();
}//end of exitMidlet()
//defining sendPhone method
public void sendPhone() throws IOException {
System.out.println("ken de man");//check
HttpConnection http = null;//HttpConnection variable
OutputStream oStrm = null;//OutputStream variable
InputStream iStrm = null;//InputStream variable
String url = "http://localhost:8084/MvsWeb/CheckPhone";//server url
try {
http = (HttpConnection) Connector.open(url);//opening connection
System.out.println("connection made");//checking code
oStrm = http.openOutputStream();//opening output stream
http.setRequestMethod(HttpConnection.POST);//setting request type
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
byte data[] = ("phone=" + phoneField.getString()).getBytes();
oStrm.write(data);
iStrm = http.openInputStream();//openning input stream
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
int length = (int) http.getLength();
String str;
if (length != -1) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
} else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) {
bStrm.write(ch);
}
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("de man");
System.out.println(str);
if (str.equals("ok")) {
//change to vcode form
} else {
//add error message to phone_error stingItem
}
}
} catch (Exception e) {
}
}
}//end of class definition
//servlet
import java.io.*;//package for io classes
import javax.servlet.ServletException;//package for servlet exception classes
import javax.servlet.http.*;
import java.sql.*;//package for sql classes
/**
*
* #author k'owino
*/
public class CheckPhone extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//declaring variables
PrintWriter pw;//PrintWriter object
String pnum;//phone parameter sent from client
Connection con = null;//connection variable
String dbDriver = "com.jdbc.mysql.Driver";//the database driver
String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
String dbUser = "root";//database user
String dbPwd = "";//database password
PreparedStatement pstmt = null;//Prepared statement variable
String query = "select * from student where stud_phone = ?;";
ResultSet rs = null;//resultset variable
String dbPhone=null;//phone from database
//getting the "phone" parameter sent from client
pnum = req.getParameter("phone");//getting the "phone" parameter sent from client
System.out.println(pnum);
//setting the content type of the response
res.setContentType("text/html");
//creating a PrintWriter object
pw = res.getWriter();
pw.println("ken");
try{//trying to load the database driver and establish a connection to the database
Class.forName(dbDriver).newInstance();//loading the database driver
con = DriverManager.getConnection(dbUrl,dbUser,dbPwd);//establishing a connection to the database
System.out.println("connection established");
}
catch(Exception e){
}
//trying to query the database
try{
pstmt = con.prepareStatement(query);//preparing a statement
pstmt.setString(1, pnum);//setting the input parameter
rs = pstmt.executeQuery();//executing the query assigning to the resultset object
//extracring data from the resultset
while(rs.next()){
dbPhone = rs.getString("stud_phone");//getting the phone number from database
}//end of while
if(pnum.equals(dbPhone)){
pw.print("ok");
pw.close();
}
else{
pw.print("error");
pw.close();
}
}
catch(Exception e){
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}