简体   繁体   中英

Null pointer exception while calling web service in codenameone

I am an Android developer, Currently I am trying to develop cross platform application, I have used flicker demo code, I just copied all images and all java files from the demo, Everything works fine except the web service call, I got null pointer exception when I am calling the web service

This is the web service link:

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json

Exception happened by this below code

 final URLImage image = URLImage.createToStorage(im, time, link, null);

If I copied the theme.res from flicker demo project I didn't faced this exception.

I found it happened by the theme.res But I can't found what component I want to add for the list to display the data and images

I have added error report below.Please anyone help me to find the solution

Expected null for key value!
java.lang.NullPointerException
    at com.codename1.ui.URLImage.<init>(URLImage.java:154)
    at com.codename1.ui.URLImage.createToStorage(URLImage.java:357)
    at com.agarangroup.flicker.Flickerdemo.createEntry(Flickerdemo.java:264)
    at com.agarangroup.flicker.Flickerdemo.access$3(Flickerdemo.java:254)
    at com.agarangroup.flicker.Flickerdemo$3$1.run(Flickerdemo.java:204)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1150)
    at com.codename1.ui.Display.edtLoopImpl(Display.java:1094)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:995)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Here I have attached my code

    package com.agarangroup.flicker;


import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.codename1.components.InfiniteProgress;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.Button;
import com.codename1.ui.Command;
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.EncodedImage;
import com.codename1.ui.FontImage;
import com.codename1.ui.Form;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.TextArea;
import com.codename1.ui.Toolbar;
import com.codename1.ui.URLImage;
import com.codename1.ui.animations.BubbleTransition;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;


public class Flickerdemo {

     private Form current;

        private static Resources res;

        public void init(Object context) {
            res = UIManager.initFirstTheme("/themes");
            // Pro only feature, uncomment if you have a pro subscription
            //Log.bindCrashProtection(true);
        }

        public void start() {
            if (current != null) {
                current.show();
                return;
            }
            Form main = createMainForm();
            main.show();
        }


    @SuppressWarnings("deprecation")
    private Form createMainForm() {
         Form main = new Form("Flickr tags");
         main.setLayout(new BorderLayout());
         Toolbar bar = new Toolbar();
         main.setToolBar(bar);
         addCommandsToToolbar(bar);

         TextArea desc = new TextArea();
         desc.setText("This is a Flickr tags demo, the demo uses the Toolbar to arrange the Form Commands.\n\n"
                 + "Select \"Cats\" to view the latest photos that were tagged as \"Cats\".\n\n"
                 + "Select \"Dogs\" to view the latest photos that were tagged as \"Dogs\".\n\n"
                 + "Select \"Search\" to enter your own tags for search.");
         desc.setEditable(false);

         main.addComponent(BorderLayout.CENTER, desc);
         return main;
        }

    private void addCommandsToToolbar(Toolbar tool) {
        // TODO Auto-generated method stub

        tool.addCommandToSideMenu(new Command("Main") {

            @Override
            public void actionPerformed(ActionEvent evt) {
                Form main = createMainForm();
                main.show();
            }

        });


          tool.addCommandToSideMenu(new Command("Cats") {

                @SuppressWarnings("deprecation")
                @Override
                public void actionPerformed(ActionEvent evt) {
                    final Form cats = new Form("Cats");
                    cats.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
                    cats.setScrollableY(true);
                    final CustomToolbar bar = new CustomToolbar(true);
                    cats.getContentPane().addScrollListener(bar);
                    cats.setToolBar(bar);
                    addCommandsToToolbar(bar);

                    Image icon = FontImage.createMaterial(FontImage.MATERIAL_REFRESH, UIManager.getInstance().getComponentStyle("TitleCommand"));                
                    bar.addCommandToRightBar(new Command("", icon) {

                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            Display.getInstance().callSerially(new Runnable() {

                                public void run() {
                                    updateScreenFromNetwork(cats, "cat");
                                    cats.revalidate();
                                }
                            });
                        }
                    });
                    bar.addCommandToOverflowMenu(new Command("Clear ") {

                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            Container cnt = (Container) cats.getContentPane();
                            cnt.removeAll();
                            //add back the big angry cat image
                            try {
                                Image im = Image.createImage("/cat.jpg");
                                im = im.scaledWidth(Display.getInstance().getDisplayWidth());
                                Label bigCat = new Label(im);
                                cats.addComponent(bigCat);

                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                            cnt.revalidate();
                        }
                    });
                    bar.addCommandToOverflowMenu(new Command("About Cats ") {

                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            if (Dialog.show("Cats", "Cats are meowing", "Ok", "Cancel")) {
                                try {
                                    Media m = MediaManager.createMedia(Display.getInstance().getResourceAsStream(getClass(), "/Cats.mp3"), "audio/mp3");
                                    m.play();
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }

                    });

                    //add the big angry cat image
                    try {
                        Image im = Image.createImage("/cat.jpg");
                        im = im.scaledWidth(Display.getInstance().getDisplayWidth());
                        Label bigCat = new Label(im);
                        cats.addComponent(bigCat);

                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }

                    cats.show();

                    updateScreenFromNetwork(cats, "cat");

                }

            });

    }

