Search in sources :

Example 21 with Log

use of com.codename1.io.Log in project CodenameOne by codenameone.

the class JavaSEPort method createSkinsMenu.

private JMenu createSkinsMenu(final JFrame frm, final JMenu menu) throws MalformedURLException {
    JMenu m;
    if (menu == null) {
        m = new JMenu("Skins");
        m.setDoubleBuffered(true);
    } else {
        m = menu;
        m.removeAll();
    }
    final JMenu skinMenu = m;
    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
    String skinNames = pref.get("skins", DEFAULT_SKINS);
    if (skinNames != null) {
        if (skinNames.length() < DEFAULT_SKINS.length()) {
            skinNames = DEFAULT_SKINS;
        }
        ButtonGroup skinGroup = new ButtonGroup();
        StringTokenizer tkn = new StringTokenizer(skinNames, ";");
        while (tkn.hasMoreTokens()) {
            final String current = tkn.nextToken();
            String name = current;
            if (current.contains(":")) {
                try {
                    URL u = new URL(current);
                    File f = new File(u.getFile());
                    if (!f.exists()) {
                        continue;
                    }
                    name = f.getName();
                } catch (Exception e) {
                    continue;
                }
            } else {
                // remove the old builtin skins from the menu
                if (current.startsWith("/") && !current.equals("/iphone3gs.skin")) {
                    continue;
                }
            }
            String d = System.getProperty("dskin");
            JRadioButtonMenuItem i = new JRadioButtonMenuItem(name, name.equals(pref.get("skin", d)));
            i.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    if (netMonitor != null) {
                        netMonitor.dispose();
                        netMonitor = null;
                    }
                    if (perfMonitor != null) {
                        perfMonitor.dispose();
                        perfMonitor = null;
                    }
                    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                    pref.putBoolean("desktopSkin", false);
                    String mainClass = System.getProperty("MainClass");
                    if (mainClass != null) {
                        pref.put("skin", current);
                        deinitializeSync();
                        frm.dispose();
                        System.setProperty("reload.simulator", "true");
                    } else {
                        loadSkinFile(current, frm);
                        refreshSkin(frm);
                    }
                }
            });
            skinGroup.add(i);
            skinMenu.add(i);
        }
    }
    JMenuItem dSkin = new JMenuItem("Desktop.skin");
    dSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (netMonitor != null) {
                netMonitor.dispose();
                netMonitor = null;
            }
            if (perfMonitor != null) {
                perfMonitor.dispose();
                perfMonitor = null;
            }
            Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
            pref.putBoolean("desktopSkin", true);
            String mainClass = System.getProperty("MainClass");
            if (mainClass != null) {
                deinitializeSync();
                frm.dispose();
                System.setProperty("reload.simulator", "true");
            }
        }
    });
    skinMenu.addSeparator();
    skinMenu.add(dSkin);
    skinMenu.addSeparator();
    JMenuItem more = new JMenuItem("More...");
    skinMenu.add(more);
    more.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JDialog pleaseWait = new JDialog(frm, false);
            pleaseWait.setLocationRelativeTo(frm);
            pleaseWait.setTitle("Message");
            pleaseWait.setLayout(new BorderLayout());
            pleaseWait.add(new JLabel("  Please Wait...  "), BorderLayout.CENTER);
            pleaseWait.pack();
            pleaseWait.setVisible(true);
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    final JDialog d = new JDialog(frm, true);
                    d.setLocationRelativeTo(frm);
                    d.setTitle("Skins");
                    d.setLayout(new BorderLayout());
                    String userDir = System.getProperty("user.home");
                    final File skinDir = new File(userDir + "/.codenameone/");
                    if (!skinDir.exists()) {
                        skinDir.mkdir();
                    }
                    Vector data = new Vector();
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    final Document[] doc = new Document[1];
                    try {
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                        InputStream is = openSkinsURL();
                        doc[0] = db.parse(is);
                        NodeList skins = doc[0].getElementsByTagName("Skin");
                        for (int i = 0; i < skins.getLength(); i++) {
                            Node skin = skins.item(i);
                            NamedNodeMap attr = skin.getAttributes();
                            String url = attr.getNamedItem("url").getNodeValue();
                            int ver = 0;
                            Node n = attr.getNamedItem("version");
                            if (n != null) {
                                ver = Integer.parseInt(n.getNodeValue());
                            }
                            boolean exists = new File(skinDir.getAbsolutePath() + url).exists();
                            if (!(exists) || Integer.parseInt(pref.get(url, "0")) < ver) {
                                Vector row = new Vector();
                                row.add(new Boolean(false));
                                row.add(new ImageIcon(new URL(defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + attr.getNamedItem("icon").getNodeValue())));
                                row.add(attr.getNamedItem("name").getNodeValue());
                                if (exists) {
                                    row.add("Update");
                                } else {
                                    row.add("New");
                                }
                                data.add(row);
                            }
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    if (data.size() == 0) {
                        pleaseWait.setVisible(false);
                        JOptionPane.showMessageDialog(frm, "No New Skins to Install");
                        return;
                    }
                    Vector cols = new Vector();
                    cols.add("Install");
                    cols.add("Icon");
                    cols.add("Name");
                    cols.add("");
                    final DefaultTableModel tableModel = new DefaultTableModel(data, cols) {

                        @Override
                        public boolean isCellEditable(int row, int column) {
                            return column == 0;
                        }
                    };
                    JTable skinsTable = new JTable(tableModel) {

                        @Override
                        public Class<?> getColumnClass(int column) {
                            if (column == 0) {
                                return Boolean.class;
                            }
                            if (column == 1) {
                                return Icon.class;
                            }
                            return super.getColumnClass(column);
                        }
                    };
                    skinsTable.setRowHeight(112);
                    skinsTable.getTableHeader().setReorderingAllowed(false);
                    d.add(new JScrollPane(skinsTable), BorderLayout.CENTER);
                    JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    JButton download = new JButton("Download");
                    download.addActionListener(new ActionListener() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            final Vector toDowload = new Vector();
                            NodeList skins = doc[0].getElementsByTagName("Skin");
                            for (int i = 0; i < tableModel.getRowCount(); i++) {
                                if (((Boolean) tableModel.getValueAt(i, 0)).booleanValue()) {
                                    Node skin;
                                    for (int j = 0; j < skins.getLength(); j++) {
                                        skin = skins.item(j);
                                        NamedNodeMap attr = skin.getAttributes();
                                        if (attr.getNamedItem("name").getNodeValue().equals(tableModel.getValueAt(i, 2))) {
                                            String url = attr.getNamedItem("url").getNodeValue();
                                            String[] data = new String[2];
                                            data[0] = defaultCodenameOneComProtocol + "://www.codenameone.com/OTA" + url;
                                            data[1] = attr.getNamedItem("version").getNodeValue();
                                            toDowload.add(data);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (toDowload.size() > 0) {
                                final JDialog downloadMessage = new JDialog(d, true);
                                downloadMessage.setTitle("Downloading");
                                downloadMessage.setLayout(new FlowLayout());
                                downloadMessage.setLocationRelativeTo(d);
                                final JLabel details = new JLabel("<br><br>Details");
                                downloadMessage.add(details);
                                final JLabel progress = new JLabel("Progress<br><br>");
                                downloadMessage.add(progress);
                                new Thread() {

                                    @Override
                                    public void run() {
                                        for (Iterator it = toDowload.iterator(); it.hasNext(); ) {
                                            String[] data = (String[]) it.next();
                                            String url = data[0];
                                            details.setText(url.substring(url.lastIndexOf("/")));
                                            details.repaint();
                                            progress.setText("");
                                            progress.repaint();
                                            try {
                                                File skin = downloadSkin(skinDir, url, data[1], progress);
                                                if (skin.exists()) {
                                                    addSkinName(skin.toURI().toString());
                                                }
                                            } catch (Exception e) {
                                            }
                                        }
                                        downloadMessage.setVisible(false);
                                        d.setVisible(false);
                                        try {
                                            createSkinsMenu(frm, skinMenu);
                                        } catch (MalformedURLException ex) {
                                            Logger.getLogger(JavaSEPort.class.getName()).log(Level.SEVERE, null, ex);
                                        }
                                    }
                                }.start();
                                downloadMessage.pack();
                                downloadMessage.setSize(200, 70);
                                downloadMessage.setVisible(true);
                            } else {
                                JOptionPane.showMessageDialog(d, "Choose a Skin to Download");
                            }
                        }
                    });
                    p.add(download);
                    d.add(p, BorderLayout.SOUTH);
                    d.pack();
                    pleaseWait.dispose();
                    d.setVisible(true);
                }
            });
        }
    });
    skinMenu.addSeparator();
    JMenuItem addSkin = new JMenuItem("Add New...");
    skinMenu.add(addSkin);
    addSkin.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            FileDialog picker = new FileDialog(frm, "Add Skin");
            picker.setMode(FileDialog.LOAD);
            picker.setFilenameFilter(new FilenameFilter() {

                public boolean accept(File file, String string) {
                    return string.endsWith(".skin");
                }
            });
            picker.setModal(true);
            picker.setVisible(true);
            String file = picker.getFile();
            if (file != null) {
                if (netMonitor != null) {
                    netMonitor.dispose();
                    netMonitor = null;
                }
                if (perfMonitor != null) {
                    perfMonitor.dispose();
                    perfMonitor = null;
                }
                String mainClass = System.getProperty("MainClass");
                if (mainClass != null) {
                    Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                    pref.put("skin", picker.getDirectory() + File.separator + file);
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile(picker.getDirectory() + File.separator + file, frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    skinMenu.addSeparator();
    JMenuItem reset = new JMenuItem("Reset Skins");
    skinMenu.add(reset);
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent ae) {
            if (JOptionPane.showConfirmDialog(frm, "Are you sure you want to reset skins to default?", "Clean Storage", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class);
                pref.put("skins", DEFAULT_SKINS);
                String userDir = System.getProperty("user.home");
                final File skinDir = new File(userDir + "/.codenameone/");
                if (skinDir.exists()) {
                    File[] childs = skinDir.listFiles();
                    for (int i = 0; i < childs.length; i++) {
                        File child = childs[i];
                        if (child.getName().endsWith(".skin")) {
                            child.delete();
                        }
                    }
                }
                if (netMonitor != null) {
                    netMonitor.dispose();
                    netMonitor = null;
                }
                if (perfMonitor != null) {
                    perfMonitor.dispose();
                    perfMonitor = null;
                }
                String mainClass = System.getProperty("MainClass");
                if (mainClass != null) {
                    pref.put("skin", "/iphone3gs.skin");
                    deinitializeSync();
                    frm.dispose();
                    System.setProperty("reload.simulator", "true");
                } else {
                    loadSkinFile("/iphone3gs.skin", frm);
                    refreshSkin(frm);
                }
            }
        }
    });
    return skinMenu;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ActionEvent(java.awt.event.ActionEvent) Node(org.w3c.dom.Node) DefaultTableModel(javax.swing.table.DefaultTableModel) Document(org.w3c.dom.Document) FilenameFilter(java.io.FilenameFilter) PathIterator(java.awt.geom.PathIterator) Preferences(java.util.prefs.Preferences) Vector(java.util.Vector) NamedNodeMap(org.w3c.dom.NamedNodeMap) BufferedInputStream(com.codename1.io.BufferedInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) NodeList(org.w3c.dom.NodeList) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) Point(java.awt.Point) StringTokenizer(java.util.StringTokenizer) ActionListener(java.awt.event.ActionListener) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileDialog(java.awt.FileDialog)

