title: Android App Keep Crashing Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
body: <p>I'm trying to create an application that can detect emotions through face, voice, and text. To do so, I created three buttons that will direct to the specific Activities.</p>
  <p>I'm using Azure Cognitive service to detect the face.</p>
  <p>but my app keeps crashing whenever I clicked on the first button &quot;face&quot; instead of opening the FaceEmotionActivity.</p>
  <p>following is <strong>the error</strong></p>
  <pre><code>roidRuntime: FATAL EXCEPTION: main
      Process: com.example.epp, PID: 19422
      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.epp/com.example.epp.FaceEmotionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3511)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3650)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:151)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:111)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2213)
          at android.os.Handler.dispatchMessage(Handler.java:107)
          at android.os.Looper.loop(Looper.java:238)
          at android.app.ActivityThread.main(ActivityThread.java:7864)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:998)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
          at com.example.epp.FaceEmotionActivity.onCreate(FaceEmotionActivity.java:86)
          at android.app.Activity.performCreate(Activity.java:7967)
          at android.app.Activity.performCreate(Activity.java:7956)
          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3482)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3650) 
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:151) 
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:111) 
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2213) 
          at android.os.Handler.dispatchMessage(Handler.java:107) 
          at android.os.Looper.loop(Looper.java:238) 
          at android.app.ActivityThread.main(ActivityThread.java:7864) 
          at java.lang.reflect.Method.invoke(Native Method) 
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:998) 
  </code></pre>
  <p>I searched for the answer but could not find the proper answer.</p>
  <p>My <strong>MianActivity.java</strong> is:</p>
  <pre><code>package com.example.epp;
  
  import android.Manifest;
  import android.content.Intent;
  import android.content.pm.PackageManager;
  import android.os.Bundle;
  import android.provider.MediaStore;
  import android.widget.Button;
  
  import androidx.appcompat.app.AppCompatActivity;
  import androidx.core.app.ActivityCompat;
  import androidx.core.content.ContextCompat;
  
  public class MainActivity extends AppCompatActivity {
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  /// checking for camera permission
          if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
              ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 110);
          }
  
          ///3 button objects accessed by id
          Button faceButton = findViewById(R.id.facebtn);
          Button voiceButton = findViewById(R.id.voicebtn);
          Button textButton = findViewById(R.id.textbtn);
  
          ///face accessing method
          faceButton.setOnClickListener(v -&gt; {
              Intent faceIntent = new Intent(MainActivity.this, FaceEmotionActivity.class);
              startActivity(faceIntent);
  
          });
          ///voice accessing method
          voiceButton.setOnClickListener(v -&gt; {
              Intent voiceIntent = new Intent(MainActivity.this, VoiceActivity.class);
              startActivity(voiceIntent);
          });
          ///text accessing method
          textButton.setOnClickListener(v -&gt; {
              Intent textIntent = new Intent(MainActivity.this, TextActivity.class);
              startActivity(textIntent);
          });
  
  
      }
  }
  </code></pre>
  <p>XML for <strong>activity_main</strong> is</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
      xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
      xmlns:tools=&quot;http://schemas.android.com/tools&quot;
      android:layout_width=&quot;wrap_content&quot;
      android:layout_height=&quot;match_parent&quot;
      android:textAlignment=&quot;center&quot;
      tools:context=&quot;.MainActivity&quot;&gt;
  
      &lt;Button
          android:id=&quot;@+id/facebtn&quot;
          android:layout_width=&quot;match_parent&quot;
          android:layout_height=&quot;78dp&quot;
          android:layout_alignTop=&quot;@+id/voicebtn&quot;
          android:layout_alignParentStart=&quot;true&quot;
          android:layout_alignParentEnd=&quot;true&quot;
          android:layout_centerHorizontal=&quot;true&quot;
          android:layout_marginStart=&quot;-3dp&quot;
          android:layout_marginTop=&quot;-149dp&quot;
          android:layout_marginEnd=&quot;2dp&quot;
          android:layout_marginBottom=&quot;75dp&quot;
          android:background=&quot;#8E2121&quot;
          android:text=&quot;FACE&quot;
          android:textSize=&quot;30sp&quot;
          app:layout_constraintBottom_toTopOf=&quot;@+id/textbtn&quot;
          app:layout_constraintEnd_toEndOf=&quot;parent&quot;
          app:layout_constraintHorizontal_bias=&quot;0.505&quot;
          app:layout_constraintStart_toStartOf=&quot;parent&quot;
          app:layout_constraintTop_toBottomOf=&quot;@+id/textView2&quot; /&gt;
  
      &lt;Button
          android:id=&quot;@+id/voicebtn&quot;
          android:layout_width=&quot;match_parent&quot;
          android:layout_height=&quot;75dp&quot;
          android:layout_alignTop=&quot;@+id/textbtn&quot;
          android:layout_alignParentStart=&quot;true&quot;
          android:layout_alignParentEnd=&quot;true&quot;
          android:layout_marginStart=&quot;-2dp&quot;
          android:layout_marginTop=&quot;-140dp&quot;
          android:layout_marginEnd=&quot;0dp&quot;
          android:layout_marginBottom=&quot;75dp&quot;
          android:background=&quot;#8E2121&quot;
          android:text=&quot;VOICE&quot;
          android:textSize=&quot;30sp&quot;
          app:layout_constraintBottom_toTopOf=&quot;@+id/textbtn&quot;
          app:layout_constraintEnd_toEndOf=&quot;parent&quot;
          app:layout_constraintHorizontal_bias=&quot;0.505&quot;
          app:layout_constraintStart_toStartOf=&quot;parent&quot;
          app:layout_constraintTop_toBottomOf=&quot;@+id/textView2&quot; /&gt;
  
      &lt;Button
          android:id=&quot;@+id/textbtn&quot;
          android:layout_width=&quot;match_parent&quot;
          android:layout_height=&quot;75dp&quot;
          android:layout_alignParentStart=&quot;true&quot;
          android:layout_alignParentBottom=&quot;true&quot;
          android:layout_marginStart=&quot;0dp&quot;
          android:layout_marginTop=&quot;348dp&quot;
          android:layout_marginBottom=&quot;149dp&quot;
          android:background=&quot;#8E2121&quot;
          android:text=&quot;TEXT&quot;
          android:textSize=&quot;30sp&quot;
          app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
          app:layout_constraintEnd_toEndOf=&quot;parent&quot;
          app:layout_constraintHorizontal_bias=&quot;0.494&quot;
          app:layout_constraintStart_toStartOf=&quot;parent&quot;
          app:layout_constraintTop_toBottomOf=&quot;@+id/textView2&quot; /&gt;
  
  &lt;/RelativeLayout&gt;
  </code></pre>
  <p><strong>FaceEmotionActivity.java</strong> where the <strong>Face button</strong> suppose to direct</p>
  <pre><code>package com.example.epp;
  
  import android.annotation.SuppressLint;
  import android.app.ProgressDialog;
  import android.content.ActivityNotFoundException;
  import android.content.Intent;
  import android.graphics.Bitmap;
  import android.graphics.Canvas;
  import android.graphics.Color;
  import android.graphics.Paint;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.provider.MediaStore;
  import android.util.Log;
  import android.view.View;
  import android.widget.Button;
  import android.widget.ImageView;
  import android.widget.Toast;
  
  import androidx.annotation.Nullable;
  import androidx.appcompat.app.AppCompatActivity;
  
  import com.microsoft.projectoxford.face.FaceServiceClient;
  import com.microsoft.projectoxford.face.FaceServiceRestClient;
  import com.microsoft.projectoxford.face.contract.Face;
  import com.microsoft.projectoxford.face.contract.FaceRectangle;
  
  import org.json.JSONObject;
  
  import java.io.ByteArrayInputStream;
  import java.io.ByteArrayOutputStream;
  import java.io.InputStream;
  import java.util.Arrays;
  
  import static android.content.ContentValues.TAG;
  
  
  public class FaceEmotionActivity extends AppCompatActivity {
  
      private final FaceServiceClient faceServiceClient = new FaceServiceRestClient(&quot;https://emotiondet.cognitiveservices.azure.com//face/v1.0/&quot;, &quot;529b219bc4b94cfe9f97e20fa3f13b51&quot;);
  
      JSONObject jsonObject, jsonObject1;
      ImageView imageView;
      Bitmap mBitmap;
      boolean takePicture = false;
  
      private ProgressDialog detectionProgressDialog;
      Face[] facesDetected;
      static final int REQUEST_IMAGE_CAPTURE = 1;
  
  
      @Override
      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          if (requestCode == 0 &amp;&amp; resultCode == RESULT_OK) {
              assert data != null;
              Bitmap bitmap = (Bitmap) data.getExtras().get(&quot;data&quot;);
              imageView.setImageBitmap(bitmap);
              detectAndFrame(bitmap);
          }
      }
      
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          detectionProgressDialog = new ProgressDialog(this);
  
          jsonObject = new JSONObject();
          jsonObject1 = new JSONObject();
          imageView = findViewById(R.id.imageView);
          Toast.makeText(getApplicationContext(), &quot;Press the Detect Button to take a picture. Press Identify to identify the person.&quot;, Toast.LENGTH_LONG).show();
  
          Button btnDetect = findViewById(R.id.faceDetectBtn);
  
          btnDetect.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                  try {
                      startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                  } catch (ActivityNotFoundException e) {
                      // display error state to the user
                  }
              }
          });
      }
  
  
      private void detectAndFrame(final Bitmap imageBitmap) {
          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
          imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
          ByteArrayInputStream inputStream =
                  new ByteArrayInputStream(outputStream.toByteArray());
  
          @SuppressLint(&quot;StaticFieldLeak&quot;) AsyncTask&lt;InputStream, String, Face[]&gt; detectTask =
  
                  new AsyncTask&lt;InputStream, String, Face[]&gt;() {
                      String exceptionMessage = &quot;&quot;;
  
                      @SuppressLint(&quot;DefaultLocale&quot;)
                      @Override
                      protected Face[] doInBackground(InputStream... params) {
                          try {
                              publishProgress(&quot;Detecting...&quot;);
                              Face[] result = faceServiceClient.detect(
                                      params[0],
                                      true,         // returnFaceId
                                      false,        // returnFaceLandmarks
                                      // returnFaceAttributes:
                                      new FaceServiceClient.FaceAttributeType[]{
                                              FaceServiceClient.FaceAttributeType.Emotion,
                                              FaceServiceClient.FaceAttributeType.Gender}
                              );
  
                              for (int i = 0; i &lt; result.length; i++) {
                                  jsonObject.put(&quot;happiness&quot;, result[i].faceAttributes.emotion.happiness);
                                  jsonObject.put(&quot;sadness&quot;, result[i].faceAttributes.emotion.sadness);
                                  jsonObject.put(&quot;surprise&quot;, result[i].faceAttributes.emotion.surprise);
                                  jsonObject.put(&quot;neutral&quot;, result[i].faceAttributes.emotion.neutral);
                                  jsonObject.put(&quot;anger&quot;, result[i].faceAttributes.emotion.anger);
                                  jsonObject.put(&quot;contempt&quot;, result[i].faceAttributes.emotion.contempt);
                                  jsonObject.put(&quot;disgust&quot;, result[i].faceAttributes.emotion.disgust);
                                  jsonObject.put(&quot;fear&quot;, result[i].faceAttributes.emotion.fear);
                                  Log.e(TAG, &quot;doInBackground: &quot; + jsonObject.toString());
  
                                  jsonObject1.put((String.valueOf(i)), jsonObject);
                              }
  //
                              runOnUiThread(() -&gt; Toast.makeText(FaceEmotionActivity.this, &quot;DATA&quot; + jsonObject1.toString(), Toast.LENGTH_LONG).show());
  
                              Log.e(&quot;TAG&quot;, &quot;doInBackground: &quot; + &quot;   &quot; + result.length);
                              publishProgress(String.format(
                                      &quot;Detection Finished. %d face(s) detected&quot;,
                                      result.length));
  
                              return result;
                          } catch (Exception e) {
                              exceptionMessage = String.format(
                                      &quot;Detection failed: %s&quot;, e.getMessage());
                              return null;
                          }
                      }
  
                      @Override
                      protected void onPreExecute() {
                          detectionProgressDialog.show();
                      }
  
                      @Override
                      protected void onProgressUpdate(String... progress) {
                          detectionProgressDialog.setMessage(progress[0]);
                      }
  
                      @Override
                      protected void onPostExecute(Face[] result) {
                          detectionProgressDialog.dismiss();
  
                          facesDetected = result;
  
                          
                          if (result == null) {
                              //                                showError(&quot;No faces detected&quot;);
                          }
                          Log.e(&quot;TAG&quot;, &quot;onPostExecute: &quot; + Arrays.toString(facesDetected));
  
                          ImageView imageView = findViewById(R.id.imageView);
                          imageView.setImageBitmap(
                                  drawFaceRectanglesOnBitmap(imageBitmap, result));
                          imageBitmap.recycle();
                          Toast.makeText(getApplicationContext(), &quot;Now you can identify the person by pressing the \&quot;Identify\&quot; Button&quot;, Toast.LENGTH_LONG).show();
                          takePicture = true;
                      }
                  };
  
          detectTask.execute(inputStream);
      }
  
      private static Bitmap drawFaceRectanglesOnBitmap(
              Bitmap originalBitmap, Face[] faces) {
          Bitmap bitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
          Canvas canvas = new Canvas(bitmap);
          Paint paint = new Paint();
          paint.setAntiAlias(true);
          paint.setStyle(Paint.Style.STROKE);
          paint.setColor(Color.RED);
          paint.setStrokeWidth(9);
          if (faces != null) {
              for (Face face : faces) {
                  FaceRectangle faceRectangle = face.faceRectangle;
                  canvas.drawRect(
                          faceRectangle.left,
                          faceRectangle.top,
                          faceRectangle.left + faceRectangle.width,
                          faceRectangle.top + faceRectangle.height,
                          paint);
              }
          }
          return bitmap;
      }
  }
  </code></pre>
  <p>Xml for FaceEmotionActivity.java is activity_face_emotion.xml</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
      xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
      xmlns:tools=&quot;http://schemas.android.com/tools&quot;
      android:layout_width=&quot;match_parent&quot;
      android:layout_height=&quot;match_parent&quot;
      android:orientation=&quot;vertical&quot;
      tools:context=&quot;.MainActivity&quot;&gt;
  
      &lt;ImageView
          android:id=&quot;@+id/imageView&quot;
          android:layout_width=&quot;match_parent&quot;
          android:layout_height=&quot;match_parent&quot; /&gt;
  
      &lt;LinearLayout
          android:id=&quot;@+id/groupButton&quot;
          android:layout_alignParentBottom=&quot;true&quot;
  
          android:gravity=&quot;center_vertical&quot;
  
          android:layout_width=&quot;match_parent&quot;
          android:layout_height=&quot;wrap_content&quot;&gt;
  
          &lt;Button
              android:id=&quot;@+id/faceDetectBtn&quot;
              android:layout_weight=&quot;3&quot;
              android:text=&quot;Detect Face&quot;
              android:layout_width=&quot;0dp&quot;
              android:layout_height=&quot;wrap_content&quot; /&gt;
  
  
      &lt;/LinearLayout&gt;
  
  
  &lt;/RelativeLayout&gt;
  </code></pre>
  <p>I haven't created the other two activities since they are not needed right now.</p>
  <p><em>Thank you</em></p>