Search code examples
codenameone

A trouble with Uber Clone


Hi Guys: I´m trying with Uber Clone code and I´m using Netbeans . I have two questions: 1).- In the countryPickerForm Listing 4.12 (The Listing number is the book´s listing "Create an Uber Clone..."); Netbeans marks me an error,("Cannot find symbol variable CommonCode"), of course, in the CommonCode object, i don´t know what library to use

´´´

public class CountryPickerForm extends Form{
    //@SuppressWarnings("LeakingThisInConstructor")
    public CountryPickerForm(Button sourceButton, Resources Flag){
        super(BoxLayout.y());
        **CommonCode.initBlackTitleForm(this,"Select a Country", val-> search(val));**
        Image blankIcon = Image.createImage(100, 70, 0);

´´´ 2).- And the second question: What is te correct place to the Listing (5.22) "Toogling the "WhereTo?" UI when focus changes". I placed it Inside the MapForm class outside from any method, but Neatbeans marks me an error: "< identifier > expected. Ilegal start of type " This is the code:

from.addFocusListener(new FocusListener(){
    public void focusGained(Component cmp){
        fromSelected.setIcon(square);
        if(layer.getComponentCount()> 1){
            Component c = layer.getComponentAt(1);
            c.setY(getDisplayHeight());
            layer.animateUnlayout(200,150,() ->{
            c.remove();
            revalidate();
        });
      }
    }
    
    public void focusLost(){
        fromSelected.setIcon(circle);
    }
});
to.addFocusListener(new FocusListener(){
    public void focusGained(Component cmp){
        fromSelected.setIcon(circle):
        toSelected.setIcon(square);
        showToNavigationBar(layer);
    }
    public void focusLost(Component cmp){
        toSelecte3dsetIcon(circle);
    }
});

Thanks Guys!!!!


Solution

  • CommonCode was somehow lost in one of the edits to the book. It's a part of the downloadable zip listed at the start of the book and should be there. This is the full listing of that class:

    package com.codename1.apps.uberclone.forms;
    
    import com.codename1.apps.uberclone.server.UserService;
    import com.codename1.components.MultiButton;
    import com.codename1.io.Log;
    import com.codename1.ui.Button;
    import static com.codename1.ui.CN.*;
    import com.codename1.ui.Command;
    import com.codename1.ui.Container;
    import com.codename1.ui.Display;
    import com.codename1.ui.FontImage;
    import com.codename1.ui.Form;
    import com.codename1.ui.Graphics;
    import com.codename1.ui.Image;
    import com.codename1.ui.Label;
    import com.codename1.ui.TextField;
    import com.codename1.ui.Toolbar;
    import com.codename1.ui.animations.CommonTransitions;
    import com.codename1.ui.animations.Transition;
    import com.codename1.ui.events.ActionEvent;
    import com.codename1.ui.events.ActionListener;
    import com.codename1.ui.layouts.BorderLayout;
    import com.codename1.ui.layouts.LayeredLayout;
    import com.codename1.ui.plaf.Style;
    import com.codename1.util.LazyValue;
    import com.codename1.util.SuccessCallback;
    import java.io.IOException;
    
    /**
     * Common code for construction and initialization of various classes e.g. the side menu logic etc.
     *
     * @author Shai Almog
     */
    public class CommonCode {
        private static Image avatar;
        public static Image getAvatar(SuccessCallback<Image> avatarChanged) {
            if(avatar == null) {
                int size = convertToPixels(10);
                Image temp = Image.createImage(size, size, 0xff000000);
                Graphics g = temp.getGraphics();
                g.setAntiAliased(true);
                g.setColor(0xffffff);
                g.fillArc(0, 0, size, size, 0, 360);
                Object mask = temp.createMask();
                UserService.fetchAvatar(i -> {
                    avatar = i.fill(size, size).applyMask(mask);
                    avatarChanged.onSucess(avatar);
                });
                if(avatar != null) {
                    return avatar;
                }
                Style s = new Style();
                s.setFgColor(0xc2c2c2);
                s.setBgTransparency(255);
                s.setBgColor(0xe9e9e9);
                FontImage x = FontImage.createMaterial(FontImage.MATERIAL_PERSON, s, size);
                avatar = x.fill(size, size);
                if(avatar instanceof FontImage) {
                    avatar = ((FontImage)avatar).toImage();
                }
                avatar = avatar.applyMask(mask);
            }
            return avatar;
        }
        