Example 22 with Log

use of com.codename1.io.Log in project CodenameOne by codenameone.

the class Log method showLog.

/**
 * Places a form with the log as a TextArea on the screen, this method can
 * be attached to appear at a given time or using a fixed global key. Using
 * this method might cause a problem with further log output
 * @deprecated this method is an outdated method that's no longer supported
 */
public static void showLog() {
    try {
        String text = getLogContent();
        TextArea area = new TextArea(text, 5, 20);
        Form f = new Form("Log");
        f.setScrollable(false);
        final Form current = Display.getInstance().getCurrent();
        Command back = new Command("Back") {

            public void actionPerformed(ActionEvent ev) {
                current.show();
            }
        };
        f.addCommand(back);
        f.setBackCommand(back);
        f.setLayout(new BorderLayout());
        f.addComponent(BorderLayout.CENTER, area);
        f.show();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Also used : BorderLayout(com.codename1.ui.layouts.BorderLayout) TextArea(com.codename1.ui.TextArea) Form(com.codename1.ui.Form) Command(com.codename1.ui.Command) ActionEvent(com.codename1.ui.events.ActionEvent) IOException(java.io.IOException)

Example 23 with Log

use of com.codename1.io.Log in project CodenameOne by codenameone.

the class AndroidContactsManager method getAllContacts.

public Contact[] getAllContacts(Context activity, boolean withNumbers, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress) {
    HashMap<String, Contact> contacts = new HashMap<String, Contact>();
    ArrayList sortedContacts = new ArrayList();
    String selection = null;
    if (withNumbers) {
        selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1";
    }
    String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID, ContactsContract.Contacts.HAS_PHONE_NUMBER };
    ContentResolver contentResolver = activity.getContentResolver();
    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection, selection, null, "upper(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
    while (cursor.moveToNext()) {
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        Contact contact = new Contact();
        contact.setId(contactId);
        contact.setEmails(new Hashtable());
        // the contacts hash is for faster lookups and the sortedContacts will keep the order sorted
        Contact old = contacts.put(contactId, contact);
        sortedContacts.add(contact);
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        contact.setDisplayName(name);
        if (includesPicture) {
            String photoID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
            if (photoID != null) {
                InputStream input = loadContactPhoto(contentResolver, Long.parseLong(contactId), Long.parseLong(photoID));
                if (input != null) {
                    try {
                        contact.setPhoto(Image.createImage(input));
                    } catch (IOException ex) {
                        Logger.getLogger(AndroidContactsManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
    cursor.close();
    if (includesNumbers) {
        projection = new String[] { ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.IS_PRIMARY };
        Cursor pCur = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
        while (pCur.moveToNext()) {
            String id = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
            Contact contact = contacts.get(id);
            if (contact == null) {
                continue;
            }
            Hashtable phones = contact.getPhoneNumbers();
            if (phones == null) {
                phones = new Hashtable();
                contact.setPhoneNumbers(phones);
            }
            String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
            String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            boolean isPrimary = pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY)) != 0;
            if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME).equals(type)) {
                type = "home";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).equals(type)) {
                type = "mobile";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_WORK).equals(type)) {
                type = "work";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME).equals(type)) {
                type = "fax";
            } else {
                type = "other";
            }
            if (isPrimary) {
                contact.setPrimaryPhoneNumber(phone);
            }
            phones.put(type, phone);
        }
        pCur.close();
    }
    if (includesEmail) {
        projection = new String[] { ContactsContract.CommonDataKinds.Email.CONTACT_ID, ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };
        Cursor emailCur = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, null, null, null);
        while (emailCur.moveToNext()) {
            String id = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
            Contact contact = contacts.get(id);
            if (contact == null) {
                continue;
            }
            Hashtable emails = contact.getEmails();
            if (emails == null) {
                emails = new Hashtable();
                contact.setEmails(emails);
            }
            // This would allow you get several email addresses
            // if the email addresses were stored in an array
            String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            String type = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            boolean isPrimary = emailCur.getInt(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.IS_PRIMARY)) != 0;
            if (String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME).equals(type)) {
                type = "home";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_MOBILE).equals(type)) {
                type = "mobile";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_WORK).equals(type)) {
                type = "work";
            } else {
                type = "other";
            }
            if (isPrimary) {
                contact.setPrimaryEmail(email);
            }
            emails.put(type, email);
        }
        emailCur.close();
    }
    if (includesFullName) {
        String birthWhere = ContactsContract.Data.MIMETYPE + "= ? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
        String[] birthWhereParams = new String[] { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
        Cursor birthCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, birthWhere, birthWhereParams, null);
        while (birthCur.moveToNext()) {
            String id = birthCur.getString(birthCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.CONTACT_ID));
            Contact contact = contacts.get(id);
            if (contact == null) {
                continue;
            }
            String birth = birthCur.getString(birthCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
            Date bd = null;
            try {
                bd = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
                contact.setBirthday(bd.getTime());
            } catch (ParseException ex) {
            }
        }
        birthCur.close();
        String nameWhere = ContactsContract.Data.MIMETYPE + " = ?";
        String[] nameWhereParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
        projection = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME };
        Cursor nameCursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, nameWhere, nameWhereParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
        while (nameCursor.moveToNext()) {
            String id = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID));
            Contact contact = contacts.get(id);
            if (contact == null) {
                continue;
            }
            String given = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
            String family = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            String display = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
            if (given != null)
                contact.setFirstName(given);
            if (family != null)
                contact.setFamilyName(family);
            if (display != null)
                contact.setDisplayName(display);
        }
        nameCursor.close();
        String noteWhere = ContactsContract.Data.MIMETYPE + " = ?";
        String[] noteWhereParams = new String[] { ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
        projection = new String[] { ContactsContract.CommonDataKinds.Note.CONTACT_ID, ContactsContract.CommonDataKinds.Note.NOTE };
        Cursor noteCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, noteWhere, noteWhereParams, null);
        while (noteCur.moveToNext()) {
            String id = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.CONTACT_ID));
            Contact contact = contacts.get(id);
            if (contact == null) {
                continue;
            }
            String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
            contact.setNote(note);
        }
        noteCur.close();
    }
    if (includeAddress) {
        String addrWhere = ContactsContract.Data.MIMETYPE + " = ?";
        String[] addrWhereParams = new String[] { ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
        projection = new String[] { ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID, ContactsContract.CommonDataKinds.StructuredPostal.POBOX, ContactsContract.CommonDataKinds.StructuredPostal.STREET, ContactsContract.CommonDataKinds.StructuredPostal.CITY, ContactsContract.CommonDataKinds.StructuredPostal.REGION, ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, ContactsContract.CommonDataKinds.StructuredPostal.TYPE };
        Cursor addrCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, addrWhere, addrWhereParams, null);
        while (addrCur.moveToNext()) {
            String id = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID));
            Contact contact = contacts.get(id);
            if (contact == null) {
                continue;
            }
            Hashtable addresses = contact.getAddresses();
            if (addresses == null) {
                addresses = new Hashtable();
                contact.setAddresses(addresses);
            }
            Address address = new Address();
            // String poBox = addrCur.getString(
            // addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
            String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
            String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
            String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
            String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
            String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
            String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
            address.setCountry(country);
            address.setLocality(city);
            address.setPostalCode(postalCode);
            address.setRegion(state);
            address.setStreetAddress(street);
            if (String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME).equals(type)) {
                type = "home";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK).equals(type)) {
                type = "work";
            } else {
                type = "other";
            }
            addresses.put(type, address);
            contact.setAddresses(addresses);
        }
        addrCur.close();
    }
    Contact[] contactsArray = new Contact[sortedContacts.size()];
    sortedContacts.toArray(contactsArray);
    return contactsArray;
}
Also used : Address(com.codename1.contacts.Address) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Cursor(android.database.Cursor) Date(java.util.Date) Contact(com.codename1.contacts.Contact) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 24 with Log

