Progress Indicator In a Table Cell - javafx-8

I have a table column which i added through Scene Builder, and with java code i made it editable like so
colSellingPrice.setCellFactory(TextFieldTableCell.<Sale, Float>forTableColumn(new FloatStringConverter()));
The problem is during updating the value in this tablecell, alot of calculations and many insertion and fetching is made which takes time to complete. Though i decided to put the update logic in a Task, i would also like to display a progress indicator in the tablecell UI while the logic is happenning.
This is what i have so far
colSellingPrice.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Sale, Float>>() {
#Override
public void handle(TableColumn.CellEditEvent<Sale, Float> t) {
Task task = new Task<Void>(){
private SaleTransaction st;
#Override
protected Void call() throws Exception {
Sale s = t.getRowValue();
// Logic, logic , logic
return null;
}
#Override
protected void succeeded() {
System.out.println("Price Updated.");
}
};
executor.submit(task);
}
});

Related

Room and RxJava Providing Inconsistent Results

This is my first time working with Room and RxJava. I'm getting some very inconsistent results when I'm reading from the DB. I have a nested RecyclerView, where the first simply shows the days of the week and the second shows the forecast for each day.
Sometimes when I launch the app, everything shows up right away. Other times, only the days will be shown, but not the forecast for each day. Other times, neither RecyclerViews are shown. However, if I view the DB using Stetho, the data is there within the device.
Here's how I've setup my Dao:
#Dao
public interface MyDao {
// Other CRUD methods
#Query("SELECT DISTINCT date FROM my_table")
Single<List<LocalDate>> getUniqueDays();
#Query("SELECT * FROM my_table WHERE date == :localDate")
Single<List<Forecasts>> getForecastForDay(LocalDate localDate);
}
I populate the first RecyclerView using the following:
Single<List<LocalDate>> source = MyApp.getDatabase().getDao().getUniqueDays();
source.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<LocalDate>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(List<LocalDate> localDates) {
mAdapter.refreshData(localDates);
}
#Override
public void onError(Throwable e) {
}
});
This is called within a fragment that displays the days of the week.
Then, within the adapter for the days of the week, I also need to populate the inner RecyclerView, which is done within my bind() of the ViewHolder:
public void bind(LocalDate date, int position){
// A bunch of other views being set
mHourlyForecasts.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
mHourlyForecasts.setLayoutManager(layoutManager);
mAdapter = new HourlyForecastAdapter(mContext);
mHourlyForecasts.setAdapter(mAdapter);
Single<List<Forecasts>> source = MyApp.getDatabase().getDao().getForecastForDay(date);
source.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<Forecasts>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onSuccess(List<Forecasts> conditions) {
Timber.i("Size of conditions in onSuccess(): %d", conditions.size());
mAdapter.refreshData(conditions);
}
#Override
public void onError(Throwable e) {
}
});
}
However, I have no idea as to why the data isn't being shown consistently. Sometimes at startup the data isn't shown, sometimes it is. Sometimes I'll close out the app and re-open it and some data is missing. Or all of it is there. And again, the data is there in the DB when I inspect the device in Stetho, it's just not being shown within the RecyclerView(s).
If anyone can provide some guidance on this, it would be immensely appreciated...

Catch closing event of a part (Eclipse e4 RCP)

