Example usage for android.telephony PhoneNumberUtils formatNumber

List of usage examples for android.telephony PhoneNumberUtils formatNumber

Introduction

In this page you can find the example usage for android.telephony PhoneNumberUtils formatNumber.

Prototype

@Deprecated
public static String formatNumber(String source) 

Source Link

Document

Breaks the given number down and formats it according to the rules for the country the number is from.

Usage

From source file:Main.java

/**
 * Looks up a contacts display name by contact id - if not found, the
 * address (phone number) will be formatted and returned instead.
 *///from   www .jav a2s  .co m
public static String getPersonName(Context context, String id, String address) {

    // Check for id, if null return the formatting phone number as the name
    if (id == null || "".equals(id.trim())) {
        if (address != null && !"".equals(address.trim())) {
            return PhoneNumberUtils.formatNumber(address);
        } else {
            return null;
        }
    }

    Cursor cursor = context.getContentResolver().query(Uri.withAppendedPath(Contacts.CONTENT_URI, id),
            new String[] { Contacts.DISPLAY_NAME }, null, null, null);

    if (cursor != null) {
        try {
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                String name = cursor.getString(0);
                return name;
            }
        } finally {
            cursor.close();
        }
    }

    if (address != null) {
        return PhoneNumberUtils.formatNumber(address);
    }

    return null;
}

From source file:Main.java

public static String getPersonNameFromNumber(Context context, String box, String address) {
    if (address == null) {
        return "unknown";
    }//w w w.j  a v a2 s. c om
    if (!box.equalsIgnoreCase("draft")) {
        Cursor cursor = context.getContentResolver().query(
                Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address)),
                new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.getCount() > 0) {
                    cursor.moveToFirst();
                    String name = cursor.getString(0);
                    return name;
                }
            } finally {
                cursor.close();
            }
        }
    }
    if (address != null) {
        return PhoneNumberUtils.formatNumber(address);
    }
    return "unknown";
}

From source file:Main.java

public static String getRecentCallsInfo(Context context) {
    StringBuilder stringBuilder = new StringBuilder();
    Cursor cursor = context.getContentResolver().query(Calls.CONTENT_URI, null, null, null,
            Calls.DATE + " DESC");
    int number = cursor.getColumnIndex(Calls.NUMBER);
    int name = cursor.getColumnIndex(Calls.CACHED_NAME);
    int type = cursor.getColumnIndex(Calls.TYPE);
    int date = cursor.getColumnIndex(Calls.DATE);
    int duration = cursor.getColumnIndex(Calls.DURATION);
    while (cursor.moveToNext()) {
        String phNumber = cursor.getString(number);
        String cachedName = cursor.getString(name);
        String callType = cursor.getString(type);
        String callDuration = cursor.getString(duration);

        String callDate = cursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));

        String dir;/*  w  w w.j  a v a2 s. c o  m*/
        int dircode = Integer.parseInt(callType);
        switch (dircode) {
        case Calls.OUTGOING_TYPE:
            dir = "OUTGOING";
            break;
        case Calls.INCOMING_TYPE:
            dir = "INCOMING";
            break;
        case Calls.MISSED_TYPE:
            dir = "MISSED";
            break;
        default:
            dir = "UNKNOWN " + dircode;
        }

        stringBuilder.append("\nPhone Number:--- ").append(phNumber).append("\nPhone formatted:--- ")
                .append(PhoneNumberUtils.formatNumber(phNumber)).append("\nCached name:--- ").append(cachedName)
                .append("\nCall Type:--- ").append(dir).append("\nCall Date:--- ").append(callDayTime)
                .append("\nCall duration in sec :--- ").append(callDuration)
                .append("\n----------------------------------");
    }
    cursor.close();
    return stringBuilder.toString();
}

From source file:com.callrecorder.android.FileHelper.java

private static String getContactName(String phoneNum, Context context) {
    @SuppressWarnings("deprecation")
    String res = PhoneNumberUtils.formatNumber(phoneNum);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context
            .checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        return res;
    }/* w  w  w .  ja v a  2  s  . c  om*/
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER };
    Cursor names = context.getContentResolver().query(uri, projection, null, null, null);
    if (names == null)
        return res;

    int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
    int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

    if (names.getCount() > 0) {
        names.moveToFirst();
        do {
            String name = names.getString(indexName);
            String number = cleanNumber(names.getString(indexNumber));

            if (PhoneNumberUtils.compare(number, phoneNum)) {
                res = name;
                break;
            }
        } while (names.moveToNext());
    }
    names.close();

    return res;
}