use of com.codename1.io.Log in project CodenameOne by codenameone.

the class AndroidContactsManager method getContact.

public Contact getContact(Context activity, String id, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress) {
    Contact retVal = new Contact();
    retVal.setId(id);
    ContentResolver cr = activity.getContentResolver();
    String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID, ContactsContract.Contacts.HAS_PHONE_NUMBER };
    Cursor result = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, ContactsContract.Contacts._ID + " = ?", new String[] { id }, null);
    if (result.moveToFirst()) {
        String name = result.getString(result.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        retVal.setDisplayName(name);
        if (includesPicture) {
            String photoID = result.getString(result.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
            if (photoID != null) {
                InputStream input = loadContactPhoto(cr, Long.parseLong(id), Long.parseLong(photoID));
                if (input != null) {
                    try {
                        retVal.setPhoto(Image.createImage(input));
                    } catch (IOException ex) {
                        Logger.getLogger(AndroidContactsManager.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
    if (includesNumbers) {
        Hashtable phones = new Hashtable();
        if (Integer.parseInt(result.getString(result.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
            // String[] whereParameters = new String[]{id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
            projection = new String[] { ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.IS_PRIMARY };
            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
            while (pCur.moveToNext()) {
                String type = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                boolean isPrimary = pCur.getInt(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY)) != 0;
                if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME).equals(type)) {
                    type = "home";
                } else if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).equals(type)) {
                    type = "mobile";
                } else if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_WORK).equals(type)) {
                    type = "work";
                } else if (String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME).equals(type)) {
                    type = "fax";
                } else {
                    type = "other";
                }
                if (isPrimary) {
                    retVal.setPrimaryPhoneNumber(phone);
                }
                phones.put(type, phone);
            }
            retVal.setPhoneNumbers(phones);
            pCur.close();
        }
    }
    if (includesEmail) {
        Hashtable emails = new Hashtable();
        projection = new String[] { ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.IS_PRIMARY };
        Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
        while (emailCur.moveToNext()) {
            // This would allow you get several email addresses
            // if the email addresses were stored in an array
            String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            String type = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
            boolean isPrimary = emailCur.getInt(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.IS_PRIMARY)) != 0;
            if (String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME).equals(type)) {
                type = "home";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_MOBILE).equals(type)) {
                type = "mobile";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_WORK).equals(type)) {
                type = "work";
            } else {
                type = "other";
            }
            if (isPrimary) {
                retVal.setPrimaryEmail(email);
            }
            emails.put(type, email);
        }
        retVal.setEmails(emails);
        emailCur.close();
    }
    if (includesFullName) {
        String birthWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + "= ? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
        String[] birthWhereParams = new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
        Cursor birthCur = cr.query(ContactsContract.Data.CONTENT_URI, null, birthWhere, birthWhereParams, null);
        if (birthCur.moveToFirst()) {
            String birth = birthCur.getString(birthCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
            Date bd = null;
            try {
                bd = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
                retVal.setBirthday(bd.getTime());
            } catch (ParseException ex) {
            }
        }
        birthCur.close();
        String nameWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] nameWhereParams = new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
        projection = new String[] { ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME };
        Cursor nameCursor = cr.query(ContactsContract.Data.CONTENT_URI, projection, nameWhere, nameWhereParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
        while (nameCursor.moveToNext()) {
            String given = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
            String family = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            String display = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
            retVal.setFirstName(given);
            retVal.setFamilyName(family);
            retVal.setDisplayName(display);
        }
        nameCursor.close();
        String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] noteWhereParams = new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
        projection = new String[] { ContactsContract.CommonDataKinds.Note.NOTE };
        Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, projection, noteWhere, noteWhereParams, null);
        if (noteCur.moveToFirst()) {
            String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
            retVal.setNote(note);
        }
        noteCur.close();
    }
    if (includeAddress) {
        Hashtable addresses = new Hashtable();
        String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] addrWhereParams = new String[] { id, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
        projection = new String[] { ContactsContract.CommonDataKinds.StructuredPostal.POBOX, ContactsContract.CommonDataKinds.StructuredPostal.STREET, ContactsContract.CommonDataKinds.StructuredPostal.CITY, ContactsContract.CommonDataKinds.StructuredPostal.REGION, ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, ContactsContract.CommonDataKinds.StructuredPostal.TYPE };
        Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, projection, addrWhere, addrWhereParams, null);
        while (addrCur.moveToNext()) {
            Address address = new Address();
            String poBox = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
            String street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
            String city = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
            String state = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
            String postalCode = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
            String country = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
            String type = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
            address.setCountry(country);
            address.setLocality(city);
            address.setPostalCode(postalCode);
            address.setRegion(state);
            address.setStreetAddress(street);
            if (String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME).equals(type)) {
                type = "home";
            } else if (String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK).equals(type)) {
                type = "work";
            } else {
                type = "other";
            }
            addresses.put(type, address);
        }
        retVal.setAddresses(addresses);
        addrCur.close();
    }
    result.close();
    return retVal;
}
Also used : Address(com.codename1.contacts.Address) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Hashtable(java.util.Hashtable) IOException(java.io.IOException) Cursor(android.database.Cursor) Date(java.util.Date) Contact(com.codename1.contacts.Contact) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 25 with Log

