Search code examples
androidandroid-contactsphone-number

How to get contact name with only their phone number?


I am making an application where I listen to all incoming SMS messages and send them securely to a database on my server. I want to also send the display names of all my incoming SMS messages, what is the best way to accomplish this? IS there a way I can do it with incoming messages or is the only way to accomplish this is to make a function that will search my contacts for the same number as the smsMessage[0].getOriginatingAddress() I get from the incoming SMS messages. Here is my function I found and my code for incoming messages:

public class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();

    Object messages[] = (Object[]) bundle.get("pdus");
    SmsMessage smsMessage[] = new SmsMessage[messages.length];
    for (int n = 0; n < messages.length; n++) {
        smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
    }

    // show first message
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.qas.im/web/add_sms.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("from", smsMessage[0].getOriginatingAddress()));
        nameValuePairs.add(new BasicNameValuePair("msg", smsMessage[0].getMessageBody()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        httpclient.execute(httppost);
    } catch (ClientProtocolException e) {} catch (IOException e) {}
    Toast toast = Toast.makeText(context, "Sent to Server \n\n" + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
    toast.show();
}

public String getContactName(final String phoneNumber) 
{  
    Uri uri;
    String[] projection;

    if (Build.VERSION.SDK_INT >= 5)
    {
        uri = Uri.parse("content://com.android.contacts/phone_lookup");
        projection = new String[] { "display_name" };
    }
    else
    { 
        uri = Uri.parse("content://contacts/phones/filter");
        projection = new String[] { "name" }; 
    } 

    uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber)); 
    Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); 

    String contactName = "";

    if (cursor.moveToFirst()) 
    { 
        contactName = cursor.getString(0);
    } 

    cursor.close();
    cursor = null;

    return contactName; 
}

It works just fine, but the getContactName() has one error:

The method getContentResolver() is undefined for the type SMSReceiver

What could be the problem? Any help is really appreciated.


Solution

  • I think the problem might be that BroadcastReceiver does not inherit from Context. You need to use the Context that is passed into onReceive() when you are getting the contentresolver. So, in the getContactName() method, instead of this:

    Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); 
    

    you should use this:

    Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);