From source file:com.callrecorder.android.RecordingsAdapter.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View rowView = convertView;// ww  w .jav  a 2s .c  om
    if (rowView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.record_row, parent, false);
    }
    final TextView titleView = (TextView) rowView.findViewById(R.id.recording_title);
    final TextView dateView = (TextView) rowView.findViewById(R.id.recording_date);
    final TextView numberView = (TextView) rowView.findViewById(R.id.recording_number);
    Recording entry = list.get(position);

    String phoneNumber = entry.getPhoneNumber();
    if (phoneNumber.matches("^[\\d]+$")) {
        //noinspection deprecation
        phoneNumber = PhoneNumberUtils.formatNumber(phoneNumber);
    } else {
        phoneNumber = context.getString(R.string.withheld_number);
    }

    dateView.setText(DateFormat.getDateTimeInstance().format(entry.getDate()));
    titleView.setText(entry.getUserName());
    numberView.setText(phoneNumber);

    return rowView;
}

From source file:org.pixmob.droidlink.ui.EventCursorAdapter.java

@Override
public void bindView(View v, Context context, Cursor cursor) {
    final int state = cursor.getInt(cursor.getColumnIndexOrThrow(STATE));
    final String name = cursor.getString(cursor.getColumnIndexOrThrow(NAME));
    String number = cursor.getString(cursor.getColumnIndexOrThrow(NUMBER));
    final long date = cursor.getLong(cursor.getColumnIndexOrThrow(CREATED));

    if (number != null) {
        number = PhoneNumberUtils.formatNumber(number);
    }//from   w  ww.  java2s  .  co  m

    final int type = cursor.getInt(cursor.getColumnIndexOrThrow(TYPE));
    final Integer typeResourceId = EVENT_ICONS.get(type);

    final CharSequence eventDate = DateUtils.getRelativeTimeSpanString(date, System.currentTimeMillis(),
            DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);

    final String message = cursor.getString(cursor.getColumnIndexOrThrow(MESSAGE));

    final String eventName;
    final String eventNumber;
    if (number == null) {
        eventName = context.getString(R.string.unknown_number);
        eventNumber = EMPTY;
    } else if (name == null) {
        eventName = number;
        eventNumber = EMPTY;
    } else {
        eventName = name;
        eventNumber = number;
    }

    TextView tv = (TextView) v.findViewById(R.id.event_name);
    tv.setText(eventName);

    tv = (TextView) v.findViewById(R.id.event_number);
    tv.setText(eventNumber);

    tv = (TextView) v.findViewById(R.id.event_date);
    tv.setText(eventDate);

    tv = (TextView) v.findViewById(R.id.event_message);
    tv.setText(message);

    ImageView iv = (ImageView) v.findViewById(R.id.event_icon);
    if (typeResourceId != null) {
        iv.setImageResource(typeResourceId);
        iv.setVisibility(View.VISIBLE);
    } else {
        iv.setVisibility(View.INVISIBLE);
    }

    iv = (ImageView) v.findViewById(R.id.event_state);
    if (state == EventsContract.PENDING_DELETE_STATE) {
        iv.setImageResource(R.drawable.pending_delete);
        iv.setVisibility(View.VISIBLE);
    } else if (state == EventsContract.PENDING_UPLOAD_STATE) {
        iv.setImageResource(R.drawable.pending_upload);
        iv.setVisibility(View.VISIBLE);
    } else {
        iv.setVisibility(View.GONE);
    }

    v.setTag(TAG_ID, cursor.getString(cursor.getColumnIndex(_ID)));
}

From source file:com.waz.zclient.pages.main.profile.preferences.dialogs.VerifyPhoneNumberPreferenceFragment.java

@Nullable
@Override//from w w  w . j  av a2 s .  c om
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final String number = PhoneNumberUtils.formatNumber(getArguments().getString(ARG_PHONE, ""));
    final View view = inflater.inflate(R.layout.fragment_preference_phone_number_verification, container,
            false);

    final TextInputLayout verificationCodeInputLayout = ViewUtils.getView(view, R.id.til__verification_code);
    verificationCodeInputLayout.setErrorEnabled(true);
    final View backButton = ViewUtils.getView(view, R.id.tv__back_button);
    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });
    final View okButton = ViewUtils.getView(view, R.id.tv__ok_button);
    okButton.setEnabled(false);
    okButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String code = getVerificationCode();
            getStoreFactory().getProfileStore().submitCode(number, code,
                    new ZMessagingApi.PhoneNumberVerificationListener() {
                        @Override
                        public void onVerified(KindOfVerification kindOfVerification) {
                            dismiss();
                        }

                        @Override
                        public void onVerificationFailed(KindOfVerification kindOfVerification, int errorCode,
                                String message, String label) {
                            if (AppEntryError.PHONE_INVALID_REGISTRATION_CODE.correspondsTo(errorCode, label)) {
                                verificationCodeInputLayout.setError(getString(
                                        AppEntryError.PHONE_INVALID_REGISTRATION_CODE.headerResource));
                            } else {
                                verificationCodeInputLayout.setError(
                                        getString(AppEntryError.PHONE_REGISTER_GENERIC_ERROR.headerResource));
                            }
                        }
                    });
        }
    });
    final TextView changeNumberButton = ViewUtils.getView(view, R.id.tv__change_number_button);
    changeNumberButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getContainer() == null) {
                return;
            }
            dismiss();
            getContainer().changePhoneNumber(number);
        }
    });
    final TextView resendButton = ViewUtils.getView(view, R.id.tv__resend_button);
    resendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resendButton.animate().alpha(0f).start();
            getStoreFactory().getProfileStore().resendPhoneVerificationCode(number,
                    new ZMessagingApi.PhoneConfirmationCodeRequestListener() {

                        @Override
                        public void onConfirmationCodeSent(KindOfAccess kindOfAccess) {
                            resendButton.animate().alpha(1f).start();
                        }

                        @Override
                        public void onPasswordExists(KindOfAccess kindOfAccess) {

                        }

                        @Override
                        public void onConfirmationCodeSendingFailed(KindOfAccess kindOfAccess, int code,
                                String message, String label) {
                            resendButton.animate().alpha(1f).start();
                            AppEntryUtil.showErrorDialog(getActivity(),
                                    AppEntryError.PHONE_REGISTER_GENERIC_ERROR, null);
                        }
                    });
        }
    });
    final TextView verificationDescription = ViewUtils.getView(view, R.id.tv__verification_description);
    verificationDescription
            .setText(getString(R.string.pref__account_action__phone_verification__description, number));

    final EditText firstNumberEditText = ViewUtils.getView(view, R.id.et__verification_code__1);
    final EditText secondNumberEditText = ViewUtils.getView(view, R.id.et__verification_code__2);
    final EditText thirdNumberEditText = ViewUtils.getView(view, R.id.et__verification_code__3);
    final EditText fourthNumberEditText = ViewUtils.getView(view, R.id.et__verification_code__4);
    final EditText fifthNumberEditText = ViewUtils.getView(view, R.id.et__verification_code__5);
    final EditText sixthNumberEditText = ViewUtils.getView(view, R.id.et__verification_code__6);

    textBoxes = new LinkedList<>(Arrays.asList(firstNumberEditText, secondNumberEditText, thirdNumberEditText,
            fourthNumberEditText, fifthNumberEditText, sixthNumberEditText));
    for (int i = 0; i < textBoxes.size(); i++) {
        final EditText textBox = textBoxes.get(i);
        final int finalI = i;
        textBox.setTypeface(TypefaceUtils.getTypeface(getString(R.string.wire__typeface__bold)));
        textBox.addTextChangedListener(new OnTextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                verificationCodeInputLayout.setError(null);
                final String val = textBox.getText().toString().trim();
                final char c;
                if (TextUtils.isEmpty(val)) {
                    c = ' ';
                } else {
                    c = val.charAt(0);
                }
                verificationCode[finalI] = c;
                final boolean wasDelete = c == ' ';
                if (!jumpToNextEmptyTextBox(wasDelete)) {
                    okButton.setEnabled(true);
                    if (finalI == textBoxes.size()) {
                        okButton.requestFocus();
                    }
                } else {
                    okButton.setEnabled(false);
                }
            }
        });
    }

    return view;
}

From source file:com.textuality.lifesaver2.Columns.java

public JSONObject cursorToJSON(Cursor cursor) {
    setColumns(cursor);/*from w  w w  .  ja v a2  s.co  m*/
    JSONObject json = new JSONObject();
    try {
        for (int i = 0; i < mNames.length; i++) {
            int col = mColumns[i];
            if (cursor.isNull(col))
                continue;
            switch (mTypes[i]) {
            case STRING:
                String str = cursor.getString(col);
                if (mNames[i].equals("number")) {
                    json.put("name", mNameFinder.find(str));
                } else if (mNames[i].equals("address")) {
                    str = PhoneNumberUtils.formatNumber(str);
                    str = PhoneNumberUtils.stripSeparators(str);
                    json.put("name", mNameFinder.find(str));
                }
                json.put(mNames[i], str);
                break;
            case INT:
                json.put(mNames[i], cursor.getInt(col));
                break;
            case LONG:
                long val = cursor.getLong(col);
                json.put(mNames[i], val);
                if (mNames[i].equals("date")) {
                    json.put("tzoffset", mTZ.getOffset(val));
                }
                break;
            case FLOAT:
                json.put(mNames[i], cursor.getFloat(col));
                break;
            case DOUBLE:
                json.put(mNames[i], cursor.getDouble(col));
                break;
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    return json;
}

From source file:at.flack.activity.NewSMSContactActivity.java

public void openMessageActivity(Activity activity, int arg2) {
    if (arg2 < 0)
        return;/*from w w  w.  j a v a  2  s  .c  o m*/
    Intent smsIntent = new Intent(activity, MessageOverview.class);
    ContactAdapter adapter = ((ContactAdapter) ((HeaderViewListAdapter) contactList.getAdapter())
            .getWrappedAdapter());
    smsIntent.putExtra("CONTACT_NUMBER", ((ContactModel) adapter.getItem(arg2)).getLastMessage());
    smsIntent.putExtra("CONTACT_NAME", ((ContactModel) (adapter.getItem(arg2))).getTitle());
    smsIntent.putExtra("CONTACT_ID", ((ContactModel) (adapter.getItem(arg2))).getThreadID());

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Bitmap temp = ((ContactModel) (adapter.getItem(arg2))).getPicture();
    if (temp != null) {
        temp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bytes = stream.toByteArray();

        smsIntent.putExtra("profilePicture", bytes);
    }
    try {
        KeyEntity key = KeySafe.getInstance(this)
                .get(PhoneNumberUtils.formatNumber(contacts.get(arg2).getLastMessage()));
        if (key != null)
            smsIntent.putExtra("CONTACT_KEY", key);
    } catch (NullPointerException e) {
    }
    activity.startActivityForResult(smsIntent, 2);
}

From source file:at.flack.SMSMainActivity.java

public void openMessageActivity(Activity activity, int arg2) {
    if (MainActivity.getContacts() == null)
        return;//from w  ww  .j av a 2 s  .  com
    if (arg2 < 0)
        return;
    Intent smsIntent = new Intent(activity, MessageOverview.class);
    smsIntent.putExtra("CONTACT_NUMBER", MainActivity.getContacts().get(arg2).mAddress);
    smsIntent.putExtra("CONTACT_NAME", MainActivity.getListItems().get(arg2).getTitle());
    smsIntent.putExtra("CONTACT_ID", MainActivity.getContacts().get(arg2).mThreadID);

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    Bitmap temp = MainActivity.getContacts().get(arg2).fetchThumbnail(activity);
    if (temp != null) {
        temp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bytes = stream.toByteArray();

        smsIntent.putExtra("profilePicture", bytes);
    }
    try {
        KeyEntity key = KeySafe.getInstance(activity)
                .get(PhoneNumberUtils.formatNumber(MainActivity.getContacts().get(arg2).mAddress));
        if (key != null && key.getVersion() != KeyEntity.ECDH_PRIVATE_KEY)
            smsIntent.putExtra("CONTACT_KEY", key);
    } catch (NullPointerException e) {
    }

    activity.startActivityForResult(smsIntent, 2);
}