SlideShare a Scribd company logo
Connecting to a Webservice
Connecting to a Webservice
✦There are a lot of ways to do web service
communication in Codename One
✦The webservice wizard is a powerful tool but I
won’t be using it here because it might not fit for
all use cases
✦I’ll stick to core classes and won’t wander to
libraries or special syntaxes like xpath. We all
know Java but some of us might not know xpath
The Item Webservice
✦We can add an item using this curl request:
curl -H "Content-Type: application/json" -X PUT 
-d '{"name":"Item Name", "marked":false, "deleted":false, "owner":"Shai"}' 
http://localhost:8080/item
✦The output is:
{"id":1,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"}
public class Item {
private Long id;
private String name;
private boolean marked;
private boolean deleted;
private String owner;
public Item(Map<String, Object> m) {
this.id = Util.toLongValue(m.get("id"));
this.name = (String)m.get("name");
String b = (String)m.get("marked");
this.marked = b != null && b.equals("true");
b = (String)m.get("deleted");
this.deleted = b != null && b.equals("true");
this.owner = (String)m.get("owner");
}
public Map<String, Object> toMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("id", getId());
map.put("name", getName());
map.put("owner", getOwner());
map.put("deleted", isDeleted());
map.put("marked", isMarked());
return map;
}
// …
}
Item Class
public class Item {
private Long id;
private String name;
private boolean marked;
private boolean deleted;
private String owner;
public Item(Map<String, Object> m) {
this.id = Util.toLongValue(m.get("id"));
this.name = (String)m.get("name");
String b = (String)m.get("marked");
this.marked = b != null && b.equals("true");
b = (String)m.get("deleted");
this.deleted = b != null && b.equals("true");
this.owner = (String)m.get("owner");
}
public Map<String, Object> toMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("id", getId());
map.put("name", getName());
map.put("owner", getOwner());
map.put("deleted", isDeleted());
map.put("marked", isMarked());
return map;
}
// …
}
Item Class
Trimmed Code
I trimmed a lot of boilerplate
code, the constructors,
getters/setters to all the
elements
public Item addItemSync(Item i) {
final String json = Result.fromContent(i.toMap()).toString();
ConnectionRequest request = new ConnectionRequest(url + "item", true);
request.setRequestBody(json);
request.setContentType("application/json");
request.setHttpMethod("PUT");
NetworkManager.getInstance().addToQueueAndWait(request);
JSONParser.setUseLongs(true);
if(request.getResponseData() != null) {
JSONParser p = new JSONParser();
InputStream response = new ByteArrayInputStream(request.getResponseData());
try {
Map<String, Object> result = p.parseJSON(new InputStreamReader(response, "UTF-8"));
return new Item(result);
} catch(IOException err) {
Log.e(err);
}
}
return null;
}
Server class - addItemSync
Sync vs Async API’s
✦Sync API’s can be invoked on the EDT (Event
Dispatch - UI thread)
✦Easier flow for some use cases
✦Async API’s are slightly more performant
✦Async doesn’t encounter “weird” nesting issues
(I’ll go into these when discussing the EDT)
public void addItemAsync(Item i, final SuccessCallback<Item> onSuccess) {
final String json = Result.fromContent(i.toMap()).toString();
ConnectionRequest request = new ConnectionRequest(url + "item", true) {
private Item resultItem;
@Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.getBytes("UTF-8"));
}
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser.setUseLongs(true);
JSONParser p = new JSONParser();
Map<String, Object> result = p.parseJSON(new InputStreamReader(input, "UTF-8"));
resultItem = new Item(result);
}
@Override
protected void postResponse() {
onSuccess.onSucess(resultItem);
}
};
request.setContentType("application/json");
request.setHttpMethod("PUT");
NetworkManager.getInstance().addToQueue(request);
}
Server class - addItemAsync
Fetch My Items
✦We can fetch my items using:
curl http://localhost:8080/item?owner=Shai
✦The output is:
[{"id":1,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"},
{"id":2,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"},
{"id":3,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"}]
public Item[] getItemsSync() {
ConnectionRequest request = new ConnectionRequest(url + "item", false);
request.addArgument("owner", owner);
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
if(request.getResponseData() != null) {
JSONParser p = new JSONParser();
InputStream response = new ByteArrayInputStream(request.getResponseData());
try {
Map<String, Object> result = p.parseJSON(new InputStreamReader(response, "UTF-8"));
List<Map<String, Object>> resultList = (List<Map<String, Object>>)result.get("root");
Item[] arr = new Item[resultList.size()];
for(int iter = 0 ; iter < arr.length ; iter++) {
arr[iter] = new Item(resultList.get(iter));
}
return arr;
} catch(IOException err) {
Log.e(err);
}
}
return null;
}
Server class - getItemsSync
public void getItemsAsync(final SuccessCallback<Item[]> response) {
ConnectionRequest request = new ConnectionRequest(url + "item", false) {
Item[] arr;
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser.setUseLongs(true);
JSONParser p = new JSONParser();
Map<String, Object> result = p.parseJSON(new InputStreamReader(input, "UTF-8"));
List<Map<String, Object>> resultList = (List<Map<String, Object>>)result.get("root");
arr = new Item[resultList.size()];
for(int iter = 0 ; iter < arr.length ; iter++) {
arr[iter] = new Item(resultList.get(iter));
}
}
@Override
protected void postResponse() {
response.onSucess(arr);
}
};
request.addArgument("owner", owner);
request.setContentType("application/json");
NetworkManager.getInstance().addToQueue(request);
}
Server class - getItemsAsync
Connecting to The UI
✦We can bind this to the todo list demo
✦Just add/list entries, first we need global
members
private static final String OWNER = "Owner";
private Server serverInstance = new Server("http://localhost:8080/", OWNER);
Connecting to The UI
✦Replace the for loop that adds the elements with:
Component ip = FlowLayout.encloseCenterMiddle(new InfiniteProgress());
shoppingList.add(ip);
serverInstance.getItemsAsync(items -> {
ip.remove();
for(Item i : items) {
if(!i.isDeleted()) {
Component c = createCheck(i.getName(), i.isMarked());
c.setWidth(shoppingList.getWidth());
shoppingList.add(c);
shoppingList.add(createSeparator());
}
}
shoppingList.revalidate();
});
Connecting to The UI
✦Replace the for loop that adds the elements with:
Component ip = FlowLayout.encloseCenterMiddle(new InfiniteProgress());
shoppingList.add(ip);
serverInstance.getItemsAsync(items -> {
ip.remove();
for(Item i : items) {
if(!i.isDeleted()) {
Component c = createCheck(i.getName(), i.isMarked());
c.setWidth(shoppingList.getWidth());
shoppingList.add(c);
shoppingList.add(createSeparator());
}
}
shoppingList.revalidate();
});
Async
I have to use async or call
serially here. The form hasn’t
shown yet and we need to
show it first before blocking
progress…
Connecting to The UI
✦Adding a new element using the FAB:
fab.addActionListener(e -> {
shoppingList.scrollComponentToVisible(filler);
TextField text = new TextField("");
shoppingList.addComponent(1, text);
shoppingList.revalidate();
text.startEditingAsync();
text.addActionListener(ee -> {
if(text.getText().length() > 0) {
text.remove();
shoppingList.addComponent(1, createCheck(text.getText(), false));
shoppingList.addComponent(2, createSeparator());
shoppingList.getContentPane().animateLayout(150);
serverInstance.addItemAsync(new Item(null, text.getText(), false, false, OWNER),
i -> ToastBar.showMessage("Item added!", FontImage.MATERIAL_INFO));
}
});
});
Connecting to The UI
✦Adding a new element using the FAB:
fab.addActionListener(e -> {
shoppingList.scrollComponentToVisible(filler);
TextField text = new TextField("");
shoppingList.addComponent(1, text);
shoppingList.revalidate();
text.startEditingAsync();
text.addActionListener(ee -> {
if(text.getText().length() > 0) {
text.remove();
shoppingList.addComponent(1, createCheck(text.getText(), false));
shoppingList.addComponent(2, createSeparator());
shoppingList.getContentPane().animateLayout(150);
serverInstance.addItemAsync(new Item(null, text.getText(), false, false, OWNER),
i -> ToastBar.showMessage("Item added!", FontImage.MATERIAL_INFO));
}
});
});
Async
I could have used sync here
just as well there was no
reason in terms of the UI
though so I used an async
call
Connecting to a Webservice.pdf
Connecting to a Webservice.pdf
Mini
Mission
© Codename One 2017 all rights reserved
Implement Check
✦The check functionality should be stored in the server
✦It should be detected in the UI and communicated as
a state change to the server
✦This means creating a webservice call both in the
client and the server
✦Extra credit: implement delete via swipe and make it
attractive!
✦Triple credit: Port Item to use Property on the client
What did we learn?
✦How to use a JSON webservice
✦Async vs. Sync calls in NetworkManager
✦Event dispatch thread relation to networking
✦Wiring remote calls to UI
Thank You
Ad

More Related Content

Similar to Connecting to a Webservice.pdf (20)

Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
fashiongallery1
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
David Pichsenmeister
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Claire Townend Gee
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
Paco de la Cruz
 
Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기
Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기
Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기
정민 안
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
Mostafa Amer
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
WebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsWebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.js
Robert Nyman
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
Rob Windsor
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Dan Wahlin
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
Joe Keeley
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
Workshop: Building Vaadin add-ons
Workshop: Building Vaadin add-onsWorkshop: Building Vaadin add-ons
Workshop: Building Vaadin add-ons
Sami Ekblad
 
Micro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMicro app-framework - NodeLive Boston
Micro app-framework - NodeLive Boston
Michael Dawson
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
fashiongallery1
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
Rouven Weßling
 
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
David Pichsenmeister
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Claire Townend Gee
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
Paco de la Cruz
 
Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기
Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기
Let'Swift 2024 - Plugin 패턴을 이용하여 기능 확장하기
정민 안
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
Mostafa Amer
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 
Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30) Azure Durable Functions (2019-03-30)
Azure Durable Functions (2019-03-30)
Paco de la Cruz
 
WebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsWebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.js
Robert Nyman
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
Introduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST APIIntroduction to the SharePoint Client Object Model and REST API
Introduction to the SharePoint Client Object Model and REST API
Rob Windsor
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Dan Wahlin
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
Joe Keeley
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
Workshop: Building Vaadin add-ons
Workshop: Building Vaadin add-onsWorkshop: Building Vaadin add-ons
Workshop: Building Vaadin add-ons
Sami Ekblad
 
Micro app-framework - NodeLive Boston
Micro app-framework - NodeLive BostonMicro app-framework - NodeLive Boston
Micro app-framework - NodeLive Boston
Michael Dawson
 

More from ShaiAlmog1 (20)

The Duck Teaches Learn to debug from the masters. Local to production- kill ...
The Duck Teaches  Learn to debug from the masters. Local to production- kill ...The Duck Teaches  Learn to debug from the masters. Local to production- kill ...
The Duck Teaches Learn to debug from the masters. Local to production- kill ...
ShaiAlmog1
 
create-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdfcreate-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdf
ShaiAlmog1
 
create-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdfcreate-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdfcreate-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdfcreate-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdfcreate-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdf
ShaiAlmog1
 
create-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdfcreate-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdfcreate-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdf
ShaiAlmog1
 
create-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdfcreate-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdf
ShaiAlmog1
 
create-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdfcreate-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdfcreate-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
ShaiAlmog1
 
create-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdfcreate-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdfCreating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdfCreating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdfCreating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdfCreating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdfCreating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdfCreating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdfCreating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdf
ShaiAlmog1
 
The Duck Teaches Learn to debug from the masters. Local to production- kill ...
The Duck Teaches  Learn to debug from the masters. Local to production- kill ...The Duck Teaches  Learn to debug from the masters. Local to production- kill ...
The Duck Teaches Learn to debug from the masters. Local to production- kill ...
ShaiAlmog1
 
create-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdfcreate-netflix-clone-06-client-ui.pdf
create-netflix-clone-06-client-ui.pdf
ShaiAlmog1
 
create-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdfcreate-netflix-clone-01-introduction_transcript.pdf
create-netflix-clone-01-introduction_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdfcreate-netflix-clone-02-server_transcript.pdf
create-netflix-clone-02-server_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdfcreate-netflix-clone-04-server-continued_transcript.pdf
create-netflix-clone-04-server-continued_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdfcreate-netflix-clone-01-introduction.pdf
create-netflix-clone-01-introduction.pdf
ShaiAlmog1
 
create-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdfcreate-netflix-clone-06-client-ui_transcript.pdf
create-netflix-clone-06-client-ui_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdfcreate-netflix-clone-03-server.pdf
create-netflix-clone-03-server.pdf
ShaiAlmog1
 
create-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdfcreate-netflix-clone-04-server-continued.pdf
create-netflix-clone-04-server-continued.pdf
ShaiAlmog1
 
create-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdfcreate-netflix-clone-05-client-model_transcript.pdf
create-netflix-clone-05-client-model_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdfcreate-netflix-clone-03-server_transcript.pdf
create-netflix-clone-03-server_transcript.pdf
ShaiAlmog1
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
ShaiAlmog1
 
create-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdfcreate-netflix-clone-05-client-model.pdf
create-netflix-clone-05-client-model.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdfCreating a Whatsapp Clone - Part II.pdf
Creating a Whatsapp Clone - Part II.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdfCreating a Whatsapp Clone - Part IX - Transcript.pdf
Creating a Whatsapp Clone - Part IX - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdfCreating a Whatsapp Clone - Part II - Transcript.pdf
Creating a Whatsapp Clone - Part II - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdfCreating a Whatsapp Clone - Part V - Transcript.pdf
Creating a Whatsapp Clone - Part V - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdfCreating a Whatsapp Clone - Part IV - Transcript.pdf
Creating a Whatsapp Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdfCreating a Whatsapp Clone - Part IV.pdf
Creating a Whatsapp Clone - Part IV.pdf
ShaiAlmog1
 
Creating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdfCreating a Whatsapp Clone - Part I - Transcript.pdf
Creating a Whatsapp Clone - Part I - Transcript.pdf
ShaiAlmog1
 
Ad

Recently uploaded (20)

HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Ad

Connecting to a Webservice.pdf

  • 1. Connecting to a Webservice
  • 2. Connecting to a Webservice ✦There are a lot of ways to do web service communication in Codename One ✦The webservice wizard is a powerful tool but I won’t be using it here because it might not fit for all use cases ✦I’ll stick to core classes and won’t wander to libraries or special syntaxes like xpath. We all know Java but some of us might not know xpath
  • 3. The Item Webservice ✦We can add an item using this curl request: curl -H "Content-Type: application/json" -X PUT -d '{"name":"Item Name", "marked":false, "deleted":false, "owner":"Shai"}' http://localhost:8080/item ✦The output is: {"id":1,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"}
  • 4. public class Item { private Long id; private String name; private boolean marked; private boolean deleted; private String owner; public Item(Map<String, Object> m) { this.id = Util.toLongValue(m.get("id")); this.name = (String)m.get("name"); String b = (String)m.get("marked"); this.marked = b != null && b.equals("true"); b = (String)m.get("deleted"); this.deleted = b != null && b.equals("true"); this.owner = (String)m.get("owner"); } public Map<String, Object> toMap() { HashMap<String, Object> map = new HashMap<>(); map.put("id", getId()); map.put("name", getName()); map.put("owner", getOwner()); map.put("deleted", isDeleted()); map.put("marked", isMarked()); return map; } // … } Item Class
  • 5. public class Item { private Long id; private String name; private boolean marked; private boolean deleted; private String owner; public Item(Map<String, Object> m) { this.id = Util.toLongValue(m.get("id")); this.name = (String)m.get("name"); String b = (String)m.get("marked"); this.marked = b != null && b.equals("true"); b = (String)m.get("deleted"); this.deleted = b != null && b.equals("true"); this.owner = (String)m.get("owner"); } public Map<String, Object> toMap() { HashMap<String, Object> map = new HashMap<>(); map.put("id", getId()); map.put("name", getName()); map.put("owner", getOwner()); map.put("deleted", isDeleted()); map.put("marked", isMarked()); return map; } // … } Item Class Trimmed Code I trimmed a lot of boilerplate code, the constructors, getters/setters to all the elements
  • 6. public Item addItemSync(Item i) { final String json = Result.fromContent(i.toMap()).toString(); ConnectionRequest request = new ConnectionRequest(url + "item", true); request.setRequestBody(json); request.setContentType("application/json"); request.setHttpMethod("PUT"); NetworkManager.getInstance().addToQueueAndWait(request); JSONParser.setUseLongs(true); if(request.getResponseData() != null) { JSONParser p = new JSONParser(); InputStream response = new ByteArrayInputStream(request.getResponseData()); try { Map<String, Object> result = p.parseJSON(new InputStreamReader(response, "UTF-8")); return new Item(result); } catch(IOException err) { Log.e(err); } } return null; } Server class - addItemSync
  • 7. Sync vs Async API’s ✦Sync API’s can be invoked on the EDT (Event Dispatch - UI thread) ✦Easier flow for some use cases ✦Async API’s are slightly more performant ✦Async doesn’t encounter “weird” nesting issues (I’ll go into these when discussing the EDT)
  • 8. public void addItemAsync(Item i, final SuccessCallback<Item> onSuccess) { final String json = Result.fromContent(i.toMap()).toString(); ConnectionRequest request = new ConnectionRequest(url + "item", true) { private Item resultItem; @Override protected void buildRequestBody(OutputStream os) throws IOException { os.write(json.getBytes("UTF-8")); } @Override protected void readResponse(InputStream input) throws IOException { JSONParser.setUseLongs(true); JSONParser p = new JSONParser(); Map<String, Object> result = p.parseJSON(new InputStreamReader(input, "UTF-8")); resultItem = new Item(result); } @Override protected void postResponse() { onSuccess.onSucess(resultItem); } }; request.setContentType("application/json"); request.setHttpMethod("PUT"); NetworkManager.getInstance().addToQueue(request); } Server class - addItemAsync
  • 9. Fetch My Items ✦We can fetch my items using: curl http://localhost:8080/item?owner=Shai ✦The output is: [{"id":1,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"}, {"id":2,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"}, {"id":3,"name":"Item Name","marked":false,"deleted":false,"owner":"Shai"}]
  • 10. public Item[] getItemsSync() { ConnectionRequest request = new ConnectionRequest(url + "item", false); request.addArgument("owner", owner); request.setContentType("application/json"); NetworkManager.getInstance().addToQueueAndWait(request); if(request.getResponseData() != null) { JSONParser p = new JSONParser(); InputStream response = new ByteArrayInputStream(request.getResponseData()); try { Map<String, Object> result = p.parseJSON(new InputStreamReader(response, "UTF-8")); List<Map<String, Object>> resultList = (List<Map<String, Object>>)result.get("root"); Item[] arr = new Item[resultList.size()]; for(int iter = 0 ; iter < arr.length ; iter++) { arr[iter] = new Item(resultList.get(iter)); } return arr; } catch(IOException err) { Log.e(err); } } return null; } Server class - getItemsSync
  • 11. public void getItemsAsync(final SuccessCallback<Item[]> response) { ConnectionRequest request = new ConnectionRequest(url + "item", false) { Item[] arr; @Override protected void readResponse(InputStream input) throws IOException { JSONParser.setUseLongs(true); JSONParser p = new JSONParser(); Map<String, Object> result = p.parseJSON(new InputStreamReader(input, "UTF-8")); List<Map<String, Object>> resultList = (List<Map<String, Object>>)result.get("root"); arr = new Item[resultList.size()]; for(int iter = 0 ; iter < arr.length ; iter++) { arr[iter] = new Item(resultList.get(iter)); } } @Override protected void postResponse() { response.onSucess(arr); } }; request.addArgument("owner", owner); request.setContentType("application/json"); NetworkManager.getInstance().addToQueue(request); } Server class - getItemsAsync
  • 12. Connecting to The UI ✦We can bind this to the todo list demo ✦Just add/list entries, first we need global members private static final String OWNER = "Owner"; private Server serverInstance = new Server("http://localhost:8080/", OWNER);
  • 13. Connecting to The UI ✦Replace the for loop that adds the elements with: Component ip = FlowLayout.encloseCenterMiddle(new InfiniteProgress()); shoppingList.add(ip); serverInstance.getItemsAsync(items -> { ip.remove(); for(Item i : items) { if(!i.isDeleted()) { Component c = createCheck(i.getName(), i.isMarked()); c.setWidth(shoppingList.getWidth()); shoppingList.add(c); shoppingList.add(createSeparator()); } } shoppingList.revalidate(); });
  • 14. Connecting to The UI ✦Replace the for loop that adds the elements with: Component ip = FlowLayout.encloseCenterMiddle(new InfiniteProgress()); shoppingList.add(ip); serverInstance.getItemsAsync(items -> { ip.remove(); for(Item i : items) { if(!i.isDeleted()) { Component c = createCheck(i.getName(), i.isMarked()); c.setWidth(shoppingList.getWidth()); shoppingList.add(c); shoppingList.add(createSeparator()); } } shoppingList.revalidate(); }); Async I have to use async or call serially here. The form hasn’t shown yet and we need to show it first before blocking progress…
  • 15. Connecting to The UI ✦Adding a new element using the FAB: fab.addActionListener(e -> { shoppingList.scrollComponentToVisible(filler); TextField text = new TextField(""); shoppingList.addComponent(1, text); shoppingList.revalidate(); text.startEditingAsync(); text.addActionListener(ee -> { if(text.getText().length() > 0) { text.remove(); shoppingList.addComponent(1, createCheck(text.getText(), false)); shoppingList.addComponent(2, createSeparator()); shoppingList.getContentPane().animateLayout(150); serverInstance.addItemAsync(new Item(null, text.getText(), false, false, OWNER), i -> ToastBar.showMessage("Item added!", FontImage.MATERIAL_INFO)); } }); });
  • 16. Connecting to The UI ✦Adding a new element using the FAB: fab.addActionListener(e -> { shoppingList.scrollComponentToVisible(filler); TextField text = new TextField(""); shoppingList.addComponent(1, text); shoppingList.revalidate(); text.startEditingAsync(); text.addActionListener(ee -> { if(text.getText().length() > 0) { text.remove(); shoppingList.addComponent(1, createCheck(text.getText(), false)); shoppingList.addComponent(2, createSeparator()); shoppingList.getContentPane().animateLayout(150); serverInstance.addItemAsync(new Item(null, text.getText(), false, false, OWNER), i -> ToastBar.showMessage("Item added!", FontImage.MATERIAL_INFO)); } }); }); Async I could have used sync here just as well there was no reason in terms of the UI though so I used an async call
  • 19. Mini Mission © Codename One 2017 all rights reserved
  • 20. Implement Check ✦The check functionality should be stored in the server ✦It should be detected in the UI and communicated as a state change to the server ✦This means creating a webservice call both in the client and the server ✦Extra credit: implement delete via swipe and make it attractive! ✦Triple credit: Port Item to use Property on the client
  • 21. What did we learn? ✦How to use a JSON webservice ✦Async vs. Sync calls in NetworkManager ✦Event dispatch thread relation to networking ✦Wiring remote calls to UI