title: How can I fix my app crash after take a photo in android
body: <p>How can I fix my app crash after take a photo in android, I am currently making an application to report to the streets via photos, but I have a problem when the user has taken a picture through the camera, when I press the application button to crash, the following reports of crashes that occur</p>
  
  <pre><code>java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.dbothxrpsc119.soppeng/com.dbothxrpsc119.soppeng.LaporanActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
      at android.app.ActivityThread.deliverResults(ActivityThread.java:4332)
      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4376)
      at android.app.ActivityThread.-wrap19(Unknown Source:0)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
      at android.os.Handler.dispatchMessage(Handler.java:106)
      at android.os.Looper.loop(Looper.java:176)
      at android.app.ActivityThread.main(ActivityThread.java:6635)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
      at com.dbothxrpsc119.soppeng.LaporanActivity.setPic(LaporanActivity.java:262)
      at com.dbothxrpsc119.soppeng.LaporanActivity.onCaptureImageResult(LaporanActivity.java:271)
      at com.dbothxrpsc119.soppeng.LaporanActivity.onActivityResult(LaporanActivity.java:206)
      at android.app.Activity.dispatchActivityResult(Activity.java:7351)
      at android.app.ActivityThread.deliverResults(ActivityThread.java:4328)
      ... 9 more
  </code></pre>
  
  <p>for the reportactivity code snippet as follows</p>
  
  <pre><code>public class LaporanActivity extends AppCompatActivity {
  
      private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
      private Button btnSelect;
      private EditText edPesanKirim;
      private Button btnUpload;
      private ImageView ivImage;
      private String userChoosenTask;
      String mCurrentPhotoPath;
      Uri photoURI;
  
      public static final String UPLOAD_KEY = "image";
      public static final String TAG = "Laporan";
  
      private Bitmap bitmap;
  
      private SQLiteDatabase db;
      private Cursor c;
  
      String pesan,nama,ktpsim,alamat,hp;
      Boolean sudahUpload = false;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_laporan);
          db=openOrCreateDatabase("User", Context.MODE_PRIVATE, null);
  
          ivImage = (ImageView) findViewById(R.id.ivImage);
          btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
          btnSelect.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  selectImage();
              }
          });
  
          edPesanKirim = (EditText) findViewById(R.id.edPesanKirim);
          btnUpload = (Button) findViewById(R.id.btnUpload);
          btnUpload.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  //check jika data belum lengkap
                  c = db.rawQuery("SELECT * FROM users",null);
                  boolean exists = (c.getCount() &gt; 0);
                  if(exists) {
                      c.moveToFirst();
                      pesan = edPesanKirim.getText().toString();
                      nama = c.getString(1);
                      ktpsim = c.getString(2);
                      alamat = c.getString(3);
                      hp = c.getString(4);
  
                      if (!c.getString(0).equals("") || !c.getString(1).equals("") || c.getString(2).equals("")
                              || c.getString(3).equals("") || c.getString(4).equals("")) {
                          if (!pesan.equals("")) {
                              if (sudahUpload.equals(true)) {
                                  uploadImage("gambar");
                              } else {
                                  uploadImage("pesan");
                              }
                          } else {
                              Toast.makeText(LaporanActivity.this,"Silahkan isi gambar dan pesan terlebih dahulu",Toast.LENGTH_SHORT).show();
                          }
                      } else {
                          Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
                          Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
                          startActivity(intent);
                      }
                  } else {
                      Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
                      Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
                      startActivity(intent);
                  }
                  c.close();
              }
          });
      }
  
      @Override
      public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
          switch (requestCode) {
              case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                  if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                      if(userChoosenTask.equals("Ambil Photo"))
                          cameraIntent();
                      else if(userChoosenTask.equals("Pilih dari Galery"))
                          galleryIntent();
                  } else {
                      //code for deny
                  }
                  break;
          }
      }
  
      private void selectImage() {
          final CharSequence[] items = { "Ambil Photo", "Pilih dari Galery", "Cancel" };
  
          AlertDialog.Builder builder = new AlertDialog.Builder(LaporanActivity.this);
          builder.setTitle("Tambah Photo!");
          builder.setItems(items, new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int item) {
                  boolean result=Utility.checkPermission(LaporanActivity.this);
  
                  if (items[item].equals("Ambil Photo")) {
                      userChoosenTask ="Ambil Photo";
                      if(result)
                          cameraIntent();
  
                  } else if (items[item].equals("Pilih dari Galery")) {
                      userChoosenTask ="Pilih dari Galery";
                      if(result)
                          galleryIntent();
  
                  } else if (items[item].equals("Cancel")) {
                      dialog.dismiss();
                  }
              }
          });
          builder.show();
      }
  
      private void galleryIntent()
      {
          Intent intent = new Intent();
          intent.setType("image/*");
          intent.setAction(Intent.ACTION_GET_CONTENT);//
          startActivityForResult(Intent.createChooser(intent, "Pilih File"),SELECT_FILE);
      }
  
      private void cameraIntent()
      {
          Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          // Ensure that there's a camera activity to handle the intent
          if (intent.resolveActivity(getPackageManager()) != null) {
              // Create the File where the photo should go
              File photoFile = null;
              try {
                  photoFile = createImageFile();
                  photoFile.delete();
              } catch (IOException ex) {
                  // Error occurred while creating the File
                  Log.d("Photo",ex.toString());
              }
              // Continue only if the File was successfully created
              if (photoFile != null) {
                  Uri photoURI = FileProvider.getUriForFile(this,
                          "com.dbothxrpsc119.soppeng.fileprovider",
                          photoFile);
              startActivityForResult(intent, REQUEST_CAMERA);
  
              }
          }
      }
  
      @Override
      public void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
  
          if (resultCode == Activity.RESULT_OK) {
              if (requestCode == SELECT_FILE)
                  onSelectFromGalleryResult(data);
              else if (requestCode == REQUEST_CAMERA) {
                  onCaptureImageResult();
              }
          }
      }
  
      private File createImageFile() throws IOException {
          // Create an image file name
          String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
          String imageFileName = "DebotHaxor_" + timeStamp + "_";
          File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
          File image = File.createTempFile(
                  imageFileName,  /* prefix */
                  ".jpg",         /* suffix */
                  storageDir      /* directory */
          );
  
          // Save a file: path for use with ACTION_VIEW intents
          //mCurrentPhotoPath = "file:" + image.getAbsolutePath();
          mCurrentPhotoPath = image.getAbsolutePath();
          //mCurrentPhotoPath = image;
          return image;
      }
      private void galleryAddPic() {
          Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
          Uri contentUri = photoURI;
          mediaScanIntent.setData(contentUri);
          this.sendBroadcast(mediaScanIntent);
      }
      private void setPic() {
          // Get the dimensions of the View
          int targetW = ivImage.getWidth();
          int targetH = ivImage.getHeight();
          //Log.d("Photo","Set Pic "+mCurrentPhotoPath);
  
          Bitmap real_bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
          // Get the dimensions of the bitmap
          BitmapFactory.Options bmOptions = new BitmapFactory.Options();
          bmOptions.inJustDecodeBounds = true;
          BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
          int photoW = bmOptions.outWidth;
          int photoH = bmOptions.outHeight;
  
          // Determine how much to scale down the image
          int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
  
          // Decode the image file into a Bitmap sized to fill the View
          bmOptions.inJustDecodeBounds = false;
          bmOptions.inSampleSize = scaleFactor;
          bmOptions.inPurgeable = true;
  
          Bitmap bitmap_view = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
          ivImage.setImageBitmap(bitmap_view);
          Log.d("Photo","Tampilkan Foto "+ mCurrentPhotoPath);
  
          //resize
          Bitmap resized;
          resized = Bitmap.createScaledBitmap(bitmap_view,(int)(real_bitmap.getWidth()*0.4), (int)(real_bitmap.getHeight()*0.4), true);
  
          ByteArrayOutputStream bytes = new ByteArrayOutputStream();
          resized.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
          bitmap = resized;
      }
  
      private void onCaptureImageResult() {
          galleryAddPic();
          setPic();
          sudahUpload = true;
      }
  
      @SuppressWarnings("deprecation")
      private void onSelectFromGalleryResult(Intent data) {
  
          Bitmap bm=null;
          if (data != null) {
              try {
                  bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
  
          ivImage.setImageBitmap(bm);
  
          ByteArrayOutputStream bytes = new ByteArrayOutputStream();
          bm.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
          bitmap = bm;
          sudahUpload = true;
      }
  
      public String getStringImage(Bitmap bmp){
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
          byte[] imageBytes = baos.toByteArray();
          String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
          return encodedImage;
      }
  
      private void uploadImage(String mode){
          class UploadImage extends AsyncTask&lt;Bitmap,Void,String&gt; {
  
              ProgressDialog loading;
              RequestHandler rh = new RequestHandler();
  
              @Override
              protected void onPreExecute() {
                  super.onPreExecute();
                  loading = ProgressDialog.show(LaporanActivity.this, "Kirim Pesan", "Mohon tunggu...",true,true);
                  loading.setCanceledOnTouchOutside(false);
              }
  
              @Override
              protected void onPostExecute(String s) {
                  super.onPostExecute(s);
                  loading.dismiss();
  
                  String msg = "";
                  if (s.equals("ok")) {
                      msg = "Pesan sukses terkirim";
                      clearForm();
                  } else {
                      msg = getString(R.string.api_error);
                  }
                  Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
              }
  
              @Override
              protected String doInBackground(Bitmap... params) {
                  HashMap&lt;String,String&gt; data = new HashMap&lt;&gt;();
                  if (params.length &gt; 0) {
                      Bitmap bitmap = params[0];
                      String uploadImage = getStringImage(bitmap);
                      data.put(UPLOAD_KEY, uploadImage);
                  }
                  data.put("pesan", pesan);
                  data.put("device_id", Utility.uniqDevice(LaporanActivity.this));
  
                  String uri = "https://"+ getString(R.string.api_url) + "/path/kirim_pesan";
                  String result = rh.sendPostRequest(uri,data);
                  return result;
              }
          }
  
          UploadImage ui = new UploadImage();
          if (mode.equals("gambar"))
              ui.execute(bitmap);
          else
              ui.execute();
      }
  
      private void clearForm() {
          ivImage.setImageResource(R.drawable.ic_menu_gallery);
          edPesanKirim.setText("");
          btnSelect.setFocusable(true);
      }
  }
  </code></pre>