Match number to contact in android app - java

Have an android app that prints with a toast pop up, and reads out a received message with tts. I use "String origin = smsMessage[0].getOriginatingAddress();" to get the phone number of the sender.
I want to query the contacts list on the phone, so if the received number matches any contacts, it will print & read out the name of the sender instead. Otherwise, if the number is not recognised, it will default back to just printing & reading the OriginatingAddress number.
Iv'e looked at How can I query Android contact based on a phone number? - but not quite sure howto go about it.

Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(origin));
Cursor phonesCursor = context.getContentResolver().query(phoneUri, new String[] {PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phonesCursor != null && phonesCursor.moveToFirst()) {
displayName = phonesCursor.getString(0); // this is the contact name
}//end if
Go this eventually.

That question had the answer and posted the code.
Uri phoneUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(mNumber));
Cursor phonesCursor = managedQuery(phoneUri, new String[] {PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phonesCursor != null && phonesCursor.moveToFirst()) {
String displayName = phonesCursor.getString(0); // this is the contact name

Related

TelecomManager.getLine1Number returning null for a valid PhoneAccountHandle

Google told me that in order for me to be able to use either TelephonyManager or TelcomManager to read device identifiers I need one of the requirements stated on the documentation for the respective device identifiers such as GetImei or GetLine1Number. I decided to meet the requirement that states The caller needs to be the default SMS Role holder on that device. So I created an app that is listed as an alternative SMS app on my device and then I check if my app holds that role and then try to get the device identifiers. My code reads the IMEI of both sim cards successfully but fails to read the phone number of the device as the method returns null but I did not expect this as the default sms app should be able to access that number for texting purposes. I am using the following code, help me make this work.
try
{
if (roleManager.IsRoleHeld(RoleManager.RoleSms))
{
var manager = (TelephonyManager)GetSystemService(Context.TelephonyService);
new Android.App.AlertDialog.Builder(this).SetTitle("Device Identifiers")
.SetMessage("phone no " + manager.Line1Number + "\n" + "line 1 imei: " + manager.GetImei(0) + "\n" +
"line 2 imei: " + manager.GetImei(1) + "\n" +
"serial no: " + manager.SimSerialNumber
).Show();
//telephonyManager.GetLine1 fails so
//try and use the telecom service to read the number
var telcom = (TelecomManager)GetSystemService(Context.TelecomService);
//get a list of all capable calling accounts
IList<PhoneAccountHandle> handles = telcom.CallCapablePhoneAccounts;
if (handles != null)
{
//Toast the phone capable calling accounts count
Toast.MakeText(this, handles.Count.ToString(), ToastLength.Short).Show();
//get the phone account handle in index 0
PhoneAccountHandle handle1 = handles[0];
//get the phone number associated with that acount
string phone1 = telcom.GetLine1Number(handle1);
if (phone1 != null)
{
new Android.App.AlertDialog.Builder(this).SetTitle("Phone Number")
.SetMessage(phone1).Show();
}
}
string phone = telcom.GetLine1Number(handles[1]);
if (phone != null)
{
Toast.MakeText(this,phone,ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "GetLine1 is returning null", ToastLength.Short).Show();
}
}
} catch (Java.Lang.SecurityException exc)
{
Toast.MakeText(this, exc.Message, ToastLength.Short).Show();
}
An answer in Android Java is also acceptable, Thank You.
At first, please check the AndroidManifest.xml if you added the <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in it or not.
In addition, there is no reliable way to get the phone number from the SIM card because some telecom operators don't add this information in SIM card and someone did. So sometimes you can get the number and sometimes you will get a null even a phone number you used before.
The most used solution on the SO is using the Google Play Service to get the phone number. You can check this case. And in the Xamarin, you can use the package named Xamarin.GooglePlayServices.Auth to do that.

Import specific SMS from default sms app to my applicaton [duplicate]

I am trying to read sms from content provider. I had following code
Uri uri = Uri.parse(SMS_URI_INBOX);
String whereClause = "address=?";
String[] whereArgs = {address};
String[] projection = new String[] { "*" };
Cursor cur = getContentResolver().query(uri, projection, whereClause,whereArgs, "date desc");
Everything was working fine unless address of various format came into picture. One type of addresses can be represented in various ways like "+9198765443210", "+91 987 65443210" , "+91 (987) 65443210", "098765443210" etc... These type of varied address formats reside in SMS Content provider as well.
Approach 1:
Initially I was converting all the address to format in which special characters are replaced by % like
+9198765443210 --> %98765443210%
+91 987 65443210 --> %987%65443210%
and then using
String whereClause = "address LIKE ?";
but failed because a case may come in which we are firing query address LIKE %98765443210% but address in SMS content provider is +91 987 65443210.
Is there something like normalized_address in android which we can use to get data from SMS Content provider?
Appending to #MikeM. comment, below piece of code helped me to get threadId using which I am making query in SMS Content Provider
//Getting thread Id
ContentResolver mContentResolver = context.getContentResolver();
Uri uriSmsURI1 = Uri.withAppendedPath(Telephony.MmsSms.CONTENT_FILTER_BYPHONE_URI, address);
String[] projection1 = {this.threadId};
Cursor c1 = dbService.query(mContentResolver, uriSmsURI1, projection1, null, null, null);
if(c1.getCount()==0) {
log.error(methodName, "Got count: "+c1.getCount()+" While looking for ThreadID");
return null;
}
String threadId = null;
while(c1.moveToNext()){
threadId = c1.getString(c1.getColumnIndexOrThrow(this.threadId));
}
c1.close();

Content Provider ListView Limit

I would like to limit the amount of contacts displayed in my app. Currently it is querying my Contactscontract.Contacts DB and returning every primary display name that has a phone number. Is there a simple way to reduce this to a numerical amount (say only display 5 contacts), or to certain specified ID's?
This is what I have so far:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " =?", // This is selection string, were looking for records that HAS_PHONE_NUMER is 1
new String[]{"1"}, // 1 means that contact has a phone number
ContactsContract.Contacts._COUNT,
new String[] {"5"},
null);
}
Whenever I try to add new parameters in the return section, Android Studio immediately goes red saying cannot resolve constructor. Is this because the CursorLoader is not defined to receive more parameters?
I defined it earlier in my code as:
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
Cheers,
Shyam
To achieve a limitation of query results, please add (string concatenate) a " LIMIT 5" to your query:
...
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=? LIMIT 5" //This is selection string, were looking for records that HAS_PHONE_NUMER is 1 AND
// the result set is limited to 5 rows
new String[]{"1"},
null);
...