        public static Image setAvatar(String imageFile) {
            int size = convertToPixels(10);
            Image temp = Image.createImage(size, size, 0xff000000);
            Graphics g = temp.getGraphics();
            g.setAntiAliased(true);
            g.setColor(0xffffff);
            g.fillArc(0, 0, size, size, 0, 360);
            Object mask = temp.createMask();
            
            try {
                Image img = Image.createImage(imageFile);
                avatar = img.fill(size, size).applyMask(mask);
            } catch(IOException err) {
                // this is unlikely as we just grabbed the image...
                Log.e(err);
            }
            return avatar;
        }
        
        public static MultiButton createEntry(char icon, String title) {
            MultiButton b = new MultiButton(title);
            b.setUIID("Container");
            b.setUIIDLine1("WhereToButtonLine1");
            b.setIconUIID("WhereToButtonIcon");
            FontImage.setMaterialIcon(b, icon);
            return b;
        }
        
        public static MultiButton createEntry(char icon, String title, String subtitle) {
            MultiButton b = new MultiButton(title);
            b.setTextLine2(subtitle);
            b.setUIID("Container");
            b.setUIIDLine1("WhereToButtonLineNoBorder");
            b.setUIIDLine2("WhereToButtonLine2");
            b.setIconUIID("WhereToButtonIcon");
            FontImage.setMaterialIcon(b, icon);
            return b;
        }
        
        
        public static Label createSeparator() {
            Label sep = new Label("", "WhereSeparator");
            sep.setShowEvenIfBlank(true);
            return sep;
        }
        
        public static void constructSideMenu(Toolbar tb) {
            Button userAndAvatar = new Button("Shai Almog", "AvatarBlock");
            userAndAvatar.setIcon(getAvatar(i -> userAndAvatar.setIcon(i)));
            userAndAvatar.setGap(convertToPixels(3));
            userAndAvatar.addActionListener(e -> new EditAccountForm().show());
            tb.addComponentToSideMenu(userAndAvatar);
            
            MultiButton uberForBusiness = new MultiButton("Do you Uber for business?");
            uberForBusiness.setTextLine2("Tap to create your business profile");
            uberForBusiness.setUIID("UberForBusinessBackground");
            uberForBusiness.setUIIDLine1("UberForBusinessLine1");
            uberForBusiness.setUIIDLine2("UberForBusinessLine2");
            tb.addComponentToSideMenu(uberForBusiness);
            
            tb.addCommandToSideMenu("Payment", null, e -> {});
            tb.addCommandToSideMenu("Your Trips", null, e -> {});
            tb.addCommandToSideMenu("Help", null, e -> {});
            tb.addCommandToSideMenu("Free Rides", null, e -> {});
            tb.addCommandToSideMenu("Settings", null, e -> new SettingsForm().show());
            
            Button legalButton = new Button("Legal", "Legal");
            Container legal = BorderLayout.centerCenterEastWest(null, new Label("v4.178.1001", "VersionNumber"), legalButton);
            legal.setLeadComponent(legalButton);
            legal.setUIID("SideNavigationPanel");
            tb.setComponentToSideMenuSouth(legal);
        } 
        
        
        /**
         * Initializes a form with a black background title animation style
         * @param f the form
         */
        public static void initBlackTitleForm(Form f, String title, SuccessCallback<String> searchResults) {
            Form backTo = getCurrentForm();
            f.getContentPane().setScrollVisible(false);
            Button back = new Button("", "TitleCommand");
            removeTransitionsTemporarily(backTo);
            back.addActionListener(e -> backTo.showBack());
            back.getAllStyles().setFgColor(0xffffff);
            FontImage.setMaterialIcon(back, FontImage.MATERIAL_ARROW_BACK);
                    
            f.setBackCommand(new Command("") {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    backTo.showBack();
                }
            });
    
            Container searchBack = null;
            if(searchResults != null) {
                Button search = new Button("", "TitleCommand");
                search.getAllStyles().setFgColor(0xffffff);
                FontImage.setMaterialIcon(search, FontImage.MATERIAL_SEARCH);
                search.addActionListener(e -> {
                    
                });
                searchBack = BorderLayout.north(
                    BorderLayout.centerEastWest(null, search, back));
            } else {
                searchBack = BorderLayout.north(
                    BorderLayout.centerEastWest(null, null, back));
            }
            
            Label titleLabel = new Label(title, "WhiteOnBlackTitle");
    
