title: Android: Get contact name using phone number
body: <p>I am trying to access contact but keeps getting null pointer error.</p>
  
  <p><code>NullPointerException: Attempt to invoke virtual method ' 
  android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
  </code></p>
  
  <p><strong>Code</strong></p>
  
  <pre><code> public static String getContactName(Context context, String phoneNumber) {
      Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
      Cursor cursor = context.getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
      if (cursor == null) {
          return null;
      }
      String contactName = null;
      String contactNumber = "";
      if(cursor.moveToFirst()) {
          contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
      }
  
      if(cursor != null &amp;&amp; !cursor.isClosed()) {
          cursor.close();
      }
  
      return contactNumber.equals("") ? phoneNumber : contactName;
  }
  </code></pre>
  
  <p>Here is how I use it </p>
  
  <pre><code>public class VideoActivity extends Activity {
  
  String contactName;
  String phoneNumber;
  Context context;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_video);
  
      //Set caller phone
      String number = getIntent().getStringExtra(
              TelephonyManager.EXTRA_INCOMING_NUMBER);
  
     contactName = getContactName(context, number);
      TextView text = (TextView) findViewById(R.id.textView2);
      text.setText(contactName);
  
  }
  </code></pre>
  
  <p>Is it possible to call BroadcastReceiver in an activity?</p>
  
  <p>Any help will be appreciated. Thanks</p>