How to get Phone number from Android Cursor?

Following this tutorial I'm trying to get the phone number of a person in the contacts list. With this code I can get the email address:
if (cursor.moveToFirst()){
int emailIdx = cursor.getColumnIndex(Email.DATA);
String email = cursor.getString(emailIdx);
Log.wtf("Email address: ", email);
}
Following this reasoning I tried to get the Phone number like this:
if (cursor.moveToFirst()){
int phoneNrIdx = cursor.getColumnIndex(Phone.DATA);
String phoneNr = cursor.getString(phoneNrIdx);
Log.wtf("Phone number:", phoneNr);
}
Unfortunately this also returns the email address. Does anybody know how I can get the phone number of this contact? All tips are welcome!
Both Email.DATA and Phone.DATA equal the same string, namely 'data1'. That is the name of the column holding the data in the cursor, hence both of your code snippets are effectively the same.
I understand you queried Email.CONTENT_URI, hence the cursor has the email address only in column 'data1'.
To get the phone number as well, close the cursor and then query Phone.CONTENT_URI to get a cursor holding the phone number instead.

I want to add information into the contact according to the ID number, but it always being added to the wrong name.

I want to add a telephone number into the contact according to the ID number, but it always being added to the wrong name. Can anyone tell me the reason why this happened. It runs well in virtual device and sony mobile phone , but it come to an error as I said above in a new Samsung moble phone. I can clearly confirm that the ID number is right
These is the source code:
ContentValues values = new ContentValues ();
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, contactID);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, shortNumber);
values.put(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_OTHER);
getContentResolver().insert(Data.CONTENT_URI,values);
values.clear();
The answer here may help: Inserting contacts in Android 2.2.
It seems the code above does not work on all devices as per the comments there. The answer posted by Alok Save https://stackoverflow.com/users/452307/alok-save, suggests using the applyBatch() method as follows:
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME,null )
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, "9X-XXXXXXXXX")
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, "Mike Sullivan")
.build());
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

Categories

Resources