Android - phone number formatting and removing the country/area code - android

I have built an app where I loop through and collect the users phone contacts, my aim is to then use these numbers and query my parse database and look for records that contain the users contacts (this will be to check if any of the users contacts are a user of my app, a users phone number will be saved to my parse database when they register). The problem I've got is that when collecting the users contacts numbers they are returned in different formats, some +447966000000, some 07966000000, some 07 966000 000000, etc.
My question is, what would be the best way to format my numbers when saving them to the database and retrieving them from the users contacts so that all numbers are saved and retrieved in the same format so that when I do a conditional check on them they will be easy to compare?
I have downloaded phone Number Utils library but I am not sure what in the library could be used to do something like this.
Code so far:
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Toast.makeText(getApplicationContext(),name + " " + phoneNumber, Toast.LENGTH_LONG).show();
}
phones.close();

You can use PhoneNumberUtils.compare to compare and check if they are same or not.It returns true if they are same ignoring country codes etc.
Example:
PhoneNumberUtils.compare(context, 1234567890, +911234567890);
returns true

I have done it for Indian mobile number format
private String getNumber(String moNumber) {
Pattern special = Pattern.compile ("[!##$%&*()_+=|<>?{}\\[\\]~-]");
if (moNumber.isEmpty()||moNumber.length()<10) {
MydebugClass.showToast(getContext(), "Please input valid Number");
return null;
}else if (moNumber.length()>10 && !special.matcher(moNumber).find()){
String[] number=moNumber.split("");
StringBuilder stringBuilder=new StringBuilder();
for(int i=moNumber.length();i>moNumber.length()-10;i--){
stringBuilder.append(number[i]);
}
String reverse=new StringBuffer(stringBuilder).reverse().toString();
return reverse;
}else if(moNumber.length()>10&&special.matcher(moNumber).find()){
String numberOnly= moNumber.replaceAll("[^0-9]", "");
String[] number=numberOnly.split("");
StringBuilder stringBuilder=new StringBuilder();
for(int i=moNumber.length();i>moNumber.length()-10;i--){
stringBuilder.append(number[i]);
}
String reverse=new StringBuffer(stringBuilder).reverse().toString();
Log.d("mobilenumberspecial",reverse);
return reverse;
}
else {
return moNumber;
}
return null;
}

Related

How to match phone numbers from user's contact list if numbers are in different format?

I have a question about how to match phone numbers from user's contact list with phone numbers I have on remote database. Flow goes like this:
User registers on my app with his phone number (so does any other user)
App ask for contact permission
App sends contacts (phone numbers) to server to match against other registered numbers
The problem I have is that users register their phone number in format: +1XXXYYY.
For example person A registers with number +1222333. It might happen that person B has person A in his contact list as 0222333, how should I match that number? I can't know if prefix is "+1" or some other number.
I would like to recommend the libphonenumber library: https://github.com/google/libphonenumber
It can parse numbers and then output then to a standardized format. The official library has support for Java, C++ and JavaScript but there are also ports to other languages (see the bottom of the Github page)
Here is a quick example on how to format a national number as an international one in java
public static String getInternationalNumber(String localNumber, String regionCode) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = phoneUtil.parse(localNumber, regionCode);
}
catch (NumberParseException e) {
return null;
}
return (phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
}
You can probably assume that the numbers in the user's contact list have the same country code as the user.
To find which country code your user's phone number has you can do something like this (assuming it is an international number)
public static String getRegionCode(String phone) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber phoneNumber;
try {
phoneNumber = phoneUtil.parse(phone, "");
}
catch (NumberParseException e) {
return null;
}
return phoneUtil.getRegionCodeForNumber(phoneNumber);
}

compare phone number in android contacts database

