CHarris
CHarris

Reputation: 2793

using startsWith and replaceFirst not working for me.

I print all my phone contacts in the Android Monitor with the code below. Where a phone number begins with 00 I want to change the 00 to + . But it is not working. Can you tell me what is wrong please ?

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));

                        if (phoneNo.startsWith("00")) {
                            System.out.println(phoneNo.replaceFirst("00", "+"));
                        }

                        System.out.println("Name: " + name);
                        System.out.println("Phone No: " + phoneNo);

                    }
                    pCur.close();
                }
            }
        }

Upvotes: 2

Views: 147

Answers (1)

azizbekian
azizbekian

Reputation: 62189

replaceFirst() returns a String, it doesn't mutate the object. You should perform assignment:

phoneNo = phoneNo.replaceFirst("00", "+")

Upvotes: 3

Related Questions