I'm currently working on a eclipse e4 RCP application and I have a part that serves as a job manager where the user can see all active jobs and their progresses, like one in eclipse. The problem is now that the user can open the progress part by double clicking in the toolbar and he should also be able to close the progress part whenever he wants, but instead of disposing the part I want to just make it invisible.
I thought at first this shouldn't be a problem because I can set the part to be not visible, but the problem is how to catch the closing event and process it by my way. Is there any event, interfaces or listeners I can implement to catch the closing event and prevent the part from getting disposed?
You can implement a CustomSaveHandler and replace the Default Eclipse Save Handler with a Processor. In that SaveHandler you can control if the Part shoud get closed or not. So you could do not close it and make it invisible.
ExampleCode:
public class ReplaceSaveHandlerProcessor {
#Named("your.id.to.window")
#Inject
MWindow window;
#Inject
IEventBroker eventBroker;
#Execute
void installIntoContext() {
eventBroker.subscribe(UIEvents.Context.TOPIC_CONTEXT, new EventHandler() {
#Override
public void handleEvent(final Event event) {
if (UIEvents.isSET(event)) {
if (window.equals(event.getProperty("ChangedElement")) && (window.getContext() != null)) {
window.getContext().runAndTrack(new RunAndTrack() {
private final ISaveHandler saveHandler = new CustomSaveHandler();
#Override
public boolean changed(final IEclipseContext context) {
Object getSaveHandlerValue = context.get(ISaveHandler.class);
if (!saveHandler.equals(getSaveHandlerValue)) { // prevents endless loop
ContextInjectionFactory.inject(saveHandler, window.getContext());
context.set(ISaveHandler.class, saveHandler);
}
return true; // ture keeps tracking and the saveHandler as the only opportunity
}
});
}
}
}
});
}
}
You have to define a Extention for ExtentionPoint org.eclipse.e4.workbench.model
With Your ReplaceSaveHandlerProcessor. (You have to declare the window id as "element" in this extention. (Added Screenshot: )
The CustomSaveHandler have to implement the ISaveHandler interface. In its Methods ypu can say if the Part should realy be closed.
public class CustomSaveHandler implements ISaveHandler {
#Override
public boolean save(MPart dirtyPart, boolean confirm) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean saveParts(Collection<MPart> dirtyParts, boolean confirm) {
// TODO Auto-generated method stub
return false;
}
#Override
public Save promptToSave(MPart dirtyPart) {
// TODO Auto-generated method stub
return null;
}
#Override
public Save[] promptToSave(Collection<MPart> dirtyParts) {
// TODO Auto-generated method stub
return null;
}
}

JavaFX8 TreeTableView notifications for scrolled items

I am writing an application that is using a JavaFX8 TreeTableView. The tree table has three columns, two of which are String properties (name and value) and one which has a Canvas widget in it that draws a picture from from data from a database (waveforms). There is also a control on the application that allows the display (of all of the drawings) to be zoomed out or in (or for that matter scrolled left and right).
The name and value columns use StringProperty values from my data model so there are CellValueFactory set for those columns. The drawing column uses both a CellFactory and CellValueFactory like this:
// Waveform column
TreeTableColumn<DrawRow, WaveformTraceBox> waveColumn = new TreeTableColumn<>();
waveColumn.setCellFactory(new Callback<TreeTableColumn<DrawRow, WaveformTraceBox>, TreeTableCell<DrawRow, WaveformTraceBox>>() {
#Override
public TreeTableCell<DrawRow, WaveformTraceBox> call(TreeTableColumn<DrawRow, WaveformTraceBox> param) {
return new WaveformTraceBoxTreeTableViewCell<>();
}
});
waveColumn.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<DrawRow, WaveformTraceBox>, ObservableValue<WaveformTraceBox>>() {
#Override
public ObservableValue<WaveformTraceBox> call(TreeTableColumn.CellDataFeatures<DrawRow, WaveformTraceBox> param) {
return new ReadOnlyObjectWrapper<>(new WaveformTraceBox());
}
});
Where WaveformTraceBoxTreeTableViewCell is:
protected static class WaveformTraceBoxTreeTableViewCell<T> extends TreeTableCell<DrawRow, T> {
public WaveformTraceBoxTreeTableViewCell() {
super();
}
#Override
protected void updateItem(T value, boolean empty) {
super.updateItem(value, empty);
setText(null);
setGraphic(null);
if (!empty && getTreeTableRow().getItem() != null) {
getTreeTableRow().getItem().setTraceBox((WaveformTraceBox)value);
setGraphic((WaveformTraceBox) value);
}
}
DrawRow is my data model. When the user zooms out or in via the controls on the window the draw row model will notify it's associated Canvas drawing item to re-draw its display. The drawing of the display can take some time to do because of the large amount of data that needs to be processed to generate the display.
Now my problem: As the TreeTableView widget is scrolled it will ask for new Canvas widgets -- which get associated with DrawRow items from the data model. However widgets from the list that get scrolled off the screen will get thrown away by the tree widget.
I have found no way to tell if the item I am working with has been thrown away or is not being used any more. So the code is doing much more work than it needs to because it is trying to draw cells that are no longer being used or shown. Eventually this will cause other problems because of garbage collection I think.
So my real question is how can I tell if a cell has been abandoned by the tree table so I can stop trying to update it? Any help with this would greatly be appreciated. I am not able to find this anywhere on the various web searches I have done.
Do you need to worry here? What is still "drawing cells that are no longer being used"? Are you running some kind of update in a background thread on the WaveformTraceBox?
In any event, you've structured this pretty strangely.
First, (less important) why is your WaveformTraceBoxTreeTableViewCell generic? Surely you want
protected static class WaveformTraceBoxTreeTableViewCell extends TreeTableCell<DrawRow, WaveformTraceBox>
and then you can replace T with WaveformTraceBox throughout and get rid of the casts, etc.
Second: if I understand this correctly, WaveformTraceBox is a custom Node subclass of some kind; i.e. it's a UI component. The cell value factory shouldn't really return a UI component - it should return the data to display. The cell factory should then use some UI component to display the data.
That way, you can create a single WaveFormTraceBox in the cell implementation, and update the data it displays in the updateItem(...) method.
So something like:
// Waveform column
TreeTableColumn<DrawRow, WaveformData> waveColumn = new TreeTableColumn<>();
waveColumn.setCellFactory(new Callback<TreeTableColumn<DrawRow, WaveformData>, TreeTableCell<DrawRow, WaveformData>>() {
#Override
public TreeTableCell<DrawRow, WaveformData> call(TreeTableColumn<DrawRow, WaveformData> param) {
return new WaveformTraceBoxTreeTableViewCell();
}
});
waveColumn.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<DrawRow, WaveformData>, ObservableValue<WaveformData>>() {
#Override
public ObservableValue<WaveformTraceBox> call(TreeTableColumn.CellDataFeatures<DrawRow, WaveformTraceBox> param) {
return new ReadOnlyObjectWrapper<>(getDataToDisplayForItem(param.getValue()));
}
});
protected static class WaveformTraceBoxTreeTableViewCell extends TreeTableCell<DrawRow, WaveFormData> {
private WaveformTraceBox traceBox = new WaveformTraceBox();
public WaveformTraceBoxTreeTableViewCell() {
super();
}
#Override
protected void updateItem(WaveFormData value, boolean empty) {
super.updateItem(value, empty);
setText(null);
setGraphic(null);
if (!empty && getTreeTableRow().getItem() != null) {
traceBox.setData(value);
setGraphic(traceBox);
} else {
setGraphic(null);
}
}
}
Obviously you need to define the WaveFormData class to encapsulate the data your WaveFormTraceBox will display, and give the WaveFormTraceBox a setData(WaveFormData) method. If you are using any resources that need to be cleaned up, the invocation of setData(...) will indicate that the previous data is no longer being accessed by that WaveformTraceBox.