            titleLabel.getAllStyles().setMarginTop(back.getPreferredH());
            titleLabel.getAllStyles().setMarginUnit(Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
            
            f.getToolbar().setTitleComponent(LayeredLayout.encloseIn(searchBack, titleLabel));
            
            f.getAnimationManager().onTitleScrollAnimation(titleLabel.createStyleAnimation("WhiteOnBlackTitleLeftMargin", 200));
            
            f.setTransitionInAnimator(CommonTransitions.createCover(CommonTransitions.SLIDE_VERTICAL, false, 300));
            f.setTransitionOutAnimator(CommonTransitions.createUncover(CommonTransitions.SLIDE_VERTICAL, true, 300));        
        }
        
        public static void removeTransitionsTemporarily(final Form f) {
            final Transition originalOut = f.getTransitionOutAnimator();
            final Transition originalIn = f.getTransitionInAnimator();
            f.setTransitionOutAnimator(CommonTransitions.createEmpty());
            f.setTransitionInAnimator(CommonTransitions.createEmpty());
            f.addShowListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    f.setTransitionOutAnimator(originalOut);
                    f.setTransitionInAnimator(originalIn);
                    f.removeShowListener(this);
                }
            });
        }
    }
    

    The second listing appears in MapForm in showNavigationToolbar. This code goes through some additional refactoring later on and looks like this:

    void showNavigationToolbar() {
        final Container layer = getLayeredPane(MapForm.class, true);
        final Container pinLayer = createPinLayer(layer);
        Button back = new Button("", "TitleCommand");
        FontImage.setMaterialIcon(back, FontImage.MATERIAL_ARROW_BACK);
    
        CompletionContainer cc = new CompletionContainer();
        AutoCompleteAddressInput from = new AutoCompleteAddressInput("Current Location", "From", layer, cc);
        AutoCompleteAddressInput to = new AutoCompleteAddressInput("", "Where To?", layer, cc);
        from.setCurrentLocation(LocationService.getCurrentLocation());
                        
        Image circle = createCircle();
        Label fromSelected = new Label(circle);
        Label toSelected = new Label(square);
        
        SearchService.nameMyCurrentLocation(LocationService.getCurrentLocation(), name -> from.setTextNoEvent(name));
        to.requestFocus();
        lastFocused = to;
        from.addFocusListener(createFromFocusListener(fromSelected, from, circle));
        to.addFocusListener(createToFocusListener(fromSelected, circle, toSelected, to));
        
        addMapListener((source, zoom, center) -> onMapChangeEvent(center));
        
        Container navigationToolbar = BoxLayout.encloseY(back, 
                BorderLayout.centerCenterEastWest(from, null, fromSelected), 
                BorderLayout.centerCenterEastWest(to, null, toSelected)
        );
        navigationToolbar.setUIID("WhereToToolbar");
        navigationToolbar.getUnselectedStyle().setBgPainter((g1, rect) -> 
            paintWhereToToolbarBackground(g1, layer, rect, fromSelected, circle, toSelected)
        );
        
        cc.addCompletionListener(e -> 
            onCompletionEvent(to, from, pinLayer, navigationToolbar, layer));
    
        back.addActionListener(e -> 
            onBackFromNavigation(pinLayer, navigationToolbar, layer));
        layer.add(NORTH, navigationToolbar);
        navigationToolbar.setWidth(getDisplayWidth());
        navigationToolbar.setHeight(getPreferredH());
        navigationToolbar.setY(-navigationToolbar.getHeight());
        getAnimationManager().addAnimation(layer.createAnimateLayout(200), 
                    () -> cc.showCompletionBar(layer));
    }
    
    private FocusListener createToFocusListener(final Label fromSelected, Image circle, final Label toSelected, AutoCompleteAddressInput to) {
        return new FocusListener() {
            @Override
            public void focusGained(Component cmp) {
                fromSelected.setIcon(circle);
                toSelected.setIcon(square);
                lastFocused = to;
            }
            
            @Override
            public void focusLost(Component cmp) {
                toSelected.setIcon(circle);
            }
        };
    }
    
    private FocusListener createFromFocusListener(final Label fromSelected, AutoCompleteAddressInput from, Image circle) {
        return new FocusListener() {
            @Override
            public void focusGained(Component cmp) {
                fromSelected.setIcon(square);
                lastFocused = from;
            }
            
            @Override
            public void focusLost(Component cmp) {
                fromSelected.setIcon(circle);
            }
        };
    }