    public void stop() {
        current = Display.getInstance().getCurrent();
        if(current instanceof Dialog) {
            ((Dialog)current).dispose();
            current = Display.getInstance().getCurrent();
        }
    }

    public void destroy() {
    }

    private static void updateScreenFromNetwork(final Form f, final String tag) {
        //show a waiting progress on the Form
        addWaitingProgress(f);

        //run the networking on a background thread
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            @SuppressWarnings("rawtypes")
            public void run() {
                final List entries = ServerAccess.getEntriesFromFlickrService(tag);

                //build the UI entries on the EDT using the callSerially
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        Container cnt = f.getContentPane();
                        for (int i = 0; i < entries.size(); i++) {
                            Map data = (Map) entries.get(i);
                            cnt.addComponent(createEntry(data, i));
                        }
                        f.revalidate();
                        //remove the waiting progress from the Form
                        removeWaitingProgress(f);
                    }
                });

            }
        });

    }

    private static void addWaitingProgress(Form f) {
        addWaitingProgress(f, true, f.getContentPane());
    }

    private static void addWaitingProgress(Form f, boolean center, Container pane) {
        pane.setVisible(false);
        Container cnt = f.getLayeredPane();
        BorderLayout bl = new BorderLayout();
        bl.setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE);
        cnt.setLayout(bl);
        if (center) {
            cnt.addComponent(BorderLayout.CENTER, new InfiniteProgress());
        } else {
            Container top = new Container();
            BorderLayout bl1 = new BorderLayout();
            bl1.setCenterBehavior(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE);
            top.setLayout(bl1);
            top.addComponent(BorderLayout.CENTER, new InfiniteProgress());

            cnt.addComponent(BorderLayout.NORTH, top);
        }
    }

    private static void removeWaitingProgress(Form f) {
        removeWaitingProgress(f, f.getContentPane());
    }

    private static void removeWaitingProgress(Form f, Container pane) {
        Container cnt = f.getLayeredPane();
        cnt.removeAll();
        pane.setVisible(true);
    }

    /**
     * This method builds a UI Entry dynamically from a data Map object.
     */
    @SuppressWarnings("rawtypes")
    private static Component createEntry(Map data, final int index) {
        final Container cnt = new Container(new BorderLayout());
        cnt.setUIID("MultiButton");
        Button icon = new Button();
        icon.setUIID("Label");
        //take the time and use it as the identifier of the image
        String time = (String) data.get("date_taken");
        String link = (String) ((Map) data.get("media")).get("m");

        EncodedImage im = (EncodedImage) res.getImage("flickr.png");
        final URLImage image = URLImage.createToStorage(im, time, link);
        icon.setIcon(image);
        icon.setName("ImageButton" + index);
        icon.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {

                Dialog d = new Dialog();
                //d.setDialogUIID("Container");                
                d.setLayout(new BorderLayout());
                Label l = new Label(image);
                l.setUIID("ImagePop");
                d.add(BorderLayout.CENTER, l);
                d.setDisposeWhenPointerOutOfBounds(true);
                d.setTransitionInAnimator(new BubbleTransition(300, "ImageButton" + index));
                d.setTransitionOutAnimator(new BubbleTransition(300, "ImageButton" + index));
                d.show();
            }
        });

        cnt.addComponent(BorderLayout.WEST, icon);

        Container center = new Container(new BorderLayout());

        Label des = new Label((String) data.get("title"));
        des.setUIID("MultiLine1");
        center.addComponent(BorderLayout.NORTH, des);
        Label author = new Label((String) data.get("author"));
        author.setUIID("MultiLine2");
        center.addComponent(BorderLayout.SOUTH, author);

        cnt.addComponent(BorderLayout.CENTER, center);
        return cnt;
    }
}

Two solutions :

Try to remove the last ' null ' parameter here :
final URLImage image = URLImage.createToStorage(im, time, link, null);
It will don't use the Image Adapter parameter and don't throw an exception.
(ImageAdapter is usefull to resize your image after loading it. Without the parameter, ImageAdapter.SCALE_TO_FILL is used and your downloaded Image will be resize to fill your placeholder Image) Explained here : javadoc

Or :

Do you have imported the specified im ? (used in your URLImage.createToStorage)
This Image is a placeholder while your urlimage is downloaded. Try to import a multi-image in your theme.res and then, create it in your code like this :

try{
       Resources res = Resources.openLayered("/theme");
       Image im = res.getImage("myImportedImage");
       final URLImage image = URLImage.createToStorage(im, time, link);
    }
catch(Exception e){
       e.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM