Search code examples
androidandroid-contentresolver

How to use getContentResolver() inside non activity class?


I am trying to create a method which retrieves contact name for the given input string. For that I have to use getContentResolver method. To use the context I am passing the context as the parameter. But still the following error is populating.

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference

public class GetContactName {

    public static String getContactName(Context context, String phoneNumber) {
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));

        String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};

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

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

        return contactName;
    }

}

Please help me to solve this


Solution

  • While calling getContactName(), call that with non null attribute

    getContactName(getActivity(), phoneNumber);
    

    where getActivity() represents the context of the class from where you are calling this method. You may be passing a null reference instead of passing the proper context.