This code used to work with Eclipse Kepler. But the developer that wrote it is gone and it is no longer working with an upgrade to Neon plugins. I am getting this exception:
Caused by: org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.IllegalArgumentException: Argument cannot be null)
at org.eclipse.swt.SWT.error(SWT.java:4533)
at org.eclipse.swt.SWT.error(SWT.java:4448)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:185)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4536)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:4154)
at com.example.server.commons.SysTrayThread.localRun(SysTrayThread.java:141)
at com.example.server.commons.SysTrayThread$2.run(SysTrayThread.java:87)
With this code:
private static final String SYSTEM_BUNDLE_ID = "org.eclipse.osgi"; //$NON-NLS-1$
private volatile boolean working = true;
private final Bundle bundle;
private final String logoPath;
private Display display;
public SysTrayThread (final Bundle bundle, final String logoPath) {
this.bundle = bundle;
this.logoPath = logoPath;
}
#Override
public void run() {
if(System.getProperty("os.name").equals("Mac OS X")) {
Class<?> comAppleConcurrentDispatch = null;
try {
comAppleConcurrentDispatch = Class.forName("com.apple.concurrent.Dispatch");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Method getInstance = null;
Object dispatchInstance = null;
Method getNonBlockingMainQueueExecutor = null;
Executor executor = null;
try {
getInstance = comAppleConcurrentDispatch.getMethod("getInstance", (Class<?>[]) null);
dispatchInstance = getInstance.invoke(null, (Object[]) null);
getNonBlockingMainQueueExecutor = dispatchInstance.getClass().getMethod("getNonBlockingMainQueueExecutor",(Class<?>[]) null);
executor = (Executor) getNonBlockingMainQueueExecutor.invoke(dispatchInstance, (Object[]) null);
executor.execute(new Runnable() {
public void run() {
try {
localRun();
} catch(Throwable t) {
}
}
}
);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
localRun();
}
});
}
}
public void localRun()
{
try {
SysTrayThread.this.display = Display.getDefault();
} catch (org.eclipse.swt.SWTError ex) {
return;
}
URL url = SysTrayThread.this.bundle.getEntry(SysTrayThread.this.logoPath);
try {
Image image = null;
Shell shell = new Shell(SysTrayThread.this.display);
InputStream stream = url.openStream();
try {
image = new Image(SysTrayThread.this.display, new ImageData(stream));
} finally {
stream.close();
}
final Menu menu = new Menu(shell, SWT.POP_UP);
MenuItem exitMenuItem = new MenuItem(menu, SWT.PUSH);
exitMenuItem.setText(Messages.SHUTDOWN_MENU_ITEM);
exitMenuItem.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(final SelectionEvent event) {
Bundle bundle = Platform.getBundle(SysTrayThread.SYSTEM_BUNDLE_ID);
try {
bundle.stop();
} catch (BundleException ex) {
throw new RuntimeException(ex);
}
}
});
Tray tray = SysTrayThread.this.display.getSystemTray();
TrayItem trayItem = new TrayItem(tray, SWT.NONE);
trayItem.addListener(SWT.MenuDetect, new Listener() {
#Override
public void handleEvent(final Event event) {
menu.setVisible(true);
}
});
trayItem.setImage(image);
while (SysTrayThread.this.working && !shell.isDisposed()) {
if (!SysTrayThread.this.display.readAndDispatch()) { // line 141
SysTrayThread.this.display.sleep();
}
}
tray.dispose();
image.dispose();
if (!shell.isDisposed()) {
shell.dispose();
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public void setWorking(final boolean working) {
if (this.display != null) {
this.display.syncExec(new Runnable() {
#Override
public void run() {
SysTrayThread.this.display.close();
}
});
}
this.working = working;
}
I had a look for RCP specific information on this problem, but the answers relate to setting an SWT element to null. As you can see I am not setting a value, just calling readAndDispatch().
Any ideas?
Related
So I'm making a simple chat where I'm sending content in the form of objects, in this case my problem is that when I'm sending and Image it just blocking my Client!, here's my shortened code.
I've isolated it mostly to the code below, as I've tested the rest and worked fine, I've also tried debugging this but I just can't seem to find the problem
Image
package com.example.mtc.Packets;
import java.io.Serializable;
public class Image extends Message implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3188407715959746920L;
private byte[] content;
private String type;
public Image(byte[] content,String type, int sourceID,int destinationID,String sourceUsername) {
super(destinationID,sourceID,sourceUsername);
this.content = content;
this.type = "." + type;
}
public byte[] getContent() {
return content;
}
public String getType() {
return type;
}
}
ClientReaderThread:
while (true) {
try {
inputData = in.readObject();
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300, java.awt.Image.SCALE_DEFAULT));
if (imagePacket.getDestinationID() == 0) {
if (Cliente.selectedChat == 0) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
} else if (imagePacket.getSourceID() == Cliente.selectedChat
|| imagePacket.getSourceID() == Cliente.getUserID()) {
Style style = chatCard.doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, imageIcon);
chatCard.doc.insertString(chatCard.doc.getLength(), "ignored text\n", style);
chatCard.textPane.setCaretPosition(chatCard.textPane.getDocument().getLength());
Cliente.gui.revalidate();
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(Cliente.gui, "Couldn't connect to Server!", "Error",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server Listener
private void Listener() {
// TODO Auto-generated method stub
while (connected) {
inputData = readObject();
if (inputData != null) {
if (inputData.getClass().getName().equals("com.example.mtc.Packets.Image")) {
Image imagePacket = (Image) inputData;
byte[] imageContent = imagePacket.getContent();
ImageIcon imageIcon = new ImageIcon(imageContent);
imageIcon.setImage(imageIcon.getImage().getScaledInstance(300, 300,
java.awt.Image.SCALE_DEFAULT));
imageIcon.getImage().flush();
BufferedImage bi = new BufferedImage(
imageIcon.getIconWidth(),
imageIcon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
imageIcon.paintIcon(null, g, 0,0);
g.dispose();
try {
File imageFile = File.createTempFile("image", imagePacket.getType(),
new File("./serverImages/"));
insertLog(imageFile.getAbsolutePath(), imagePacket.getDestinationID(), true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Files.write(imageFile.toPath(), imageContent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (imagePacket.getDestinationID() == 0) {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
t.sendObject(imagePacket);
}
}
}
} else {
synchronized (Server.Threads) {
for (ClientHandler t : Server.Threads) {
if (!idExistsInBlockedList(t.getUserID(), userID)) {
if (t.getUserID() == imagePacket.getDestinationID()) {
t.sendObject(imagePacket);
}
}
}
sendObject(imagePacket);
}
}
}
}
}
}
Managed to solve it by using SwingUtilities.invokeLater(), as advised by R.L.M
I want to create new Runnable in a loop. However, it is not possible to use a variable within an inner class. I cannot use global/instance variable because it generates wrong results. My program is similar to the simplified code that follows:
public class RunManager {
public void runManager(int delay, final Context context) {
for (int dim = 7; dim < 227; dim++) {
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
the error is: Variable 'dim' is accessed from within inner class, needs to be declared final.
Your problem is you're trying to access a non final variable from a new thread. In order for variable to ne accesed from new thread it needs to be declared as final. In your cas you can just copy the dim int to a final int array of size 1 then access the array from thread.
Probably the most legible way of doing it would be to create a constructor for your Runnable which accepts an int as parameter. Such as:
public class MyRunnable implements Runnable {
public MyRunnable(Context context, int dim) {
// save parameters as class variables
}
public void run() {
// do the work
}
}
Then call it:
Runnable r = new MyRunnable(context, dim);
new Thread(r).start();
You should use final int[] dim if you want to have access to the value within inner class.
public class RunManager {
public void runManager(int delay, final Context context) {
for (final int dim[] = {7}; dim[1] < 227; dim[1]++) {
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, dim[1]);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Option 2 - use field:
public class RunManager {
private int _dim;
public void runManager(int delay, final Context context) {
for (int dim = 7; dim < 227; dim++) {
_dim = dim;
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, _dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Option 3 - iterate in another method and add final int dim as method argument:
private void createThreads(int delay, final Object context) {
for (int dim = 7; dim < 227; dim++) {
runManager(delay, context, dim);
}
}
public void runManager(int delay, final Context context, final int dim) {
Runnable r = new Runnable() {
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
};
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Option 4 - use custom runnable. You can implement class as recommended by #BMacedo or create abstract class and implement logic in inner class.
public class RunManager {
public void runManager(int delay, final Context context) {
for (int dim = 7; dim < 227; dim++) {
CustomRunnable r = new CustomRunnable() {
private int _dim;
#Override
public void run() {
RandomKernels randomKernels = new RandomKernels();
try {
randomKernels.foo(context, _dim);
} catch (InterruptedException e) {
Log.e(tag, e.getMessage());
}
}
public void setDim(int dim) {
_dim = dim;
}
};
r.setDim(dim);
Thread cnnThread = new Thread(r);
cnnThread.start();
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
abstract class CustomRunnable implements Runnable {
public abstract void setDim(int dim);
}
}
I'm creating a Netbeans module. How do I pass a selected text in the java editor as a parameter to my ActionListener class and, after process it, how do I replace this old text (passed as parameter) by the new processed text in the java editor?
#ActionID(category = "Edit", id = "com.beg.regextester.RegexTesterListener")
#ActionRegistration(displayName = "Regex Tester")
#ActionReference(path = "Editors/text/x-java/Popup")
public class RegexTesterListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//the code here
}
After a long research, I got it.
#ActionID(category = "Edit", id = "com.beg.regextester.RegexTesterListener")
#ActionRegistration(displayName = "Regex Tester")
#ActionReference(path = "Editors/text/x-java/Popup")
public class RegexTesterListener implements ActionListener {
private final DataObject context;
public RegexTesterListener(DataObject context) {
this.context = context;
}
#Override
public void actionPerformed(ActionEvent e) {
//Identify java object in the context
FileObject fileObject = context.getPrimaryFile();
JavaSource javaSrc = JavaSource.forFileObject(fileObject);
if (javaSrc == null) {
StatusDisplayer.getDefault().setStatusText(fileObject.getPath() + " is not a java file");
} else {
try {
javaSrc.runUserActionTask(new org.netbeans.api.java.source.Task<CompilationController>() {
#Override
public void run(CompilationController p) throws Exception {
p.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
Document doc = p.getDocument();
if (doc == null) {
StatusDisplayer.getDefault().setStatusText("Java file is closed");
} else {
new MemberVisitor(p).scan(p.getCompilationUnit(), null);
}
}
}, true);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}//end else
}//end actionPerformed
private static class MemberVisitor extends TreePathScanner<Void, Void> {
private CompilationInfo info;
public MemberVisitor(CompilationInfo info) {
this.info = info;
}
#Override
public Void visitClass(ClassTree t, Void v) {
try {
JTextComponent editor = EditorRegistry.lastFocusedComponent();
if (editor.getDocument() == info.getDocument()) {
int dot = editor.getCaret().getDot();
TreePath tp = info.getTreeUtilities().pathFor(dot);
Element el = info.getTrees().getElement(tp);
if (el != null) {
StatusDisplayer.getDefault().setStatusText("Please, select a string");
} else {
//get the selected text
String str = editor.getSelectedText();
//process the string and pass it to the clipboard
...
//replacing the old str by the new one
editor.paste();
}
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
}
}//end class
Below is my code:-
public class MainScreen extends javax.swing.JFrame {
private TableRowSorter<TableModel> sorter;
public MainScreen() {
initComponents();
this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
sorter = new TableRowSorter<>(tblCustomer.getModel());
tblCustomer.setRowSorter(sorter);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
System.out.println("I'm here "+findAll.size());
((DefaultTableModel) tblCustomer.getModel()).setDataVector(getDataVector(findAll), getVectorHeader());
tblCustomer.setAutoCreateRowSorter(true);
tblCustomer.getColumnModel().getColumn(0).setMinWidth(0);
tblCustomer.getColumnModel().getColumn(0).setMaxWidth(0);
}
public static Vector getDataVector(List<BasicDetailsDTO> listData) {
Vector dataVector = new Vector();
for (BasicDetailsDTO instance : listData) {
Vector row = new Vector();
row.add(instance.getId());
row.add(instance.getParticulars());
row.add(instance.getBookedBy());
row.add(instance.getContactPerson());
row.add(instance.getMobileNo());
row.add(instance.getEmail_id());
dataVector.add(row);
}
return dataVector;
}
public static Vector getVectorHeader() {
Vector header = new Vector();
header.add("ID");
header.add("Particulars");
header.add("BOOKED BY");
header.add("CONTACT PERSON");
header.add("MOBILE NO");
header.add("EMAIL ID");
return header;
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new HomePage(), "Details Of Customer", 1200, 800);
}
private void tblCustomerKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void tblCustomerMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please Select the Record");
return;
}
int option = displayConfirmDialog("Do you Really want to delete Record ?");
if (option == JOptionPane.YES_OPTION) {
String recordId = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordId));
instance.setDeleted(Boolean.TRUE);
UtilDAO.getDaoBasicDetails().remove(instance);
List<BasicDetailsDTO> findAll = UtilDAO.getDaoBasicDetails().findAll();
getDataVector(findAll);
displayMessage(" Record Deleted ");
}
}
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1200, 1000);
}
private void tblCustomerMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() == 2) {
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
displayPanel(new HomePage(instance, 1), "Customer " + instance.getBillingName(), 1000, 1000);
}
}
private void btnViewHotelListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewHotelDetails(), "List Of Hotels", 800, 700);
}
private void btnViewAgencyListActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
displayPanel(new ViewAgencyDetails(), "List Of Hotels", 800, 700);
}
private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if (evt.getKeyCode() != KeyEvent.VK_ENTER && evt.getKeyCode() != KeyEvent.VK_DOWN) {
if (txtSearch.getText().trim().length() > 0) {
RowFilter<TableModel, Object> filter = new RowFilter<TableModel, Object>() {
#Override
public boolean include(javax.swing.RowFilter.Entry<? extends TableModel, ? extends Object> entry) {
String search = txtSearch.getText().trim().toLowerCase();
// System.out.println(entry.getStringValue(1));
return (entry.getValue(1).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(2).toString().toLowerCase().indexOf(search) != -1 || entry.getValue(3).toString().toLowerCase().indexOf(search) != -1);
}
};
sorter.setRowFilter(filter);
//sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
// System.out.println("New Row is " + filter);
} else {
sorter.setRowFilter(null);
tblCustomer.setRowSorter(sorter);
}
} else {
if (tblCustomer.getRowCount() > 0) {
tblCustomer.requestFocus();
tblCustomer.setRowSelectionInterval(0, 0);
} else {
txtSearch.requestFocus();
}
}
}
private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
InputStream in = MainScreen.class.getResourceAsStream("Passenger_Name.docx");
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
IContext context = report.createContext();
if (tblCustomer.getSelectedRow() == -1) {
displayError("Please select record.");
return;
}
String recordID = tblCustomer.getValueAt(tblCustomer.getSelectedRow(), 0).toString();
BasicDetailsDTO instance = UtilDAO.getDaoBasicDetails().findById(Integer.parseInt(recordID));
context.put("Customer", instance);
OutputStream out = new FileOutputStream(new File("Passenger Name_Out.docx"));
report.process(context, out);
Desktop desktop = Desktop.getDesktop();
File f = new File("Passenger Name_Out.docx");
desktop.open(f);
} catch (IOException | XDocReportException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainScreen.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
new MainScreen().setVisible(true);
}
});
}
public static void setlblMessageDetail(String msg) {
MainScreen.lblMessage.setHorizontalAlignment(JLabel.CENTER);
MainScreen.lblMessage.setText(msg);
}
// Variables declaration - do not modify
}
Whenever I update the data within the table, the updated data is not reflected. The updated data is reflected only when I reopen the window.
Kindly help me through.
Thanks in advance.
why voids for DefaultTableModel and JTableHeader are static
remove rows from DefaultTableModel
use DocumentListener instead of KeyListener for RowFilter
why is there initialized two different LookAndFeels
updates to DefaultTableModel must be done on EDT, more in Oracle tutorial Concurrency in Swing - The Event Dispatch Thread
search for ResultSetTableModel, TableFromDatabase, BeanTableModel
rest of issue is hidden in shadowing void or classes, note remove all static declare, there should be static only main class
I need Your help!
So I got this app on an Android device, in which I get data from the accelerometer, and button presses which get this data to an edittext, and sets listeners on the edittextes.
When it's changed, there's a functions that creates a socket, sends data, and closes the socket.
Then I have a server app on my computer, in which I create serversockets, and create two threads that are waiting for serversocket.accept() that gets the data and put it into texbox. Simple as that.
I'm glad that I got it working anyway :-) but the point is, it's not working so well. I believe that whole communication is bad and not optimized. It sends data well, but often freezes, then unfreezes and sends quickly all previous data and so on.
I'm sorry for my bad code, but can someone please take a good look on this, and propose what I should change and how I could make it work more smooth and stable? :-(
Here's the Client code:
package com.test.klienttcp;
//import's...
public class Klient extends Activity implements SensorListener {
final String log = "Log";
EditText textOut;
EditText adres;
EditText test;
EditText gazuje;
TextView textIn;
TextView tekst;
TextView dziala;
String numer = null;
float wspk = 0; // wspolczynniki kalibracji
float wychylenietmp = 0;
float wychylenie = 0;
int tmp = 0;
int i = 0;
boolean wysylaj = false;
SensorManager sm = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textOut = (EditText)findViewById(R.id.textout);
adres = (EditText)findViewById(R.id.adres);
gazuje = (EditText)findViewById(R.id.gazuje);
Button kalibracja = (Button)findViewById(R.id.kalibracja);
Button polacz = (Button)findViewById(R.id.polacz);
Button gaz = (Button)findViewById(R.id.gaz);
Button hamulec = (Button)findViewById(R.id.hamulec);
kalibracja.setOnClickListener(kalibracjaOnClickListener);
polacz.setOnClickListener(polaczOnClickListener);
gaz.setOnTouchListener(gazOnTouchListener);
hamulec.setOnTouchListener(hamulecOnTouchListener);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
//text listener steering
textOut.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Wyslij();
}
}
});
//text listener for throttle
gazuje.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(wysylaj)
{
Gaz();
}
}
});
}
Button.OnClickListener polaczOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(wysylaj==false)
{
wysylaj = true;
}
else
{
wysylaj = false;
}
}};
//throttle button handler
Button.OnTouchListener gazOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("1");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//brake button handler
Button.OnTouchListener hamulecOnTouchListener
= new Button.OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN) {
gazuje.setText("2");
} else if (event.getAction() == MotionEvent.ACTION_UP) {
gazuje.setText("0");
}
return false;
}};
//sensor handler
public void onSensorChanged(int sensor, float[] values) {
synchronized (this) {
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
wychylenie = values[0] * 10;
tmp = Math.round(wychylenie);
wychylenie = tmp / 10;
if(wychylenie != wychylenietmp)
{
textOut.setText(Float.toString(wychylenie - wspk));
wychylenietmp = wychylenie;
}
}
}
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(log, "onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this, SensorManager.SENSOR_ORIENTATION
| SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
//callibration handler
Button.OnClickListener kalibracjaOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
wspk = wychylenie;
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
// sending steering data
public void Wyslij()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//sending throttle data
public void Gaz()
{
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
numer = adres.getText().toString();
socket = new Socket(numer, 8889);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(gazuje.getText().toString());
if(socket.isClosed())
{
test.setText("Socket zamkniety");
}
//textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
And here's Server code:
//import's...
public class Okno
{
public static float wychylenie;
public static String gaz="0";
public static float jedzie;
public static int skrecam, gazuje;
public static String wiadomosc="100";
private static int maxConnections=0, port=8888, portg=8889;
public static void main(String[] args)
{
skrecam = 0;
gazuje = 0;
Window ok = new Window();
ok.setDefaultCloseOperation(3);
ok.setVisible(true);
ok.setResizable(false);
ok.setTitle("Serwer TCP");
int i=0;
try{
Robot robot = new Robot();
Robot robotgaz = new Robot();
ServerSocket listener = new ServerSocket(port);
ServerSocket listenergaz = new ServerSocket(portg);
while((i++ < maxConnections) || (maxConnections == 0)){
//create thread for steering
if(skrecam == 0)
{
skrecam=1;
doComms conn_c= new doComms(listener);
Thread t = new Thread(conn_c);
t.start();
}
//create thread for throttle
if(gazuje == 0)
{
gazuje=1;
doCommsgaz conn_gaz= new doCommsgaz(listenergaz);
Thread tgaz = new Thread(conn_gaz);
tgaz.start();
}
ok.pole3.setText(wiadomosc);
ok.pole2.setText(gaz);
}
}
catch (AWTException e) {
e.printStackTrace();
}
catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doComms(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.wiadomosc = in.readUTF();
server.close();
Okno.skrecam=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doCommsgaz implements Runnable {
private Socket server;
private ServerSocket listener;
private String line,input;
doCommsgaz(ServerSocket listener) {
this.listener=listener;
}
public void run () {
input="";
try {
Socket server;
server = listener.accept();
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
//PrintStream out = new PrintStream(server.getOutputStream());
Okno.gaz = in.readUTF();
server.close();
Okno.gazuje=0;
} catch (IOException ioe) {
//System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class Window extends JFrame {
private JButton ustaw;
public JTextField pole1;
public JTextField pole2;
public JTextField pole3;
Window()
{
setSize(300,200);
getContentPane().setLayout(new GridLayout(4,1));
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(1));
getContentPane().add(panel1);
pole1 = new JTextField(15);
panel1.add(pole1);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(1));
getContentPane().add(panel2);
pole2 = new JTextField(15);
panel2.add(pole2);
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout(1));
getContentPane().add(panel3);
pole3 = new JTextField(15);
panel3.add(pole3);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(1));
getContentPane().add(panel4);
ustaw = new JButton("Ustaw");
panel4.add(ustaw);
//action button handler
ustaw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent zdarz){
try{
}
catch(Exception wyjatek){}
pole1.setText("costam");
}
});
}
}
Once again, sorry for the non optimized, and hard-to-read code. But please, if someone knows what would be better, please respond.
Thanks a lot!
The client socket code should go into an AsyncTask. Google has a good into to it here. This will not speed anything up but it will stop your app from freezing. You can put in a "Processing" message while displaying a progress dialog to let the user know that something is happening.