Codename One – Upload/retrieve image from database
This simple tutorial was requested by a quite good number of you, specially those who are in third year class at ESPRIT, or who have worked on all of my previous codename one samples. I made it as easy as it already is. We’ll simply capture a photo, get it’s path on temporary storage and store/retrieve this data on database.
This is what the ui we’ll work on look like:
Main UI
Our demo ui contains an image viewer and three buttons. Add the following code to MyApplication.java :
public class MyApplication { private Form current; private Resources theme; private ConnectionRequest connectionRequest; private Image img; private String imgPath; public void init(Object context) { theme = UIManager.initFirstTheme("/theme"); Toolbar.setGlobalToolbar(true); } public void start() { try { if (current != null) { current.show(); return; } Form hi = new Form("Image Uploader",new BoxLayout(BoxLayout.Y_AXIS)); Button btnUploadImg = new Button("Add Image to DB"); Button btnReadImg = new Button("Read Image from DB"); Button btnRemoveImg = new Button("Remove Image from DB"); ImageViewer iv = new ImageViewer(Image.createImage("/placeholder2.png")); iv.addPointerReleasedListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // } }); btnUploadImg.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // } }); btnRemoveImg.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // } }); btnReadImg.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // } }); hi.add(iv); hi.add(btnUploadImg); hi.add(btnReadImg); hi.add(btnRemoveImg); hi.show(); } catch (IOException ex) { } } public void stop() { current = Display.getInstance().getCurrent(); if (current instanceof Dialog) { ((Dialog) current).dispose(); current = Display.getInstance().getCurrent(); } } public void destroy() { } //---------- crud operations ---------------- private void addImage(String imgName) { // } private void removeLastUploadedImage(String imgName) { // } public void readImage(String nomImg,ImageViewer iv) { // } }
Choosing image from the device
For this purpose we’ll use the Capture object
that “captures” media files from the device e.g. record audio, video and snap photos. Files returned by this class are potentially temporary files and might be deleted by the OS in the future.
We’ll simply create an Image with the local temporary storage path returned by Capture.capturePhoto and set it to the imageViewer:
iv.addPointerReleasedListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { try { imgPath = Capture.capturePhoto(Display.getInstance().getDisplayWidth(), -1); img = Image.createImage(imgPath); iv.setImage(img); } catch (IOException ex) { System.out.println(ex); } } });
Adding to DB
We’ll store a new image to the database with the imgPath value. We’ll do the same work as on previous cruds tutorial.
btnUploadImg.addActionListener((ActionListener) (ActionEvent evt) -> { addImage(imgPath); });
private void addImage(String imgPath) { connectionRequest = new ConnectionRequest() { @Override protected void postResponse() { Dialog.show("Add Image", "Image added successfully", "OK", null); } }; connectionRequest.setUrl("http://localhost/testUploader/insert.php?path=" + imgPath); NetworkManager.getInstance().addToQueue(connectionRequest); }
Removing from DB
Here we’ll just try to delete an image we add ( right after adding, we click on the remobe button ) just to test out how thing work, you can change this in your code the delete a selected image from a list, ect..
btnRemoveImg.addActionListener((ActionListener) (ActionEvent evt) -> { /** * we are just testing the remove from DB operation.. So * we'll remove the last uploaded image.. you can switch * this in your code to remove a selected img..ect.. * */ removeLastUploadedImage(imgPath); });
private void removeLastUploadedImage(String imgPath) { connectionRequest = new ConnectionRequest() { @Override protected void postResponse() { Dialog.show("Remove Image", "Image removed successfully", "OK", null); } }; connectionRequest.setUrl("http://localhost/testUploader/remove.php?path=" + imgPath); NetworkManager.getInstance().addToQueue(connectionRequest); }
Reading from database
We’ll do the same test we did for the removal, we’ll add the image path statically just to test out this simple operation:
btnReadImg.addActionListener((ActionListener) (ActionEvent evt) -> { readImage("file://C:/Users/Amal/AppData/Local/Temp/temp7382551891537267493s..jpg", iv); });
public void readImage(String pathImg, ImageViewer iv) { connectionRequest = new ConnectionRequest() { Img loadedImg; Listimgs = new ArrayList<>(); @Override protected void readResponse(InputStream in) throws IOException { JSONParser json = new JSONParser(); try { Reader reader = new InputStreamReader(in, "UTF-8"); Map<String, Object> data = json.parseJSON(reader); List<Map<String, Object>> content = (List<Map<String, Object>>) data.get("root"); //Map<String,Object> imgRow = (Map<String, Object>)data.get("images"); imgs.clear(); for (Map<String, Object> obj : content) { imgs.add(new Img(Integer.parseInt((String)obj.get("id")),(String) obj.get("path"))); } } catch (IOException err) { Log.e(err); } } @Override protected void postResponse() { try { loadedImg=imgs.get(0); iv.setImage(Image.createImage(loadedImg.getPath())); } catch (IOException ex) { } } }; connectionRequest.setUrl("http://localhost/testUploader/read.php?path=" + pathImg); NetworkManager.getInstance().addToQueue(connectionRequest); }
That’s all coders ! You can download the associated php scripts here.
much thanks from esprit
you are so much welcome 🙂
Thank you for this tutorial it’s pretty useful, but How am I supposed to share an image to our server using multipart request through a JSON API (we are actually using a Symfony app), I made some researches it appears that I am supposed to send some kind of binary image or base64 files or input stream and it’s really confusing, and have no idea how am I supposed to encode and decode them between two ends if you have any idea I would be more than happy to find a solution for this cuz I literally wasted several hours looking for an answer and Thank you again.
Hi IS Img in the readImage’s function a class named img ?
When you find people suffering from the same pidev shit on the internet giving you solutions on how to use the poorly documted/used frameworks ESPRIT uses <3
Highly apreciated, good luck