Why can not update autocomplete suggestions? - codenameone

I am using two AutocompleteTextFilters as depended filters. I want the second one filter to change its options depending on the suggestion of the first filter.
I have bind an event listener on the first filter so as when it loose focus it triggers a proccess on the second filter.
The proble is that the second filter never changes its options. I even have setup hardcoded values in case somethig was wrong on my code but no luck.
The code I use is below:
public CreateSubmission(com.codename1.ui.util.Resources resourceObjectInstance, Map<String, ProjectType> projectTypes) {
this.projectTypes = projectTypes;
initGuiBuilderComponents(resourceObjectInstance);
gui_ac_projecttype.clear();
gui_ac_projecttype.setCompletion( this.projectTypes.keySet().toArray( new String[0]) );
gui_ac_projecttype.addFocusListener( new ProjectTypeFocusListener( this ));
gui_ac_steps.setCompletion( new String[]{"t10", "t20"});
}
public void makeSteps (String selection) {
ProjectType projectType = this.projectTypes.get( selection );
if (projectType != null) {
this.selectedProjectType = selection;
int length = projectType.projectSteps.length;
String[] steps = new String[ length ];
for(int i =0; i < length; i ++) {
steps[i] = projectType.projectSteps[i].projectStep;
}
// String[] s = gui_ac_steps.getCompletion();
gui_ac_steps.setCompletion( new String[]{"t1", "t2"} );
gui_ac_steps.repaint();
}
else {
}
}
public class ProjectTypeFocusListener implements FocusListener{
private CreateSubmission parent;
public ProjectTypeFocusListener( CreateSubmission parent ) {
this.parent = parent;
}
#Override
public void focusGained(Component cmp) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void focusLost(Component cmp) {
this.parent.makeSteps (
((AutoCompleteTextField)cmp).getText()
);
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
On the above code the initialization happens on "public CreateSubmission" method.
"gui_ac_projecttype" is the first AutocompletionTextField that triggers the whole proccess through it's FocusListener handler (class ProjectTypeFocusListener )
"gui_ac_steps" is the second AutocompleteTextField filter that must change its values. On the code above I initialize it's suggestions to "t10", "t20". Those two values are shown correctly.
Later from iside the FoculListenerHandler's method "ProjectTypeFocusListener.focusLost" I call method "makeSteps" which sets the suggestion options to "t1", "t2 and then I repaint the component. These two last values are never shown. It remains on the first values "t10", "t20".
The Strange thing is that in debugger when I ask gui_ac_steps.getCompletion(); to see the current options ( the code that is commentd out into makeSteps method) I get the correct values "t1", "t2".
But on the screen it keeps showing "t10", "t20".
any help is aprreciated.

You shouldn't do anything "important" in a focus listener. Especially not with a text field. They are somewhat unreliable because the text field switches to native editing and in effect transfers the focus there. The problem is that some events are delayed due to the back and forth with the native editing so by the time the focus event is received you've moved on to the next field.
Try something like this for this specific use case https://www.codenameone.com/blog/dynamic-autocomplete.html

Related

in flink processFunction, all mapstate is empty in onTimer() function

I want implements the aggregationFunction by the processKeyedFunction, because the default aggregationFunction does not support rich function,
Besides, I tryed the aggreagationFunction + processWindowFunction(https://ci.apache.org/projects/flink/flink-docs-stable/dev/stream/operators/windows.html), but it also cannot satisfy my needs, so I have to use the basic processKeyedFunction to implement the aggregationFunction, the detail of my problem is as followed:
in processFunction, , I define a windowState for stage the aggregation value of elements, the code is as followed:
public void open(Configuration parameters) throws Exception {
followCacheMap = FollowSet.getInstance();
windowState = getRuntimeContext().getMapState(windowStateDescriptor);
currentTimer = getRuntimeContext().getState(new ValueStateDescriptor<Long>(
"timer",
Long.class
));
in processElement() function, I use the windowState (which is a MapState initiate in open function) to aggregate the window element, and register the first timeServie to clear current window state, the code is as followed:
#Override
public void processElement(FollowData value, Context ctx, Collector<FollowData> out) throws Exception
{
if ( (currentTimer==null || (currentTimer.value() ==null) || (long)currentTimer.value()==0 ) && value.getClickTime() != null) {
currentTimer.update(value.getClickTime() + interval);
ctx.timerService().registerEventTimeTimer((long)currentTimer.value());
}
windowState = doMyAggregation(value);
}
in onTimer() function, first, I register the next timeService in next One minute, and clear the window State
#Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<FollowData> out) throws Exception {
currentTimer.update(timestamp + interval); // interval is 1 minute
ctx.timerService().registerEventTimeTimer((long)currentTimer.value());
out.collect(windowState);
windowState.clear();
}
but when the program is running , I found that all the windowState in onTimer is empty, but it is not empyt in processElement() function, I don't know why this happens, maybe the execution logic is different, how can I fix this,
Thanks in advance !
new added code about doMyAggregation() part
windowState is a MapState , key is "mykey", value is an self-defined Object AggregateFollow
public class AggregateFollow {
private String clicked;
private String unionid;
private ArrayList allFollows;
private int enterCnt;
private Long clickTime;
}
and the doMyAggregation(value) function is pretty much like this , the function of doMyAggregation is to get all the value whose source field is 'follow', but if there are no values whose field is 'click' during 1 minute, the 'follow' value should be obsolete, in a word , it's like a join operation of 'follow' data and 'click' data,
AggregateFollow acc = windowState.get(windowkey);
String flag = acc.getClicked();
ArrayList<FollowData> followDataList = acc.getAllFollows();
if ("0".equals(flag)) {
if ("follow".equals(value.getSource())) {
followDataList.add(value);
acc.setAllFollows(followDataList);
}
if ("click".equals(value.getSource())) {
String unionid = value.getUnionid();
clickTime = value.getClickTime();
if (followDataList.size() > 0) {
ArrayList listNew = new ArrayList();
for (FollowData followData : followDataList) {
followData.setUnionid(unionid);
followData.setClickTime(clickTime);
followData.setSource("joined_flag"); //
}
acc.setAllFollows(listNew);
}
acc.setClicked("1");
acc.setUnionid(unionid);
acc.setClickTime(clickTime);
windowState.put(windowkey, acc);
}
} else if ("1".equals(flag)) {
if ("follow".equals(value.getSource())) {
value.setUnionid(acc.getUnionid());
value.setClickTime(acc.getClickTime());
value.setSource("joined_flag");
followDataList.add(value);
acc.setAllFollows(followDataList);
windowState.put(windowkey, acc);
}
}
because of performance problem, original windowAPI is not a valid choice for me, the only way here I think is to use processFunction + ontimer and Guava Cache ,
Thanks a lot
If windowState is empty, it would be helpful to see what doMyAggregation(value) is doing.
It's difficult to debug this, or propose good alternatives, without more context, but out.collect(windowState) isn't going to work as intended. What you might want to do instead would be to iterate over this MapState and collect each key/value pair it contains to the output.
I changed the type of windowState from MapState to ValueState, and the problem is solved, maybe it is a bug or something, can anyone can explain this?

CEP - Pattern not executed after adding Window

//Creating a window of ten items
WindowedStream<ObservationEvent,Tuple,GlobalWindow> windowStream = inputStream.keyBy("rackId").countWindow(10);
// Applying a Window Function , adding some custom evaluating all the values in the window
DataStream<ObservationEvent> inactivityStream = windowStream.apply(new WindowFunction<ObservationEvent, ObservationEvent , Tuple , GlobalWindow>() {
#Override
public void apply(Tuple tuple, GlobalWindow timeWindow, Iterable<ObservationEvent> itr, Collector<ObservationEvent> out)
//custom evaluation logic
out.collect(new ObservationEvent(1,"temperature", "stable"));
}
});
//Defining Simple CEP Pattern
Pattern<ObservationEvent, ?> inactivityPattern = Pattern.ObservationEvent>begin("first")
.subtype(ObservationEvent.class)
.where(new FilterFunction<ObservationEvent>() {
#Override
public boolean filter(ObservationEvent arg0) throws Exception {
System.out.println( arg0 ); //This function is not at all called
return false;
}
});
PatternStream<ObservationEvent> inactivityCEP = CEP.pattern(inactivityStream.keyBy("rackId"), inactivityPattern);
When I run this code, the filter function inside the where clause is not at all getting called.
I have printed the inactivityStream.print() and I can see the matching value.
Now, when I plug in the inputStream directly without applying a window. The pattern is matching
I printed inputStream and WindowedStream and I can see they both send similar kind of data.
What am I missing
The FilterFunction should be getting called eventually but you are going to have to wait for 10 events for the SAME key before you see your FilterFunction called for the first time. Could it be that you are just not waiting long enough in your windowing test?
Keep in mind that if you have many unique keys this implies you will have to wait well more than 10 times as long in the window test before you'll see your filter function called.

Codename One : Get the current visible image index from a DefaultListModel included in an ImageViewer

I am building an app that makes use of LayeredLayout to display 2 ImageViewers on top of each other. The deeper ImageViewer contains a captured image (a photo) and the shallower one a decoration that the user can change via swiping.
So the decoration images are stored in an ArrayList like this :
decorationImageList = new ArrayList<Image>();
// On filtre les décorations qu'on ajoute à la liste
for (String png : res.getImageResourceNames()) {
if (png.endsWith("-ratio-4-3.png")) {
decorationImageList.add(res.getImage(png));
}
}
Then in the StateMachine I load them in the decoration ImageViewer like this :
DefaultListModel<Image> decorationModel = new DefaultListModel<Image>(decorationImageList);
findDecorationIV().setImageList(decorationModel);
So far it works as expected, the user can swipe to change the decoration.
However I need to know which decoration has been chosen by the user (ie which decoration is currently visible / shown to the user).
I tried to add listeners to the decoration ImageViewer to count the number and direction of swipes but the listeners did not trigger (in the simulator).
findDecorationIV().addScrollListener(new ScrollListener() {
#Override
public void scrollChanged(int scrollX, int scrollY, int oldscrollX, int oldscrollY) {
System.out.println("There has been some scrolling"); // never triggered
}
});
or
findDecorationIV().addFocusListener(new FocusListener() {
#Override
public void focusLost(Component cmp) {
System.out.println("Focused lost!"); // never triggered
}
#Override
public void focusGained(Component cmp) {
System.out.println("On focus!"); // triggered only once
}
});
Now while reading CN1 doc I tend to think that I should implement ListModel in my own DecorationModel class, since there is a method called getSelectedIndex. Unfortunately I can't understand how this works and why in their example they do always return 0 in the getSelectedIndex method.
Therefore I am really stuck and looking for help in order to be able and get the current visible decoration shown to the user.
Thanks a lot to whoever may help!
Regards
Eventually after doing something else I tried something way simpler than what I tried previously. Indeed a I added a listener (SelectionListener in this case) to the ImageList after loading the decoration model :
findDecorationIV().getImageList().addSelectionListener(new SelectionListener() {
#Override
public void selectionChanged(int oldSelected, int newSelected) {
System.out.println("On vient de sélectionner la décoration suivante " + newSelected);
}
});
So problem solved!

How to make a Listview non selectable?

I crated an application using DialogBox. I added a ListView to it.
Is there a way to make this Listview non-selectable?
The user should not select anything, it should just display some data.
Thanks in advance!
In order to disable list items on list creation you have to subclass from ArrayAdapter. You have to override the following methods: isEnabled(int position) and areAllItemsEnabled(). In former you return true or false depending is list item at given position enabled or not. In latter you return false.
If you want to use createFromResource() you will have to implement that method as well, since the ArrayAdapter.createFromResource() still instantiates ArrayAdapter instead of your own adapter.
Finally, the code would look something like the following:
class MenuAdapter extends ArrayAdapter<CharSequence> {
public MenuAdapter(
Context context, int textViewResId, CharSequence[] strings) {
super(context, textViewResId, strings);
}
public static MenuAdapter createFromResource(
Context context, int textArrayResId, int textViewResId) {
Resources resources = context.getResources();
CharSequence[] strings = resources.getTextArray(textArrayResId);
return new MenuAdapter(context, textViewResId, strings);
}
public boolean areAllItemsEnabled() {
return false;
}
public boolean isEnabled(int position) {
// return false if position == position you want to disable
}
}

Restrict text input inside combobox

I need to restrict text input inside combobox with positive numbers. I've searched stackoverflow for this and found similar question: Recommended way to restrict input in JavaFX textfield
The only difference is that the mentioned question addresses bare textfield. The answer approved by the javafx designers is to extend the TextField class and override couple of methods: replaceText and replaceSelection. This hack does not work with combobox: TextField instance if stored inside and is avaiable as read-only property named editor.
So what is the recommended way to restrict text input inside javafx combobox?
Since this question question never got a proper answer I'm adding a solution I've implemented that restricts the user to input that matches a regular expression and is shorter than a particular length (this is optional). This is done by adding a ChangeListener to the editor TextField. Any input that doesn't match will not get written into the editor TextField.
This example restricts the user to a maximum of two numeric characters.
ComboBox<Integer> integerComboBox = new ComboBox<Integer>();
integerComboBox.setEditable(true);
integerComboBox.getEditor().textProperty()
.addListener(new ChangeListener<String>() {
// The max length of the input
int maxLength = 2;
// The regular expression controlling the input, in this case we only allow number 0 to 9.
String restriction = "[0-9]";
private boolean ignore;
#Override
public void changed(
ObservableValue<? extends String> observableValue,
String oldValue, String newValue) {
if (ignore || newValue == null) {
return;
}
if (newValue.length() > maxLength) {
ignore = true;
integerComboBox.getEditor().setText(
newValue.substring(0, maxLength));
ignore = false;
}
if (!newValue.matches(restriction + "*")) {
ignore = true;
integerComboBox.getEditor().setText(oldValue);
ignore = false;
}
}
});
You might register a check method on the editor property to check if any input is accpetable.
Here I allow editing, but draw a red frame if values are not in the items list.
ObservableList<String> myChoices = FXCollections.observableArrayList();
void testComboBoxCheck(VBox box) {
myChoices.add("A");
myChoices.add("B");
myChoices.add("C");
ComboBox<String> first = new ComboBox<String>();
first.setItems(myChoices);
first.setEditable(true);
first.editorProperty().getValue().textProperty().addListener((v, o, n) -> {
if (myChoices.contains(n.toUpperCase())) {
first.setBackground(new Background(new BackgroundFill(Color.rgb(30,30,30), new CornerRadii(0), new Insets(0))));
} else {
first.setBackground(new Background(new BackgroundFill(Color.RED, new CornerRadii(0), new Insets(0))));
}
});
box.getChildren().addAll(first);
}
How about decouplign the Text editor from the ComboBox and link their values?
HBox combo = new HBox();
TextField editor = new TextField();
ComboBox<String> first = new ComboBox<String>();
first.setItems(myChoices);
first.setButtonCell(new ComboBoxListCell<String>(){
#Override public void updateItem(String s, boolean empty) {
super.updateItem(s, empty);
setText(null);
}
});
editor.textProperty().bindBidirectional(first.valueProperty());
combo.getChildren().addAll(editor, first);
box.getChildren().addAll(combo);
Now you have full conroll over the TextField allowing to override any methods etc.

Resources