Search in sources :

Example 6 with Cursor

use of com.codename1.db.Cursor in project CodenameOne by codenameone.

the class ResetableTextWatcher method startEditing.

/**
 * Start editing the given text-area
 * This method is executed on the UI thread, so UI manipulation is safe here.
 * @param activity Current running activity
 * @param textArea The TextAreaData instance that wraps the CN1 TextArea that our internal EditText needs to overlap.  We use
 *                 a TextAreaData so that the text area properties can be accessed off the EDT safely.
 * @param codenameOneInputType One of the input type constants in com.codename1.ui.TextArea
 * @param initialText The text that appears in the Codename One text are before the call to startEditing
 * @param isEditedFieldSwitch if true, then special case for async edit mode - the native editing is already active, no need to show
 *                            native field, just change the connected field
 */
private synchronized void startEditing(Activity activity, TextAreaData textArea, String initialText, int codenameOneInputType, final boolean isEditedFieldSwitch) {
    int txty = lastTextAreaY = textArea.getAbsoluteY() + textArea.getScrollY();
    int txtx = lastTextAreaX = textArea.getAbsoluteX() + textArea.getScrollX();
    lastTextAreaWidth = textArea.getWidth();
    lastTextAreaHeight = textArea.getHeight();
    int paddingTop = 0;
    int paddingLeft = textArea.paddingLeft;
    int paddingRight = textArea.paddingRight;
    int paddingBottom = textArea.paddingBottom;
    if (textArea.isTextField) {
        switch(textArea.getVerticalAlignment()) {
            case Component.BOTTOM:
                paddingTop = textArea.getHeight() - textArea.paddingBottom - textArea.fontHeight;
                break;
            case Component.CENTER:
                paddingTop = textArea.getHeight() / 2 - textArea.fontHeight / 2;
                break;
            default:
                paddingTop = textArea.paddingTop;
                break;
        }
    } else {
        paddingTop = textArea.paddingTop;
    }
    int id = activity.getResources().getIdentifier("cn1Style", "attr", activity.getApplicationInfo().packageName);
    if (!isEditedFieldSwitch) {
        mEditText = new EditView(activity, textArea.textArea, this, id);
    } else {
        mEditText.switchToTextArea(textArea.textArea);
    }
    if (textArea.getClientProperty("blockCopyPaste") != null || Display.getInstance().getProperty("blockCopyPaste", "false").equals("true")) {
        // The code below is taken from this stackoverflow answer: http://stackoverflow.com/a/22756538/756809
        if (android.os.Build.VERSION.SDK_INT < 11) {
            mEditText.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

                @Override
                public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                    menu.clear();
                }
            });
        } else {
            mEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                public void onDestroyActionMode(ActionMode mode) {
                }

                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    return false;
                }
            });
        }
    } else if (isEditedFieldSwitch) {
        // reset copy-paste protection
        if (android.os.Build.VERSION.SDK_INT < 11) {
            mEditText.setOnCreateContextMenuListener(null);
        } else {
            mEditText.setCustomSelectionActionModeCallback(null);
        }
    }
    if (!isEditedFieldSwitch) {
        mEditText.addTextChangedListener(mEditText.mTextWatcher);
    }
    mEditText.setBackgroundDrawable(null);
    mEditText.setFocusableInTouchMode(true);
    mEditLayoutParams = new FrameLayout.LayoutParams(0, 0);
    // Set the appropriate gravity so that the left and top margins will be
    // taken into account
    mEditLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
    mEditLayoutParams.setMargins(txtx, txty, 0, 0);
    mEditLayoutParams.width = textArea.getWidth();
    mEditLayoutParams.height = textArea.getHeight();
    mEditText.setLayoutParams(mEditLayoutParams);
    if (textArea.isRTL()) {
        mEditText.setGravity(Gravity.RIGHT | Gravity.TOP);
    } else {
        mEditText.setGravity(Gravity.LEFT | Gravity.TOP);
    }
    mEditText.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
    Component nextDown = textArea.nextDown;
    boolean imeOptionTaken = true;
    int ime = EditorInfo.IME_FLAG_NO_EXTRACT_UI;
    if (textArea.isSingleLineTextArea()) {
        if (textArea.getClientProperty("searchField") != null) {
            mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_SEARCH);
        } else {
            if (textArea.getClientProperty("sendButton") != null) {
                mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_SEND);
            } else {
                if (textArea.getClientProperty("goButton") != null) {
                    mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_GO);
                } else {
                    if (textArea.isTextField && textArea.getDoneListener() != null) {
                        mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_DONE);
                    } else if (nextDown != null && nextDown instanceof TextArea && ((TextArea) nextDown).isEditable() && ((TextArea) nextDown).isEnabled()) {
                        mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_NEXT);
                    } else {
                        mEditText.setImeOptions(ime | EditorInfo.IME_ACTION_DONE);
                        imeOptionTaken = false;
                    }
                }
            }
        }
    }
    mEditText.setSingleLine(textArea.isSingleLineTextArea());
    mEditText.setAdapter((ArrayAdapter<String>) null);
    mEditText.setText(initialText);
    if (!textArea.isSingleLineTextArea() && textArea.textArea.isGrowByContent() && textArea.textArea.getGrowLimit() > -1) {
        defaultMaxLines = mEditText.getMaxLines();
        mEditText.setMaxLines(textArea.textArea.getGrowLimit());
    }
    if (textArea.nativeHintBool && textArea.getHint() != null) {
        mEditText.setHint(textArea.getHint());
    }
    if (!isEditedFieldSwitch) {
        addView(mEditText, mEditLayoutParams);
    }
    invalidate();
    setVisibility(VISIBLE);
    bringToFront();
    mEditText.requestFocus();
    Object nativeFont = textArea.nativeFont;
    if (nativeFont == null) {
        nativeFont = impl.getDefaultFont();
    }
    Paint p = (Paint) ((AndroidImplementation.NativeFont) nativeFont).font;
    mEditText.setTypeface(p.getTypeface());
    mEditText.setTextScaleX(p.getTextScaleX());
    mEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, p.getTextSize());
    int fgColor = textArea.fgColor;
    mEditText.setTextColor(Color.rgb(fgColor >> 16, (fgColor & 0x00ff00) >> 8, (fgColor & 0x0000ff)));
    boolean password = false;
    if ((codenameOneInputType & TextArea.PASSWORD) == TextArea.PASSWORD) {
        codenameOneInputType = codenameOneInputType ^ TextArea.PASSWORD;
        password = true;
    }
    if (textArea.isSingleLineTextArea()) {
        mEditText.setInputType(getAndroidInputType(codenameOneInputType));
        // if not ime was explicity requested and this is a single line textfield of type ANY add the emoji keyboard.
        if (!imeOptionTaken && codenameOneInputType == TextArea.ANY) {
            mEditText.setInputType(getAndroidInputType(codenameOneInputType) | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
        }
        if (Display.getInstance().getProperty("andAddComma", "false").equals("true") && (codenameOneInputType & TextArea.DECIMAL) == TextArea.DECIMAL) {
            defaultKeyListener = mEditText.getKeyListener();
            mEditText.setKeyListener(DigitsKeyListener.getInstance("0123456789.,"));
        }
    }
    if (password) {
        int type = mInputTypeMap.get(codenameOneInputType, InputType.TYPE_CLASS_TEXT);
        if ((type & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) == InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) {
            type = type ^ InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
        }
        // turn off suggestions for passwords
        mEditText.setInputType(type | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
        mEditText.setTransformationMethod(new MyPasswordTransformationMethod());
    }
    int maxLength = textArea.maxSize;
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(maxLength);
    mEditText.setFilters(FilterArray);
    mEditText.setSelection(mEditText.getText().length());
    showVirtualKeyboard(true);
    if (Boolean.FALSE.equals(textArea.getClientProperty("android.cursorVisible"))) {
        // This provides an imperfect workaround for this issue:
        // https://github.com/codenameone/CodenameOne/issues/2317
        // Blinking cursor causes text to disappear on some versions of android
        // Can't seem to find how to detect whether device is affected, so
        // just providing a client property to disable the blinking cursor
        // on a particular text field.
        mEditText.setCursorVisible(false);
    }
/*
        // Leaving this hack here for posterity.  It seems that this manually
        // blinking cursor causes the paste menu to disappear
        // https://github.com/codenameone/CodenameOne/issues/2147
        // Removing the hack below, fixes this issue.  And in the test device
        // I'm using the blinking of text doesn't seem to occur, so perhaps
        // it was fixed via other means.  Test device:
        // Name: Samsung Galaxy S3 (T-Mobile)
        //    OS: 4.3
        //    Manufacturer: Samsung
        //    Model: 4.3
        //    Chipset: armeabi-v7a 1512MHz
        //    Memory: 16000000000
        //    Heap: 256000000
        //    Display: 720 x 1280
        //
        // UPDATE Feb. 13, 2018:
        // This issue seems to be still present in some devices, but it isn't clear even
        // how to detect it.
        // Issue reported and reproduced here https://github.com/codenameone/CodenameOne/issues/2317
        // Issue has been observed in a Virtual Box installation with 5.1.1, but
        // cannot be reproduced in a Nexus 5 running 5.1.1.
        // 
        if (Build.VERSION.SDK_INT < 21) {
            // HACK!!!  On Android 4.4, it seems that the natural blinking cursor
            // causes text to disappear when it blinks.  Manually blinking the
            // cursor seems to work around this issue, so that's what we do here.
            // This issue is described here: http://stackoverflow.com/questions/41305052/textfields-content-disappears-during-typing?noredirect=1#comment69977316_41305052
            mEditText.setCursorVisible(false);
            final boolean[] cursorVisible = new boolean[]{false};
            if (cursorTimer != null) {
                cursorTimer.cancel();
            }
            cursorTimer = new Timer();
            cursorTimerTask = new TimerTask() {
                public void run() {
                    AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            EditView v = mEditText;
                            if (v != null) {
                                cursorVisible[0] = !cursorVisible[0];
                                v.setCursorVisible(cursorVisible[0]);
                            }
                        }
                    });

                }
            };
            cursorTimer.schedule(cursorTimerTask, 100, 500);
        }
        */
}
Also used : InputFilter(android.text.InputFilter) TextArea(com.codename1.ui.TextArea) ContextMenu(android.view.ContextMenu) MenuItem(android.view.MenuItem) Paint(android.graphics.Paint) View(android.view.View) AutoCompleteTextView(android.widget.AutoCompleteTextView) Paint(android.graphics.Paint) ActionMode(android.view.ActionMode) FrameLayout(android.widget.FrameLayout) ContextMenuInfo(android.view.ContextMenu.ContextMenuInfo) ContextMenu(android.view.ContextMenu) Menu(android.view.Menu) Component(com.codename1.ui.Component)

Example 7 with Cursor

use of com.codename1.db.Cursor in project CodenameOne by codenameone.

the class ResetableTextWatcher method showTextEditorAgain.

/**
 * Shows the native text field again after it has been hidden in async edit mode.
 */
private void showTextEditorAgain() {
    if (!mIsEditing || !isTextEditorHidden()) {
        return;
    }
    textEditorHidden = false;
    final TextArea ta = mEditText.mTextArea;
    // changed since the native aread was hidden.
    synchronized (this) {
        inputBuffer = new ArrayList<TextChange>();
    }
    // We are probably not on the EDT.  We need to be on the EDT to
    // safely get text from the textarea for synchronization.
    Display.getInstance().callSerially(new Runnable() {

        public void run() {
            // and the editing text area hasn't changed since we issued this call.
            if (mIsEditing && mEditText != null && mEditText.mTextArea == ta) {
                final String text = ta.getText();
                final int cursorPos = ta.getCursorPosition();
                // Now that we have our text from the CN1 text area, we need to be on the
                // Android UI thread in order to set the text of the native text editor.
                impl.getActivity().runOnUiThread(new Runnable() {

                    public void run() {
                        // and the editing text area hasn't changed since we issued this call.
                        if (mIsEditing && mEditText != null && mEditText.mTextArea == ta) {
                            // so that we don't find it in an inconsistent state.
                            synchronized (InPlaceEditView.this) {
                                // Let's record the cursor positions of the native
                                // text editor in case we need to use them after synchronizing
                                // with the CN1 textarea.
                                int start = cursorPos;
                                int end = cursorPos;
                                /*
                                    if (!inputBuffer.isEmpty()) {
                                        // If the input buffer isn't empty, then our start
                                        // and end positions will be "wonky"
                                        start = end = inputBuffer.get(0).atPos;

                                        // If the first change was a delete, then the atPos
                                        // will point to the beginning of the deleted section
                                        // so we need to adjust the end point to be *after*
                                        // the deleted section to begin.
                                        if (inputBuffer.get(0).deleteLength > 0) {
                                            end = start = end + inputBuffer.get(0).deleteLength;
                                        }
                                    }
                                    */
                                StringBuilder buf = new StringBuilder();
                                buf.append(text);
                                // Loop through any pending changes in the input buffer
                                // (I.e. key strokes that have occurred since we initiated
                                // this async callback hell!!)
                                List<TextChange> tinput = inputBuffer;
                                if (tinput != null) {
                                    for (TextChange change : tinput) {
                                        // end.
                                        if (change.textToAppend != null) {
                                            if (end >= 0 && end <= buf.length()) {
                                                buf.insert(end, change.textToAppend);
                                                end += change.textToAppend.length();
                                                start = end;
                                            } else {
                                                buf.append(change.textToAppend);
                                                end = buf.length();
                                                start = end;
                                            }
                                        } else // The change is "deleted" text.
                                        if (change.deleteLength > 0) {
                                            if (end >= change.deleteLength && end <= buf.length()) {
                                                buf.delete(end - change.deleteLength, end);
                                                end -= change.deleteLength;
                                                start = end;
                                            } else if (end > 0 && end < change.deleteLength) {
                                                buf.delete(0, end);
                                                end = 0;
                                                start = end;
                                            }
                                        }
                                    }
                                }
                                // Important:  Clear the input buffer so that the TextWatcher
                                // knows to stop filling it up.  We only need the inputBuffer
                                // to keep input between the original showTextEditorAgain() call
                                // and here.
                                inputBuffer = null;
                                mEditText.setText(buf.toString());
                                if (start < 0 || start > mEditText.getText().length()) {
                                    start = mEditText.getText().length();
                                }
                                if (end < 0 || end > mEditText.getText().length()) {
                                    end = mEditText.getText().length();
                                }
                                // Update the caret in the edit text field so we can continue.
                                mEditText.setSelection(start, end);
                            }
                        }
                    }
                });
            }
        }
    });
    reLayoutEdit(true);
    repaintTextEditor(true);
}
Also used : TextArea(com.codename1.ui.TextArea) Paint(android.graphics.Paint)

Example 8 with Cursor

use of com.codename1.db.Cursor 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 9 with Cursor

use of com.codename1.db.Cursor 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 10 with Cursor

use of com.codename1.db.Cursor 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)

Aggregations

TextArea (com.codename1.ui.TextArea)4 IOException (java.io.IOException)4 Cursor (android.database.Cursor)3 InputStream (java.io.InputStream)3 ParseException (java.text.ParseException)3 Paint (android.graphics.Paint)2 Address (com.codename1.contacts.Address)2 Contact (com.codename1.contacts.Contact)2 Cursor (com.codename1.db.Cursor)2 TextField (com.codename1.ui.TextField)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 SimpleDateFormat (java.text.SimpleDateFormat)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 Hashtable (java.util.Hashtable)2 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)1 Uri (android.net.Uri)1 InputFilter (android.text.InputFilter)1 ActionMode (android.view.ActionMode)1 ContextMenu (android.view.ContextMenu)1