Search in sources :

Example 26 with Result

use of com.codename1.processing.Result 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 27 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class BrowserComponent method fireBrowserNavigationCallbacks.

/**
 * Fires all of the registered browser navigation callbacks against the provided URL.
 * @param url The URL to fire the navigation callbacks against.
 * @return True if all of the callbacks say that they can browse.  False otherwise.
 */
public boolean fireBrowserNavigationCallbacks(String url) {
    boolean shouldNavigate = true;
    if (browserNavigationCallback != null && !browserNavigationCallback.shouldNavigate(url)) {
        shouldNavigate = false;
    }
    if (browserNavigationCallbacks != null) {
        for (BrowserNavigationCallback cb : browserNavigationCallbacks) {
            if (!cb.shouldNavigate(url)) {
                shouldNavigate = false;
            }
        }
    }
    if (!url.startsWith("javascript:") && url.indexOf(RETURN_URL_PREFIX) != -1) {
        // System.out.println("Received browser navigation callback "+url);
        String result = decodeURL(url.substring(url.indexOf(RETURN_URL_PREFIX) + RETURN_URL_PREFIX.length()), "UTF-8");
        // System.out.println("After decode "+result);
        Result structResult = Result.fromContent(result, Result.JSON);
        int callbackId = structResult.getAsInteger("callbackId");
        final String value = structResult.getAsString("value");
        final String type = structResult.getAsString("type");
        final String errorMessage = structResult.getAsString("errorMessage");
        final SuccessCallback<JSRef> callback = popReturnValueCallback(callbackId);
        if (jsCallbacks != null && jsCallbacks.contains(callback)) {
            // If this is a registered callback, then we treat it more like
            // an event listener, and we retain it for future callbacks.
            returnValueCallbacks.put(callbackId, callback);
        }
        if (callback != null) {
            if (errorMessage != null) {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        if (callback instanceof Callback) {
                            ((Callback) callback).onError(this, new RuntimeException(errorMessage), 0, errorMessage);
                        }
                    }
                });
            } else {
                Display.getInstance().callSerially(new Runnable() {

                    public void run() {
                        callback.onSucess(new JSRef(value, type));
                    }
                });
            }
        } else {
            Log.e(new RuntimeException("Received return value from javascript, but no callback could be found for that ID"));
        }
        shouldNavigate = false;
    }
    return shouldNavigate;
}
Also used : BrowserNavigationCallback(com.codename1.ui.events.BrowserNavigationCallback) Callback(com.codename1.util.Callback) SuccessCallback(com.codename1.util.SuccessCallback) BrowserNavigationCallback(com.codename1.ui.events.BrowserNavigationCallback) Result(com.codename1.processing.Result)

Example 28 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class SQLMap method select.

/**
 * Fetches the components from the database matching the given cmp description, the fields that aren't
 * null within the cmp will match the where clause
 * @param cmp the component to match
 * @param orderBy the column to order by, can be null to ignore order
 * @param ascending true to indicate ascending order
 * @param maxElements the maximum number of elements returned can be 0 or lower to ignore
 * @param page  the page within the query to match the max elements value
 * @return the result of the query
 */