use of com.codename1.io.Log in project CodenameOne by codenameone.

the class TestUtils method pointerDrag.

/**
 * A component drag on a given named component at x/y where x and y are <b>NOT pixels</b>
 * but rather a number between 0 to 1 representing the percentage within the component where the
 * event took place. E.g. For a 100x100 component a press within 10,5 would be 0.1f, 0.05f.
 * @param x the offset within the component as a number between 0 and 1
 * @param y the offset within the component as a number between 0 and 1
 * @param componentName the name of the component
 */
public static void pointerDrag(float x, float y, String componentName) {
    if (verbose) {
        log("pointerDrag(" + x + ", " + y + ", " + componentName + ")");
    }
    Component c = findByName(componentName);
    int actualX = c.getAbsoluteX() + (int) (x * c.getWidth());
    int actualY = c.getAbsoluteY() + (int) (y * c.getHeight());
    Display.getInstance().getCurrent().pointerDragged(actualX, actualY);
}
Also used : Component(com.codename1.ui.Component)

Aggregations

Component (com.codename1.ui.Component)9 IOException (java.io.IOException)9 TextArea (com.codename1.ui.TextArea)8 Label (com.codename1.ui.Label)4 InputStream (java.io.InputStream)4 Button (com.codename1.ui.Button)3 Form (com.codename1.ui.Form)3 BorderLayout (com.codename1.ui.layouts.BorderLayout)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ParseException (java.text.ParseException)3 Date (java.util.Date)3 TimerTask (java.util.TimerTask)3 Cursor (android.database.Cursor)2 Address (com.codename1.contacts.Address)2 Contact (com.codename1.contacts.Contact)2 BufferedInputStream (com.codename1.io.BufferedInputStream)2 Location (com.codename1.location.Location)2 Command (com.codename1.ui.Command)2 ActionEvent (com.codename1.ui.events.ActionEvent)2 SimpleDateFormat (java.text.SimpleDateFormat)2