AutoCompleteTextField does not respect minimum length on load - codenameone

On load, when I focus or select the AutoCompleteTextField , the suggestions are showed right away eventhough I set the minimumLength to 4.
This is what is going on:
1) On load , all suggestions are shown in this example
2) Only after I start typing the suggestions behave correctly and they wouldn't show until we meet the 4 character criteria.
You can recreate this issue with the code below from a barebone hello world.
public void start() {
if (current != null) {
current.show();
return;
}
Form hi = new Form("Hi World");
ListModel<String> suggestionsModel = new DefaultListModel<String>();
suggestionsModel.addItem("Apple");
suggestionsModel.addItem("Banana");
suggestionsModel.addItem("Chocolate");
suggestionsModel.addItem("Elk");
suggestionsModel.addItem("Fish");
AutoCompleteTextField search = new AutoCompleteTextField(suggestionsModel);
search.setMinimumLength(4);
suggestionsModel.addSelectionListener(new SelectionListener() {
#Override
public void selectionChanged(int oldSelected, int newSelected) {
System.out.println("SUGGESTION SELECTED"+suggestionsModel.getSelectedIndex());
}
});
hi.add(search);
hi.show();
}

That is a bug on Codename One side... I experienced the same thing. Here is a link for you to file an issue and it will be fixed
https://github.com/codenameone/CodenameOne/issues/new
EDIT:
According to Shai's answer to your previous question, I doubt if the behavior will be changed due to other actions that rely on it.

Related

Codename One back command update form data

