Goku
Goku

Reputation: 1663

Calling a phone number provided by GooglePlaces in Android

So using google places reference (detailed web-service) i retrieved a "formatted phone number" its in the form of (256) 922-0556. The goal is to call this number. The way I am trying is be using an intent. However, the number above is not a in the format to use Uri parse method. Anyone know a solution to call this number? Is there a different intent or a good way to turn this into Uri data? I have seen the opposite of this done like so: 1234567890 → (123) 456-7890

  String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);

But i want to do the reverse of this. any ideas or alternative solutions? Here is my code:

protected void onPostExecute(Boolean result){
                Intent callintent = new Intent(Intent.ACTION_CALL);
                callintent.setData(Uri.parse(phoneNum));
                try {
                    startActivity(callintent);
                }catch (Exception e) {e.printStackTrace();}
            }

Where phoneNum is a formatted phone number string retrieved from GooglePlaces via JSON

To expand on Peotropo's comment: is there a better way to replace values than the following?

phoneNum = phoneNum.replace(" ", ""); // gets rid of the spaces
phoneNum = phoneNum.replace("-", ""); // gets rid of the -
phoneNum = phoneNum.replace("(", ""); // gets rid of the (
phoneNum = phoneNum.replace(")", ""); // gets rid of the )

Upvotes: 0

Views: 132

Answers (2)

Joe
Joe

Reputation: 1

You don't need to do a string replace. You can use the Spannable code below to have your phone automatically recognize the number and call it. It adjusts for parentheses, spaces and dashes.

 // call the phone
 SpannableString callphone = new SpannableString("Phone: " + phone);
 callphone.setSpan(new StyleSpan(Typeface.BOLD), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 callphone.setSpan(new URLSpan("tel:"+phone), 7, 21, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
 TextView zphone = (TextView) findViewById(R.id.phone);
 zphone.setText(callphone);
 zphone.setMovementMethod(LinkMovementMethod.getInstance());

It will display

 Phone: (123) 456-7890

Where you see 7,21 in the code above it is saying to start at the 8th character, which is the ( and end at the 21st character which is the last digit in the phone number. Adjust it to display how you want. Nothing special to do in your view:

 <!-- Phone Number Label -->
 <TextView
    android:id="@+id/phone"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dip"/>

Upvotes: 0

piotrpo
piotrpo

Reputation: 12626

This is simple string. Use String.replace() method to remove extra chars. You can also use replaceAll method:

String phoneNumber = "(123)123-456465"
return phoneNumber.replaceAll("[^0-9]", "");

Not tested docs are here: replaceAll

Java regular expressions

Upvotes: 1

Related Questions