0
votes

Comment réparer NullPointerException: fichier lors de la capture de la photo de la caméra

J'essaie de capturer une image à l'aide de l'appareil photo, cependant, lors de la sauvegarde du fichier, j'obtiens l'erreur suivante:

public class ReportFoundItem extends AppCompatActivity {

private DatabaseReference databaseFound;

private static final int CAPTURE_IMAGE = 1;

private Uri picUri;

private StorageReference mStorage;

private ProgressDialog mProgress;

private EditText etemail;
private EditText etphone;
private Spinner etcategory;
private Spinner etsub_category;
private Button btncapture;
private ImageView imageView;
private EditText etdate_found;
private EditText etlocation_found;
private EditText etdetails;

private void dispatchTakePictureIntent() {
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    File file = getOutputMediaFile(1);
    picUri = Uri.fromFile(file);
    i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
    startActivityForResult(i, CAPTURE_IMAGE);
        }

public File getOutputMediaFile(int type) {
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "TRARC");


    /**Create the storage directory if it does not exist*/
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == 1){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_"+ timeStamp + ".png");
    } else {
        return null;
    }

    return mediaFile;
}





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_report_found_item);

    mStorage = FirebaseStorage.getInstance().getReference();

    databaseFound = FirebaseDatabase.getInstance().getReference("found");

    etemail = (EditText)findViewById(R.id.etemail);
    etphone = (EditText)findViewById(R.id.etphone);
    etcategory = (Spinner)findViewById(R.id.etcategory);
    etsub_category = (Spinner)findViewById(R.id.etsub_category);
    btncapture = (Button)findViewById(R.id.btncapture);
    imageView = (ImageView)findViewById(R.id.imageView);
    etdate_found = (EditText) findViewById(R.id.etdate_found);
    etlocation_found = (EditText) findViewById(R.id.etlocation_found);
    etdetails = (EditText) findViewById(R.id.etdetails);

    mProgress = new ProgressDialog(this);

    btncapture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            dispatchTakePictureIntent();
        }
    });



}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAPTURE_IMAGE && resultCode == RESULT_OK){

        mProgress.setMessage("Uploading Image...Please wait...");
        mProgress.show();

        final StorageReference filepath = mStorage.child("Found_Photos").child(uri.getLastPathSegment());

        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                mProgress.dismiss();

                //creating the upload object to store uploaded image details
                Upload upload = new Upload(uri.toString(),taskSnapshot.getDownloadUrl().toString());

                //adding an upload to firebase database
                String uploadId = databaseFound.push().getKey();
                databaseFound.child(uploadId).setValue(upload);

                Uri downloadUri = taskSnapshot.getDownloadUrl();

                Picasso.with(ReportFoundItem.this).load(downloadUri).fit().centerCrop().into(imageView);

                //Toast.makeText(ReportFoundItem.this, "Uploading finished...", Toast.LENGTH_LONG).show();

            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {

                double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                mProgress.setMessage("Uploaded " + ((int) progress) + "%...");

            }
        });//add on failure listener
    }
}

private void reportFoundItem() {
    String email = etemail.getText().toString().trim();
    String phone = etphone.getText().toString().trim();
    String category = etcategory.getSelectedItem().toString().trim();
    String sub_category = etsub_category.getSelectedItem().toString().trim();
    String date_found = etdate_found.getText().toString().trim();
    String location_found = etlocation_found.getText().toString().trim();
    String details = etdetails.getText().toString().trim();
    //check if empty
    if (!TextUtils.isEmpty(email)){
        //getting the key
        String id = databaseFound.push().getKey();
        //save the data under lost
        Found found = new Found(id, email, phone, category, sub_category, date_found, location_found, details);
        //set the value under the id
        databaseFound.child(id).setValue(found);
        Toast.makeText(this, "Found Item added successfully!", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "Please enter all Fields!", Toast.LENGTH_SHORT).show();
    }

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.savetodb, menu);
    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.save:
            reportFoundItem();
            ClearEditTextAfterDoneTask();
    }
    return true;
}

@Override
public void onBackPressed()
{
    super.onBackPressed();
    startActivity(new Intent(ReportFoundItem.this, Home.class));
    finish();

}

public void ClearEditTextAfterDoneTask() {
    etemail.getText().clear();
    etphone.getText().clear();
    etdate_found.getText().clear();
    etlocation_found.getText().clear();
    etdetails.getText().clear();
}


0 commentaires

3 Réponses :


0
votes
 @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(data);
    }
}

  private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    user_image.setImageBitmap(thumbnail);
  }




   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();
        }
    }

    user_image.setImageBitmap(bm);
}
check data is !=null to avoid nullpointer exception

2 commentaires

Je veux capturer l'image de la caméra directement ne cueille pas l'image de la galerie ...


OncaptureImageresult Appelez cette fonction Je viens de mettre à jour le code Vérifiez maintenant



0
votes

Essayez celui-ci ...

image capturé ... xxx

en cliquant .... xxx

sur l'activitéResult .... xxx

et autre méthode .... xxx

Remarque: - Vous obtenez URI NULL parce que l'image que vous capturez n'a aucun chemin. Donc, UriR renvoie null ..


0 commentaires

0
votes

Voici comment je l'ai fait dans mon projet. xxx


0 commentaires