I have a phone number with country code like +91XXXXXXXXXX. and a phone number in my android contacts database is in the form of XX XX XXXXXX. How to compare them in sqlite database query.
Any help would be appreciable....
I need this to update or delete the existing phone number in android database.
Note
Phone number can be of any country. Above is just the example.
you can try the code below
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode("Pass phone number here"));
Cursor c = getContentResolver().query(uri, new String[]{PhoneLookup.NUMBER}, null, null, null);
if(c.getCount()>0){
c.moveToFirst();
System.out.println(c.getString(c.getColumnIndex(PhoneLookup.NUMBER)));
}
c.close();
There can be multiple ways to do this:
As you see below here:
String yourInputString = "+91XXXXXXXXXX";
String dbContactString = "XX XX XXXXXX";
both have different format; so we must have to extract substring ("XXXXXXXXXX") from first string and also have to remove whitespaces ("XXXXXXXXXX") from the second string!
yourInputString = yourInputString.substring(2); // 2 is start index and result will be "XXXXXXXXXX"
dbContactString = dbContactString.replaceAll("\\s+",""); // replaces all whitespaces and result will be "XXXXXXXXXX"
now, both have same format so you can easily compare them with equals().
yourInputString.equals(dbContactString) is the way.
It returns true if yourInputString is equals to dbContactString in value. Else, it will return false.
Hope this helps!

StringBuilder seems to be out of capacity

my app retrieves VCards as Strings and puts all together to a big string via StringBuilder
public String getVcardStrings() throws Exception {
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
StringBuilder builder = new StringBuilder();
if (cursor.moveToFirst()) ;
do {
String s = getVCardStringFromContact(cursor);
L.d("VCARD", s);
builder.append(s);
} while (cursor.moveToNext());
cursor.close();
L.d("VCARD", "Output: \n" + builder.toString());
return builder.toString();
}
The output of each getVCardAsString() call is correct. It contains all data. but calling builder.toString() onlly returns the vcard data of 1,5 Contacts, which is about 4kb of text data and the rest is simply missing!
There is no exception and I´ve read that StringBuilders capacity theoretically reaches up to 4GB. Now my question is, what is happening here?
I'm pretty sure this is a false positive:
In other words the data is there but is being truncated by logcat.
This observation would seem to be validated by this define:
#define LOGGER_ENTRY_MAX_LEN (4*1024)
Which is bang-on 4KB and relates directly to what you are experiencing.
Write your output to a file to check if its actually there.

Sql lite gets all data sent to webservice JSon format in android?

I am creating local database I want to send all data sent to web service.
For example product name one column. Lots of product name is there. I want to send it.
& Product name = briyani,egg,rice
I got all details from database below i have mention code:
public String fetchMyRowid(String column_name)
{
String query = "select "+column_name+" From " + TABLErestaurant;
mCursor =db.rawQuery(query, null);
StringBuffer buf = new StringBuffer();
if (mCursor.moveToNext()) {
buf.append(mCursor.getString(0));
String str = buf.toString();
System.out.println("**************"+str);
}
return buf.toString();
}
}
return buf.toString();
}
In class :
HashMap<String, String> paramsvalue = new HashMap<String, String>(); paramsvalue.put("product_name", dataBase.fetchMyRowid(DatabaseHelper.columnproductname));
But I have some issue. I got only one product name. I need all product name. Can any one suggest solution for this.
wel come to stackoveflow,
Please check below link in that i have first select all table's recode then i have created one another method for get all columns value by row. after that i have marge all data in to JSON. this is idea you have to do similar way...
https://stackoverflow.com/a/10600440/1168654

Android get contact names by phone number efficiently for displaying in ListView

I'm creating an Sms app which contains a ListView in the Main Activity that displays all the conversations from the sms inbox. Each ListView row displays one conversation along with the phone number, message body and time of the message. Now instead of the phone number I want to display the contact name if it exists.
So far, for getting the contact name by phone number I found this code
private String getDisplayNameByNumber(String number) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor contactLookup = context.getContentResolver().query(uri, new String[] {ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);
int indexName = contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
try {
if (contactLookup != null && contactLookup.moveToNext()) {
number = contactLookup.getString(indexName);
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return number;
}
But this seems inefficient as it has to make a query for each contact name individually and lags the app. So instead I tried to get all the contact names from the phone and store it in an HashMap with the phone number as the key and the contact name as the value, so that I can get the contact name any time I want from the HashMap. But there seems to be another problem, the phone numbers are stored in many different formats, for eg:
+91 4324244434
04324244434
0224324244434
So how do I search for a phone number from the HashMap since it can be stored in many different formats?
Before you add the contact to the HashMap, use regular expression to grab the phone number. This way, no matter what format the phone number is in, the regular expression will be able to grab the appropriate number needed.
Once you grab the number, add it to the HashMap accordingly.
Hope that answers your question.

Categories

Resources