I have an Android application that uses Back Command to go back to the start screen.
The start screen has a label with a number inside, that I want to update when the back command is used.
I could figure out a solution with the code inside the back command, but I don't know if my approach is the best, since the ClassOne gets sort of loaded twice.
Here is the code I already have:
public class ClassOne {
public ClassOne(ClassPojo classPojo) {
// I want to change the text of this label when calling the back command
labelOne.setText(classPojo.getStringTest());
formOne.show();
}
}
public class ClassTwo {
public ClassTwo(Form a , ClassPojo classPojo) {
Command back = new Command("A") {
#Override
public void actionPerformed(ActionEvent evt) {
// I am adding the new value for the label here inside the back command
classPojo.setStringTest("testing");
a.showBack();
new ClassOne(classPojo);
}
};
formTwo.setBackCommand(back);
}
I'm not sure what the problem is, your example is a bit generic. However, a complete minimal example where the startScreen form instance is not recreated is this one:
Form startScreen = new Form("Start screen", BoxLayout.y());
Wrapper<Integer> count = new Wrapper<>(1);
Label numberLabel = new Label(count.get() + "");
Button button1 = new Button("Go to Form 2");
startScreen.addAll(numberLabel, button1);
startScreen.show();
button1.addActionListener(l -> {
Form form2 = new Form("Form 2", BoxLayout.y());
Label label = new Label("Use the back button");
form2.add(label);
form2.getToolbar().setBackCommand("Back", Toolbar.BackCommandPolicy.ALWAYS, ll -> {
count.set(count.get() + 1);
numberLabel.setText(count.get() + "");
startScreen.showBack();
});
form2.show();
});
If you don't even want to recreate the form2 instance, then you can do so:
Form startScreen = new Form("Start screen", BoxLayout.y());
Wrapper<Integer> count = new Wrapper<>(1);
Label numberLabel = new Label(count.get() + "");
Button button1 = new Button("Go to Form 2");
startScreen.addAll(numberLabel, button1);
startScreen.show();
Form form2 = new Form("Form 2", BoxLayout.y());
Label label = new Label("Use the back button");
form2.add(label);
form2.getToolbar().setBackCommand("Back", Toolbar.BackCommandPolicy.ALWAYS, ll -> {
count.set(count.get() + 1);
numberLabel.setText(count.get() + "");
startScreen.showBack();
});
button1.addActionListener(l -> {
form2.show();
});
In my opinion, whether or not to recreate the instances of a Form should be evaluated on a case-by-case basis. Among the variables between taking into consideration, according to my modest opinion, there is also the readability of the code and what it does, especially in complex cases.
The overhead of recreating a form instance is negligible so that wouldn't be a problem but in recent years we try to reuse form instances more. Not because of the performance.
The benefit is in minor behaviors e.g. scroll position within the form. These are very hard to replicate.
During testing, I found an easy solution that is adding the label to the constructor. I hope this snippet can be helpful.
public ClassTwo(Form a, ClassPojo classPojo, Label label) {
Command back = new Command("A") {
#Override
public void actionPerformed(ActionEvent evt) {
label.setText(classPojo.getStringTest());
a.showBack();
}
};

Restore all layered pane components in their positions and repaint them

This question is related to this: Keep Codename One components in invalid positions after app stop/resume
In the linked question, the solution proposed is to use a fake layout. I tried that, but it produces side effects when I try to restore the original layouts.
I tried a completely different approach, that works fine on Android. My question is why the following code works well in Android only (it doesn't work on iPhone, that seems to ignore that code) and if there are small changes that make that code working also on iPhone.
The code:
private Map<Component, Dimension> layeredPaneCmps = new HashMap<>();
public void start() {
if (current != null) {
current.show();
layeredPaneRestore(); // it works on Android, but not on iOS
return;
}
[...]
}
public void stop() {
current = getCurrentForm();
if (current instanceof Dialog) {
((Dialog) current).dispose();
current = getCurrentForm();
}
layeredPaneSave(null);
}
/**
* Save the position of all layered pane components in a recursive way: just
* invoke with null as cnt.
*
* #param cnt
*/
private void layeredPaneSave(Container cnt) {
if (cnt == null) {
layeredPaneCmps.clear();
cnt = Display.getInstance().getCurrent().getLayeredPane(this.getClass(), true);
}
for (int i = 0; i < cnt.getComponentCount(); i++) {
layeredPaneCmps.put(cnt.getComponentAt(i), new Dimension(cnt.getComponentAt(i).getX(), cnt.getComponentAt(i).getY()));
if (cnt.getComponentAt(i) instanceof Container) {
layeredPaneSave((Container) cnt.getComponentAt(i));
}
}
}
/**
* Restores all layered pane components in their position and repaints them.
*/
private void layeredPaneRestore() {
Container layeredPane = Display.getInstance().getCurrent().getLayeredPane(this.getClass(), true);
for (Component cmp : layeredPaneCmps.keySet()) {
cmp.setX(layeredPaneCmps.get(cmp).getWidth());
cmp.setY(layeredPaneCmps.get(cmp).getHeight());
cmp.repaint();
}
layeredPane.repaint();
}
Android and iOS have very different suspend/resume behaviors where iOS tries to minimize repaints and back-grounding while Android constantly suspends/resumes. I would suggest logging in the stop()/start() method to make sure they aren't invoked multiple times.
Notice that you shouldn't invoke repaint() it would be invoked for you. Since a repaint() might trigger a layout this could be a problem. Also the repaint() of the parent component loops into painting the components so layeredPane would be enough and doesn't require also cmp.repaint();.

Why can not update autocomplete suggestions?

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

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!

MVC5 DisplayModeProvider registration problems

so I have an mvc 5 application with 3 display modes, desktop (default), mobile, and tablet. I'm using WURFL to figure out devices. Here's the code called from global.cs to register:
public static void RegisterDisplayModes(IList<IDisplayMode> displayModes){
var datafile = HttpContext.Current.Server.MapPath(WurflDataFilePath);
var configurer = new InMemoryConfigurer().MainFile(datafile);
var manager = WURFLManagerBuilder.Build(configurer);
HttpContext.Current.Cache[WURFLMANAGER_CACHE_KEY] = manager;
bool mobileEnabled = ConfigurationManager.AppSettings["EnableMobileSite"] == "true";
bool tabletEnabled = ConfigurationManager.AppSettings["EnableTabletSite"] == "true";
var modeDesktop = new DefaultDisplayMode("") {
ContextCondition = (c => c.Request.IsDesktop())
};
var modeMobile = new DefaultDisplayMode("mobile"){
ContextCondition = (c => c.Request.IsMobile())
};
var modeTablet = new DefaultDisplayMode("tablet"){
ContextCondition = (c => c.Request.IsTablet())
};
displayModes.Clear();
if (mobileEnabled) displayModes.Add(modeMobile);
if (tabletEnabled) displayModes.Add(modeTablet);
displayModes.Add(modeDesktop);
}
I'm using some extension methods to HttpRequestBase, as discussed in http://msdn.microsoft.com/en-us/magazine/dn296507.aspx:
public static bool IsDesktop(this HttpRequestBase request){
return true;
}
public static bool IsMobile(this HttpRequestBase request) {
return IsMobileInternal(request.UserAgent) && !IsForcedDesktop(request);
}
public static bool IsTablet(this HttpRequestBase request) {
return IsTabletInternal(request.UserAgent) && !IsForcedDesktop(request);
}
public static void OverrideBrowser(this HttpRequestBase request, bool forceDesktop){
request.RequestContext.HttpContext.Cache[OVERRIDE_BROWSER_CACHE_KEY] = forceDesktop;
}
public static bool IsForcedDesktop(this HttpRequestBase request){
var isForced = request.RequestContext.HttpContext.Cache[OVERRIDE_BROWSER_CACHE_KEY];
return isForced != null ? isForced.ToString().ToBool() : false;
}
private static bool IsMobileInternal(string userAgent) {
var device = WURFLManagerBuilder.Instance.GetDeviceForRequest(userAgent);
if (device.IsTablet() == true) {
return false;
} else {
return device.IsMobile();
}
}
private static bool IsTabletInternal(string userAgent) {
var device = WURFLManagerBuilder.Instance.GetDeviceForRequest(userAgent);
return device.IsTablet();
}
It all works fine for a while, but then after an hour or so, mobile and tablet devices start displaying the desktop views, and the desktop view starts showing the ViewSwitcher shared view (I assume most people are familiar with it, it just allows you to show the desktop view from a mobile device). It's almost like that caching bug in mvc4. I have tried removing my code to register the display modes, and just went with the default mvc mobile support, and it works fine it has the same issue! So clearly there's a problem in here somewhere... can anyone see anything obvious? Almost impossible to debug cause problems only start coming up after a long time, and even then only on the live system really! Any ideas?
Thanks heaps... been on this issue for way too long now...
Cheers
Andy
EDIT: even stripping it right back to the default implementations creates the issue. I added some debugging code to make sure I'm actually running mvc5, but it appears I am. I've also tried the initially recommended workaround for the issue on mvc4 by disabling the cache, still no joy. Is there really no one with info on this?
So I finally figured it out. Very simple as usual. For some reason I used RequestContext.HttpContext.Cache to save the status when someone wants the full view as opposed to the mobile view. I've never used HttpContext.Cache, I'm pretty sure I would have taken that from a blog somewhere - can't find it anymore though. So all that happened was that it would switch the view for everyone, not just the one person. Can't believe it took weeks to figure that out. Hope it helps someone else at some point.

Resources