3
votes

I have edited the question as your suggestions but null pointer exception is caught.I used connectionRequest instead of multipartRequest since i dont need to upload(just need to read the value frm json). All my codes below, please have a look.

Edited: exception

java.lang.NullPointerException
    at userclasses.StateMachine$16.readResponse(StateMachine.java:1834)
    at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:438)
    at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:263)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Code:

 @Override
    protected void beforeImgGallery(Form f) {
        int iter = 0;
        GridLayout gr = new GridLayout(1, 1);
        Container grid = new Container(gr);
        gr.setAutoFit(true);
        grid.setScrollableY(true);
        grid.addComponent(new InfiniteProgress());
        f.addComponent(BorderLayout.CENTER, grid);

        f.removeAllCommands();
        f.setBackCommand(null);
        createPictureCommand(grid);
    }

    private static boolean animating;
    private Vector<Map<String, Object>> responsesgallery;
    String galleryPhotoUrl;

    private void createPictureCommand(final Container grid) {
        ConnectionRequest mp = new ConnectionRequest(){

            @Override
            protected void readResponse(InputStream input) throws IOException {
                JSONParser p = new JSONParser();
                results = p.parse(new InputStreamReader(input));
                 responsesgallery = (Vector<Map<String, Object>>) results.get("data");
                 //i've kept this for loop in postResponse but same error
                for (int i = 0; i < responsesgallery.size(); i++) {
                //null pointer exception in this line
                    final Button btn = createImageButton(i, grid, imageList.getSize()); 
                    //if i simply create a btn like below, it works
//                  final Button btn = new Button((URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL))); 
                    imageList.addImageId(i);
                    grid.addComponent(i, btn);
                    Hashtable hm = (Hashtable) responsesgallery.get(i);
                    String galleryImgId = (String) hm.get("news_id");
                    galleryPhotoUrl = (String) hm.get("photo");
                }
            }
        };
        mp.setUrl("http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews");
        NetworkManager.getInstance().addToQueueAndWait(mp);
    }

    ImageList imageList;

    Button createImageButton(final int imageId, final Container grid, final int offset) {
        final Button btn = new Button(URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL));
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                imageList.setSelectedIndex(offset);
                final Container viewerParent = new Container(new LayeredLayout());
                ImageViewer viewer = new ImageViewer(imageList.getItemAt(offset));
                viewerParent.addComponent(viewer);
                Container parent = new Container(new BorderLayout());
                viewerParent.addComponent(parent);
                viewer.setImageList(imageList);
                grid.getParent().replace(grid, viewerParent, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 300));
                Display.getInstance().getCurrent().setBackCommand(createBackCommand(viewerParent, grid));
            }
        });
        return btn;
    }

    public static final String SERVER_URL = "http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews";

    class ImageList implements ListModel<Image> {
        private int selection;
        private long[] imageIds;
        private EncodedImage[] images;
        private EventDispatcher listeners = new EventDispatcher();

        public void addImageId(int id) {
            long[] n = new long[imageIds.length + 1];
            EncodedImage[] nImages = new EncodedImage[n.length];
            System.arraycopy(imageIds, 0, n, 0, imageIds.length);
            System.arraycopy(images, 0, nImages, 0, images.length);
            n[imageIds.length] = id;
            imageIds = n;
            images = nImages;
            listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
        }

        public long getSelectedImageId() {
            return imageIds[selection];
        }

        public ImageList(long[] images) {
            this.imageIds = images;
            this.images = new EncodedImage[images.length];
        }

        public Image getItemAt(final int index) {
            if (images[index] == null) {
                images[index] = placeholder;
                Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        try {
                            images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
                            listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
                        } catch (IOException err) {
                            err.printStackTrace();
                        }
                    }
                });
            }
            return images[index];
        }

        public int getSize() {
            return imageIds.length;
        }

        public int getSelectedIndex() {
            return selection;
        }

        public void setSelectedIndex(int index) {
            WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
                public void onSucess(Integer value) {
                }

                public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
                }
            });
            selection = index;
        }

        public void addDataChangedListener(DataChangedListener l) {
            listeners.addListener(l);
        }

        public void removeDataChangedListener(DataChangedListener l) {
            listeners.removeListener(l);
        }

        public void addSelectionListener(SelectionListener l) {
        }

        public void removeSelectionListener(SelectionListener l) {
        }

        public void addItem(Image item) {
        }

        public void removeItem(int index) {
        }
    }
1
I added the java tag for syntax highlighting. I'm unsure what's not working for you. The code looks good and you seem to be in the right direction, its unclear what failed? - Shai Almog
yeahh, it works. But I hav hundreds of images from json & I am short of ideas on how to loop through the designated image in image Viewer, which is clicked by user. In the imageViewer code above, I'm stuck in defaultListModel. For eg one clicks img no.5 in the grid view, then one sud be able to swipe img no 6,7....100 and so on up to img no 4 using imgViewer. I cannot put all the images static like abov, right? So I need to loop the images frm json. Hope u get my problem... Thankyou for the reply... - Amrita Stha

1 Answers

0
votes

In the Photo Share demo (that's on github) I demonstrate something pretty similar. I used a custom list model that fetches the images to the ImageViewer dynamically.

The interesting bit is this list model where the images are downloaded dynamically as needed:

class ImageList implements ListModel<Image> {
    private int selection;
    private long[] imageIds;
    private EncodedImage[] images;
    private EventDispatcher listeners = new EventDispatcher();

    public void addImageId(long id) {
        long[] n = new long[imageIds.length + 1];
        EncodedImage[] nImages = new EncodedImage[n.length];
        System.arraycopy(imageIds, 0, n, 0, imageIds.length);
        System.arraycopy(images, 0, nImages, 0, images.length);
        n[imageIds.length] = id;
        imageIds = n;
        images = nImages;
        listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
    }

    public long getSelectedImageId() {
        return imageIds[selection];
    }

    public ImageList(long[] images) {
        this.imageIds = images;
        this.images = new EncodedImage[images.length];
    }

    public Image getItemAt(final int index) {
        if(images[index] == null) {
            images[index] = placeholder;
            Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    try {
                        images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
                        listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
                    } catch(IOException err) {
                        err.printStackTrace();
                    }
                }
            });
        } 
        return images[index];
    }

    public int getSize() {
        return imageIds.length;
    }

    public int getSelectedIndex() {
        return selection;
    }

    public void setSelectedIndex(int index) {
        WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
            public void onSucess(Integer value) {
                if(likeCount != null) {
                    likeCount.setText("" + value);
                    likeCount.getParent().revalidate();
                }
            }

            public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
            }
        });
        selection = index;
    }

    public void addDataChangedListener(DataChangedListener l) {
        listeners.addListener(l);
    }

    public void removeDataChangedListener(DataChangedListener l) {
        listeners.removeListener(l);
    }

    public void addSelectionListener(SelectionListener l) {
    }

    public void removeSelectionListener(SelectionListener l) {
    }

    public void addItem(Image item) {
    }

    public void removeItem(int index) {
    }
}