public java.util.List<PropertyBusinessObject> select(PropertyBusinessObject cmp, Property orderBy, boolean ascending, int maxElements, int page) throws IOException, InstantiationException {
    String tableName = getTableName(cmp);
    StringBuilder createStatement = new StringBuilder("SELECT * FROM ");
    createStatement.append(tableName);
    ArrayList<Object> params = new ArrayList<Object>();
    createStatement.append(" WHERE ");
    boolean found = false;
    for (PropertyBase p : cmp.getPropertyIndex()) {
        if (p instanceof Property) {
            if (((Property) p).get() != null) {
                if (found) {
                    createStatement.append(" AND ");
                }
                found = true;
                params.add(((Property) p).get());
                createStatement.append(getColumnName(p));
                createStatement.append(" = ?");
            }
        }
    }
    // all properties are null undo the where append
    if (!found) {
        createStatement = new StringBuilder("SELECT * FROM ");
        createStatement.append(tableName);
    }
    if (orderBy != null) {
        createStatement.append(" ORDER BY ");
        createStatement.append(getColumnName(orderBy));
        if (!ascending) {
            createStatement.append(" DESC");
        }
    }
    if (maxElements > 0) {
        createStatement.append(" LIMIT ");
        createStatement.append(maxElements);
        if (page > 0) {
            createStatement.append(" OFFSET ");
            createStatement.append(page * maxElements);
        }
    }
    Cursor c = null;
    try {
        ArrayList<PropertyBusinessObject> response = new ArrayList<PropertyBusinessObject>();
        c = executeQuery(createStatement.toString(), params.toArray());
        while (c.next()) {
            PropertyBusinessObject pb = (PropertyBusinessObject) cmp.getClass().newInstance();
            for (PropertyBase p : pb.getPropertyIndex()) {
                Row currentRow = c.getRow();
                SqlType t = getSqlType(p);
                if (t == SqlType.SQL_EXCLUDE) {
                    continue;
                }
                Object value = t.getValue(currentRow, c.getColumnIndex(getColumnName(p)), p);
                if (p instanceof Property) {
                    ((Property) p).set(value);
                }
            }
            response.add(pb);
        }
        c.close();
        return response;
    } catch (Throwable t) {
        Log.e(t);
        if (c != null) {
            c.close();
        }
        if (t instanceof IOException) {
            throw ((IOException) t);
        } else {
            throw new IOException(t.toString());
        }
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) Cursor(com.codename1.db.Cursor) Row(com.codename1.db.Row)

Example 29 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class TestUtils method getToolbarCommands.

/**
 * Returns all the command objects from the toolbar in the order of left, right, overflow &amp; sidemenu
 * @return the set of commands
 */
public static Command[] getToolbarCommands() {
    Form f = Display.getInstance().getCurrent();
    Toolbar tb = f.getToolbar();
    ArrayList<Command> result = new ArrayList<Command>();
    addAllCommands(tb.getLeftBarCommands(), result);
    addAllCommands(tb.getRightBarCommands(), result);
    addAllCommands(tb.getOverflowCommands(), result);
    addAllCommands(tb.getSideMenuCommands(), result);
    Command[] carr = new Command[result.size()];
    result.toArray(carr);
    return carr;
}
Also used : Form(com.codename1.ui.Form) Command(com.codename1.ui.Command) ArrayList(java.util.ArrayList) Toolbar(com.codename1.ui.Toolbar)

Example 30 with Result

use of com.codename1.processing.Result in project CodenameOne by codenameone.

the class SnapshotThread method run.

public void run() {
    do {
        waitForSignal();
        if (done) {
            break;
        }
        BinaryBitmap bitmap = null;
        try {
            Player player = barCodeScanner.getPlayer();
            if (player == null) {
                break;
            }
            multimediaManager.setFocus(player);
            byte[] snapshot = takeSnapshot();
            if (snapshot == null) {
                break;
            }
            Image capturedImage = Image.createImage(snapshot, 0, snapshot.length);
            LuminanceSource source = new CN1ImageLuminanceSource(capturedImage);
            bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = null;
            if (barCodeScanner.type == BarCodeScanner.QRCODE) {
                Reader reader = new QRCodeReader();
                result = reader.decode(bitmap);
            } else {
                MultiFormatReader reader = new MultiFormatReader();
                result = reader.decodeBarcode(bitmap);
            }
            barCodeScanner.handleDecodedText(result);
        } catch (ReaderException re) {
            barCodeScanner.showError("Not found!");
        } catch (Exception e) {
            barCodeScanner.showError(e.getMessage());
        }
    } while (!done);
}
Also used : QRCodeReader(com.google.zxing.qrcode.QRCodeReader) Player(javax.microedition.media.Player) QRCodeReader(com.google.zxing.qrcode.QRCodeReader) Image(com.codename1.ui.Image) HybridBinarizer(com.google.zxing.common.HybridBinarizer) MediaException(javax.microedition.media.MediaException)

Aggregations

IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)5 EncodedImage (com.codename1.ui.EncodedImage)4 BorderLayout (com.codename1.ui.layouts.BorderLayout)4 Point (java.awt.Point)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Hashtable (java.util.Hashtable)4 Component (com.codename1.ui.Component)3 ActionEvent (com.codename1.ui.events.ActionEvent)3 ActionListener (com.codename1.ui.events.ActionListener)3 Intent (android.content.Intent)2 FileEncodedImage (com.codename1.components.FileEncodedImage)2 IntentResultListener (com.codename1.impl.android.IntentResultListener)2 Properties (com.codename1.io.Properties)2 Command (com.codename1.ui.Command)2 Container (com.codename1.ui.Container)2 Image (com.codename1.ui.Image)2 TextArea (com.codename1.ui.TextArea)2 Dimension (com.codename1.ui.geom.Dimension)2 GridLayout (com.codename1.ui.layouts.GridLayout)2