I have a multiline textview need to show the status of the server. So it should always add a new line when server status changes. However, When I use mTextview.Text=string.Format("connected\n"); or mTextview.SetText("...") The new line doesn't show up immediatelly but show when all the processes are finished. Can anyone help me change it into a automatically show TextView? THX
logTextView.Text = string.Format ("Client log:\n");
.......
logTextView.Text=string.Format("Socket connected to 172.27.27.1\n");
.......
logTextView.Text = logTextView.Text+string.Format ("Start send image to server\n");
.......
you should use:
YourTextView.setText("Connected\n");
and to add multiple lines use:
YourTextView.append("another line\n");
Create a new thread with that log process and immediately invoke it after some events occur.
For example:
class LogProcess implements Runnable {
private String message;
private TextView textView;
public LogProcess(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
#Override
public void run() {
textView.append(message);
}
}
And then invoke it:
Thread logProcess = new Thread(new LogProcess(logTextView, message));
logProcess .start();
Related
I've written a small Spring Boot/Vaadin application that displays a simple UI to take user input and make a call to another service that takes some time to run. When the task is submitted, I'm displaying a progress dialog that shows a progress bar, a message informing the user what is going on and a close button to allow them to close the dialog when the job completes. I'm using a ListenableFuture to be notified when the task is done.
I can get the dialog to appear with status of "executing" and the progress bar doing its thing, but when the task is done (I have debug statements going to the console to let me know), it's not triggering the logic to update the status message and enable the close button. I can't figure out what I'm doing wrong.
Here's the code:
MainView1.java
#Route("rescheduleWorkOrders1")
#CssImport("./styles/shared-styles.css")
public class MainView1 extends VerticalLayout {
...
private final BackendService service;
public MainView1(BackendService service) {
this.service = service;
configureView();
addSubmitButton();
bindFields();
}
private void addSubmitButton() {
Button submit = new Button("Submit", this::submit);
add(submit);
}
private void submit(ClickEvent<?> event) {
UserData data = binder.getBean();
ListenableFuture<ResponseEntity<String>> future = service.executeTask(data);
ProgressDialog dialog = new ProgressDialog(future);
dialog.open();
}
private void configureView() {
...
}
private void bindFields() {
...
}
}
ProgressDialog.java
public class ProgressDialog extends Dialog {
private final ListenableFuture<ResponseEntity<String>> future;
private ProgressBar bar;
private Paragraph message;
private Button close;
public ProgressDialog(ListenableFuture<ResponseEntity<String>> future) {
super();
this.future = future;
configureView();
this.future.addCallback(new ListenableFutureCallback<>() {
#Override
public void onSuccess(ResponseEntity<String> result) {
message.setText("Task complete. Status: " + result.getStatusCode());
bar.setVisible(false);
close.setEnabled(true);
}
#Override
public void onFailure(Throwable ex) {
message.setText(ex.getMessage());
bar.setVisible(false);
close.setEnabled(true);
}
});
}
private void configureView() {
bar = new ProgressBar();
bar.setIndeterminate(true);
bar.setVisible(true);
message = new Paragraph("Executing task ...");
close = new Button("Close", this::close);
close.setEnabled(false);
add(bar, message, close);
}
private void close(ClickEvent<?> event) {
this.close();
}
}
BackendService.java
#Service
public class BackendService {
#Async
public ListenableFuture<ResponseEntity<String>> executeTask(UserData data) {
...
RestTemplate template = new RestTemplate();
ResponseEntity<String> response = template.postForEntity(uri, entity, String.class);
System.out.println(response);
return AsyncResult.forValue(response);
}
}
Note: I do have #EnableAsync specified in a #Configuration annotated class.
When dealing with asynchronous code in Vaadin you need to:
Use UI#access when updating the UI outside an active request. This acquires a lock on the UI, to prevent it being updated by two threads simultaneously.
Enable server push by adding the #Push annotation to your main layout or view. This allows the server to push updates to the client even if no request is active.
Without the former, you can get ConcurrentModificationExceptions in the best case, and very subtle bugs in the worst.
Without the latter, the changes will be applied (i.e. dialog closed), but the changes will only be sent to the client the next time the client sends a request. I believe this is your main issue.
More information can be found in the documentation.
I have been stuck with one problem. I need some people which check a part of my code and help me with problem and critize my code (I write code but I haven't people which can say this is wrong or something in this pattern)
Generally.
My service get message from bluetooth (HC-05) and I can see values in Log.d, in service.
A part code of my service which get message.
private class ConnectedThread extends Thread{
private final BluetoothSocket bluetoothSocket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket){
Log.d(TAG,"ConnectedThread: Starting");
bluetoothSocket=socket;
InputStream tmpInput = null;
OutputStream tmpOutput = null;
try{
tmpInput = bluetoothSocket.getInputStream();
tmpOutput = bluetoothSocket.getOutputStream();
}catch (IOException e){
e.printStackTrace();
active=false;
}
inputStream=tmpInput;
outputStream=tmpOutput;
}
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(active){
try {
bytes = inputStream.read(buffer);
final String comingMsg = new String(buffer,0,bytes);
Log.d(TAG,"InputStream: " + comingMsg);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Message message = new Message();
message.obj = comingMsg;
message.what = 1; // I need it to prevent NullObjReference
Log.d(TAG,"Handler run(): " + message.obj);
mHandler.sendMessage(message);
}
});
}catch (IOException e){
Log.e(TAG,"Write: Error reading input." + e.getMessage());
active=false;
break;
}
}
}
...some code is hidden because it is diploma thesis
}
The problem is get message every time from this service to another activity where all is happen.
I tried a lot of things (with Threads,Looper,runOnUiThread, handleMessage and callback), checked a lot of posts in stackoverflow and I tried to combine with my project but all time I had nullobjectreference (for that i tried to use msg.what to check) , black screen when tried to move to my home activity (it is main) and update my textView or typical crash app.
Now I want only to get message from service to textview. When everything starts working fine, I want to parse string (for example 3 first chars) and send message to one of six textviews.
A part of codes from onCreate before method runThread() is started:
Log.d(TAG,"Check intent - result");
if(getIntent().getIntExtra("result",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded device");
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service ");
checkIfActive();;
}
Log.d(TAG,"Check intent - connect_to_paired");
if(getIntent().getIntExtra("connect_to_paired",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded_paired_device");
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service ");
checkIfActive();
}
public void checkIfActive(){
Log.d(TAG,"CheckIfActive: Started");
while(myBluetoothService.active!=true) {
Log.d(TAG,"CheckIfActive() active is "+ myBluetoothService.active);
if (myBluetoothService.active) {
Log.d(TAG, "CheckIfActive: Running method runOnUiThread - myBluetoothService.active is "+myBluetoothService.active);
runThread();
}
}
}
Method runThread() which should work everytime after connected with bluetooth device:
public void runThread(){
//I used there Thread but when connection was fail,
// method created multiply threads when I tried to connect next time
runOnUiThread(new Runnable() {
#Override
public void run() {
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg) {
while (true) {
switch (msg.what) {
//when is one, service has messages to send
case 1:
String message = myBluetoothService.mHandler.obtainMessage().toString();
rearLeft.setText(message);
break;
default:
super.handleMessage(msg);
}
}
}
};
}
});
}
UPDATE:
Is it good idea ? Maybe I can put JSON Object to service to send message and in the HomeActivity, I can try get values from JSON. Is it fast ? I send a lot of data, because bluetooth receive data of distance from 4 ultrasound sensors in 4 times in lasts until few milliseconds, everytime.
Here is screen how sees my data in service when I have debug logs.
Next idea, but still nothing:
HomeActivity (my main)
public void runThread(){
runOnUiThread(new Runnable() {
#Override
public void run() {
//Looper.prepare();
new Handler() {
#Override
public void handleMessage(Message msg) {
rearLeft.setText(msg.obj.toString());
}
};
//Looper.loop();
//Log.d(TAG, myBluetoothService.mHandler.getLooper().toString());
//rearLeft.setText(myBluetoothService.mHandler.getLooper().toString());
}
});
}
Service which should send data from bluetooth to UI Thread is the same (Check first code).
Screen from HomeActivity where you can see 6 text views. Now I want put all text to one view which will be refresh by get next message.
Ok this post a bit help me to solve problem:
Sending a simple message from Service to Activity
Maybe this link could help another people.
Thanks for help, now understand why i should use broadcast receiver to do this.
OK so I have the uploader uploading files using the Java FTP, I would like to update the label and the progress bar. Label with the percent text, bar with the percent int value. Right now with the current code only get the 100 and full bar at the end of the upload. During the upload none of them change.
here it is:
OutputStream output = new BufferedOutputStream(ftpOut);
CopyStreamListener listener = new CopyStreamListener() {
public void bytesTransferred(long totalBytesTransferred, int bytesTransferred, long streamSize) {
System.out.printf("\r%-30S: %d / %d", "Sent", totalBytesTransferred, streamSize);
ftpup.this.upd(totalBytesTransferred,streamSize);
}
public void bytesTransferred(CopyStreamEvent arg0) { }
};
Util.copyStream(input, output, ftp.getBufferSize(), f.length(), listener);
}
public void upd(long num, long size){
int k = (int) ((num*100)/size);
System.out.println(String.valueOf(k));
this.d.setText(String.valueOf(k));
//d.setText(String.valueOf(k));
progressBar.setValue(k);
}
From the sounds of it (and lacking any evidence to the contree) it sounds like your processing a time consuming action in the Event Dispatching Thread
You might like to read Concurrency in Swing for some further insight
I'd suggest using a SwingWorker to perform the actual transfer & take advantage of its built in progress support
UPDATE after seeing source code
Don't mix heavy weight components with light weight components. Change Applet to JApplet, change TextField to JTextField, don't use Canvas use a JPanel or JComponent
If you expect other people to read your code, please use proper names for your variables, I have no idea what p is.
Your Thread is useless. Rather then starting the thread and using it's run method you simply make your download call within it's constructor. This will do nothing for you...
Remove your implementation of MyThread and replace it with
public class MyWorker extends SwingWorker<Object, Object> {
private URL host;
private File outputFile;
public MyWorker(URL host, File f) {
this.host = host;
outputFile = f;
}
#Override
protected Object doInBackground() throws Exception {
// You're ignoring the host you past in to the constructor
String hostName = "localhost";
String username = "un";
String password = "pass";
String location = f.toString();
//FTPClient ftp = null;
ftp.connect(hostName, 2121);
ftp.login(username, password);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.setKeepAlive(true);
ftp.setControlKeepAliveTimeout(3000);
ftp.setDataTimeout(3000); // 100 minutes
ftp.setConnectTimeout(3000); // 100 minutes
ftp.changeWorkingDirectory("/SSL");
int reply = ftp.getReplyCode();
System.out.println("Received Reply from FTP Connection:" + reply);
if (FTPReply.isPositiveCompletion(reply)) {
System.out.println("Connected Success");
}
System.out.println(f.getName().toString());
File f1 = new File(location);
in = new FileInputStream(f1);
FileInputStream input = new FileInputStream(f1);
// ftp.storeFile(f.getName().toString(),in);
//ProgressMonitorInputStream is= new ProgressMonitorInputStream(getParent(), "st", in);
OutputStream ftpOut = ftp.storeFileStream(f.getName().toString());
System.out.println(ftpOut.toString());
//newname hereSystem.out.println(ftp.remoteRetrieve(f.toString()));
OutputStream output = new BufferedOutputStream(ftpOut);
CopyStreamListener listener = new CopyStreamListener() {
public void bytesTransferred(final long totalBytesTransferred, final int bytesTransferred, final long streamSize) {
setProgress((int) Math.round(((double) totalBytesTransferred / (double) streamSize) * 100d));
}
#Override
public void bytesTransferred(CopyStreamEvent arg0) {
// TODO Auto-generated method stub
}
};
Util.copyStream(input, output, ftp.getBufferSize(), f.length(), listener);
return null;
}
}
In your ActionListener of o (??) replace the thread execution code with
try {
MyWorker worker = new MyWorker(new URL("http://localhost"), file);
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("progress")) {
Integer progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
}
}
});
worker.execute();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
Note. You are ignoring the URL you pass to the constructor. http:// is not ftp:// so I doubt this will work...
During the upload you don't see changes to the GUI, because you run the upload and the GUI changes in the same thread.
You should start one threayd that does the upload and another one in EDT (Event-Dispatch-Thread) that does the GUI updates.
For more info see:
The Event Dispatch Thread
You should implement the transfer logic in a SwingWorker, that way the UI will have the chance to present the progress.
I'm having trouble figuring out how to make this work.
I'm developing an app in which I download data from a online txt, parse it and add it to my database. This is taking +-30 seconds, and there is only one part of the updater implemented.
When I try to use a Thread or Asynctask, I have problems when trying to pass the arguments to the void which is updating the Database.
How can I implement it on the good way?
Here is my code:
Main activity class:
public class Androideye_principal extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
//WhazzupUpdate.DownloadWhazzup(AllUsers, TotalConnections);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_androideye_principal);
PilotsSQLiteHelper pdbh = new PilotsSQLiteHelper(this, "PilotsDB", null, 1);
SQLiteDatabase dbPilots = pdbh.getWritableDatabase();
Context context = getApplicationContext();
String TotalConnections = new String();
WhazzupUpdate.DownloadWhazzup(dbPilots, TotalConnections, context);
dbPilots.close();
CharSequence text = "Total Users: " + TotalConnections;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
[Continues with Buttons stuff and so on...]
Parser class:
public class WhazzupUpdate {
public static void DownloadWhazzup (SQLiteDatabase PilotsDB, String TotalConnections, Context context) {
try {
// Create a URL for the desired page
URL url = new URL("This is my url/whazzup.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
for (int i = 0; i<=4; i++) {
in.readLine(); } // Go to the number of connections
TotalConnections = in.readLine();
for (int i = 0; i<=3; i++) {
in.readLine(); } // Go to !CLIENTS
PilotsDB.execSQL("DELETE FROM Pilots");
while (((str = in.readLine()) != null) && !(in.readLine().contains("!AIRPORTS"))) {
// str is one line of text; readLine() strips the newline character(s)
String[] dataRow = str.split(":");
if (str.contains("PILOT")) {
ContentValues NewValue = new ContentValues();
NewValue.put("VID", dataRow[1]);
[More NewValue puts...]
PilotsDB.insert("Pilots", null, NewValue);
} //End IF Pilot
} // End While
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}}
As you see, I call WhazzupUpdate.DownloadWhazzup Method in the main activity, and this is when all is getting frozen, but don't know how to derivate it to another threat and keep the references to the Data Bases and so on...
Hope anyone can help me. Thanks in advance.
A Thread or AsyncTask would be fine here. I prefer using AsyncTask for most of my heavy-lifting. You can create an AsyncTask and do your work in doInBackground() as it works on a background Thread. Then you can update your UI elements if needed in any of its other methods.
onPostExecute() will run after a result is passed from doInBackground()
onProgressUpdate() will run if you need to update UI during doInBackground() operations by calling publishProgress(). Here you can show a ProgressBar if you need to
and
onPreExecute() will run when you first call your task before doInBackground() runs.
Running the code in a background thread using Thread or AsyncTask will allow your UI to be free while the heavy work is being done.
Example of AsyncTask
Using interface with AsyncTask to post data back yo UI
AsyncTask Docs
I have this AsyncTask which I use to send a chat message over the internet. The problem is that when I execute the task nothing happens - at least not on the UI. I suspect that onProgressUpdate() does not execute at all. The idea is that when the task is started, a message will be sent over the internet and an EditText on the UI will be updated with the new text. Here is the whole class:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import android.os.AsyncTask;
import android.widget.EditText;
public class Messager extends AsyncTask<SocketAndEditText, Void, Void> {
private MulticastSocket socket;
private EditText host;
private EditText port;
private EditText sendMessage;
private EditText messageBoard;
private InetAddress serverAddress;
private int pt;
private String newConverstion;
private String message;
#Override
protected Void doInBackground(SocketAndEditText... soEd) {
// get the text that they contain and add the new messages to the old ones
//host = soEd[0].getHost();
//port = soEd[0].getPort();
messageBoard = soEd[0].getMessageBoard();
sendMessage = soEd[0].getSendMessage();
message = sendMessage.getText().toString();
String conversation = messageBoard.getText().toString();
newConverstion = conversation.concat("\n[You] ").concat(message);
return null;
}
protected void onProgressUpdate(Integer... progress) {
// make the messages text view editable
messageBoard.setFocusable(true);
messageBoard.setText(newConverstion); // add the new message to the text view
messageBoard.setFocusable(false); // make the messages text view not editable
// erase the text on the second text view that has just been sent
sendMessage.setText("");
sendMessage(message);
}
public void sendMessage(String message) {
// convert the host name to InetAddress
try {
serverAddress = InetAddress.getByName("localhost");
} catch (Exception e) {}
pt = 4456;
// create socket and start communicating
try {
socket = new MulticastSocket(pt);
socket.joinGroup(serverAddress);
} catch (IOException e) {}
// Send message to server
// convert message to bytes array
byte[] data = (message).getBytes();
// create and send a datagram
DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, pt);
try {
socket.send(packet);
} catch (IOException e) {}
}
}
What could be wrong?
The onProgressUpdate() won't be called if you don't call publishProgress() yourself. See the 4 steps of AsyncTask.
As Boris pointed out. You should call sendMessage() in doInBackground() and update UI in onPostExecute().
onProgressUpdate should be invoked explicitly from within doInBackground as seen here. It is not the correct method to use in your case. I would rather expect that the setting of the text field should be done in onPostExecute. Reason being that the value of newConverstion is determined just after the remote call and it might take a while to complete. If you do it before the asynctask has finished execution you risk NPE.
Edit Adding some code:
public class Messager extends AsyncTask<SocketAndEditText, Void, Void> {
//skipping some field declaration
#Override
protected Void doInBackground(SocketAndEditText... soEd) {
// get the text that they contain and add the new messages to the old ones
//host = soEd[0].getHost();
//port = soEd[0].getPort();
messageBoard = soEd[0].getMessageBoard();
sendMessage = soEd[0].getSendMessage();
message = sendMessage.getText().toString();
sendMessage(message); //NOTE: added the remote call in the background method. This is the only thing that really SHOULD be done in background.
String conversation = messageBoard.getText().toString();
newConverstion = conversation.concat("\n[You] ").concat(message);
return null;
}
protected void onPostExecute(Void result) {
// make the messages text view editable
messageBoard.setFocusable(true);
messageBoard.setText(newConverstion); // add the new message to the text view
messageBoard.setFocusable(false); // make the messages text view not editable
// erase the text on the second text view that has just been sent
sendMessage.setText("");
}
Basically the most important thing is to place the most time consuming calls in the background of the task. In your case this is sendMessage. From then on you can do whatever fixes you wish in the postExecute and the preExecute. I am not quite sure what your intention for the onProgressUpdate was. Holever I just translated it to using onPostExecute. If you need to temporarily disable the field you can disable it in onPreExecute and enable it onPostExecute.