Created
July 10, 2016 16:18
-
-
Save codenameone/6ac9cca810fc467ab15c192faf50907e to your computer and use it in GitHub Desktop.
Demonstrates the usage of the Codename One auto complete with a webservice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void showForm() { | |
final DefaultListModel<String> options = new DefaultListModel<>(); | |
AutoCompleteTextField ac = new AutoCompleteTextField(options) { | |
@Override | |
protected boolean filter(String text) { | |
if(text.length() == 0) { | |
return false; | |
} | |
String[] l = searchLocations(text); | |
if(l == null || l.length == 0) { | |
return false; | |
} | |
options.removeAll(); | |
for(String s : l) { | |
options.addItem(s); | |
} | |
return true; | |
} | |
}; | |
ac.setMinimumElementsShownInPopup(5); | |
hi.add(ac); | |
hi.add(new SpanLabel("This demo requires a valid google API key to be set below " | |
+ "you can get this key for the webservice (not the native key) by following the instructions here: " | |
+ "https://developers.google.com/places/web-service/get-api-key")); | |
hi.add(apiKey); | |
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key")); | |
hi.show(); | |
} | |
TextField apiKey = new TextField(); | |
String[] searchLocations(String text) { | |
try { | |
if(text.length() > 0) { | |
ConnectionRequest r = new ConnectionRequest(); | |
r.setPost(false); | |
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json"); | |
r.addArgument("key", apiKey.getText()); | |
r.addArgument("input", text); | |
NetworkManager.getInstance().addToQueueAndWait(r); | |
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8")); | |
String[] res = Result.fromContent(result).getAsStringArray("//description"); | |
return res; | |
} | |
} catch(Exception err) { | |
Log.e(err); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage of AutoCompleteTextField.
From the Codename One project