来自json codenameone的ImageViewer图像循环

时间:2015-12-26 13:37:44

标签: java codenameone

我已经将问题编辑为您的建议但是捕获了空指针异常。我使用connectionRequest而不是multipartRequest,因为我不需要上传(只需要读取值frm json)。我的所有代码都在下面看看。

已编辑:例外

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)

代码:

 @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 个答案:

答案 0 :(得分:0)

Photo Share demothat's on github)中,我展示了一些非常相似的东西。我使用了一个自定义列表模型,可以动态地将图像提取到ImageViewer

有趣的是这个列表模型,根据需要动态下载图像:

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) {
    }
}