Update ListView Textview vom Asyntask

i need to update a textView from my asynctask. I have an custom adapter for the listview and there i want to have a countdown for each entry. I will start the asynctask for each entry from my Adapter. How can i update the textview each second from the asynctask?
Thanks for help :)
If you post your code, I can give you a better answer. However, a common way to update views periodically is by using Handlers.
private final Handler mHandler = new Handler(); //intialize in main thread
public void test() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mTextView.setText("hello");
}
}, 1000);
}
You can do something like this (this will add an entry to a list view every one second). I have used the normal ArrayAdapter to add a string. You can use your custom adapter to do something similar. The publishProgress() method basically triggers the onProgressUpdate() method which hooks to the UI thread and displays the elements getting added.:
class AddStringTask extends AsyncTask {
#Override
protected Void doInBackground(Void... params) {
for(String item : items) {
publishProgress(item);
SystemClock.sleep(1000);
}
return null;
}
#Override
protected void onProgressUpdate(String... item) {
adapter.add(item[0]);
}
#Override
protected void onPostExecute(Void unused) {
Toast.makeText(getActivity(), "Done adding string item", Toast.LENGTH_SHORT).show();
}
}

How can I correctly update a progress bar for an operation of unknown duration within an Eclipse wizard?

I have implemented a wizard for my Eclipse plug-in, showing several pages. One of these pages needs some lengthy initialization, that means it consists of a SWT table, which needs to be populated by information coming from an external source. This source needs to be activated first (one single method call that returns after a couple of seconds - I can not know in advance how long it will take exactly), before it can be used as input for for the table viewer. This initialization is currently done by the table model provider when it needs to access the external source for the first time.
Therefore, when I enter the wizard page, I would like to show a dummy progress bar that just counts up for a while. My approach was the following, but unfortunately does not work at all:
private void initViewer() {
IRunnableWithProgress runnable = new IRunnableWithProgress() { // needed to embed long running operation into the wizard page
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
SubMonitor progress = SubMonitor.convert(monitor);
Thread thread = new Thread() {
#Override
public void run() {
Display.getDefault().syncExec(new Runnable() {
public void run() {
viewer.setInput(ResourcesPlugin.getWorkspace().getRoot()); // this will make the table provider initialize the external source.
}
});
}
};
thread.start();
while(thread.isAlive()) {
progress.setWorkRemaining(10000);
progress.worked(1);
}
progress.done();
}
};
try {
getContainer().run(false, false, runnable);
} catch(Exception e) {
throw new Exception("Could not access data store", e);
}
}
This method gets then invoked when the wizard page's setVisible()-method is called and should, after a couple of seconds, set the viewer's input. This, however, never happens, because the inner-most run()-method never gets executed.
Any hints on how to deal with long-running (where an exact estimate is not available) initializations in Eclipse wizards would be very appreciated!
I have given below a simple example on how to use IRunnableWithProgress along with a ProgressMonitorDialog to perform a task of unknown quantity. To start with, have an implementation to IRunnableWithProgress from where the actual task is performed. This implementation could be an inner class.
public class MyRunnableWithProgress implements IRunnableWithProgress {
private String _fileName;
public MyRunnableWithProgress(String fileName) {
_fileName = fileName;
}
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
int totalUnitsOfWork = IProgressMonitor.UNKNOWN;
monitor.beginTask("Performing read. Please wait...", totalUnitsOfWork);
performRead(_fileName, monitor); // This only performs the tasks
monitor.done();
}
}
Now, a generic implementation to ProgressMonitorDialog can be created as below which could be used for other places where a progress monitor dialog is required.
public class MyProgressMonitorDialog extends ProgressMonitorDialog {
private boolean cancellable;
public MyProgressMonitorDialog(Shell parent, boolean cancellable) {
super(parent);
this.cancellable = cancellable;
}
#Override
public Composite createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
setCancelable(cancellable);
return container;
}
}
Having got the required implementation, the task can be invoked as below to get it processed with a progress dialog.
boolean cancellable = false;
IRunnableWithProgress myRunnable = new MyRunnableWithProgress(receivedFileName);
ProgressMonitorDialog progressMonitorDialog = new MyProgressMonitorDialog(getShell(), cancellable);
try {
progressMonitorDialog.run(true, true, myRunnable);
} catch (InvocationTargetException e) {
// Catch in your best way
throw new RuntimeException(e);
} catch (InterruptedException e) {
//Catch in your best way
Thread.currentThread().interrupt();
}
Hope this helps!
I assume the reason why it's "not working" for you is that the preparation of input is done in UI thread meaning that the progress bar cannot be updated. A better approach is to prepare input in advance and only set input to viewer after that.