访问Camera Android时,意图上发生NullPointerException

时间:2019-06-14 22:08:39

标签: java android firebase firebaseui

我尝试按以下说明两次调用Camera应用程序:https://developer.android.com/training/camera/photobasics 现在,当我在不创建临时文件的情况下使用此文件时,它可以正常工作,并且可以调用两次相机,但是在添加临时文件后,我只能在崩溃前拍摄一个文件。这非常令人沮丧,因为我可以看到它在崩溃前返回了全尺寸图片。

我已经尝试在获取之前进行第二次.putExtras(),但这没有用。我也尝试过断言不为null,结果相同。

private void takePictureAndUpload() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File

            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.provider",
                        photoFile);
                startActivityForResult(takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                        , REQUEST_IMAGE_CAPTURE);
            }
        }


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_IMAGE_CAPTURE) && (resultCode == Activity.RESULT_OK)){
            count++;
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            assert imageBitmap != null;
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            final byte[] imageData = stream.toByteArray();

            setuId(user);
            final String path = "posts/" + UUID.randomUUID() + ".jpg";

            FirebaseStorage storage = FirebaseStorage.getInstance();
            final StorageReference storageRef = storage.getReference();
            final StorageReference imageRef = storageRef.child(path);


            UploadTask uploadTask = imageRef.putBytes(imageData);
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    String ex = e.getLocalizedMessage();
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    imageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                    {
                        @Override
                        public void onSuccess(Uri downloadUrl)
                        {
                            final String url = downloadUrl.toString();//do something with downloadurl
                            data.putExtra(MediaStore.EXTRA_OUTPUT, url);
                            addPhotoUrlToDatabase(post.getImageUrl_1(), post.getImageUrl_2(), path);

                        }
                    });
                }
            });
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + 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
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

这应该打开相机拍摄照片,然后在接受第一张照片后应该重新打开相机拍摄第二张照片。但是到目前为止,它所做的只是打开相机,拍张照片,然后当我点击接受时,它崩溃并显示nullPointerException。

LogCat:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.android, PID: 21689
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.android/com.example.android.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4491)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4534)
        at android.app.ActivityThread.-wrap20(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1752)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
        at com.example.android.MainActivity.onActivityResult(MainActivity.java:257)
        at android.app.Activity.dispatchActivityResult(Activity.java:7547)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4487)

修改

这是我遵循的指南: https://developer.android.com/training/camera/photobasics.html#TaskPath

2 个答案:

答案 0 :(得分:0)

像使用相同的命名参数那样使您的活动结果令人困惑。

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
          }

您的捆绑包似乎为空。

答案 1 :(得分:0)

在这里找到答案:https://stackoverflow.com/a/37628687/10941659。在android开发人员培训网站上尚未明确说明,但是当您要获取完整尺寸的图片时,请勿使用传递给onActivityResult的意图。您需要使用为图像生成的路径,例如:

package tech.service.common;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import tech.alphalupi.rhcore.dto.MailResponseDto;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class MailingService {


    @Autowired
    private JavaMailSender sender;


    public MailResponseDto sendEmail(String mailTo,String Subject) {
        MailResponseDto response = new MailResponseDto();
        MimeMessage message = sender.createMimeMessage();
        Configuration config = new Configuration(new Version(2, 3, 0));

        try {
            // set mediaType
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            TemplateLoader templateLoader = new FileTemplateLoader(new File("src/main/resources/template"));
            config.setTemplateLoader(templateLoader);
            // add attachment
            helper.addAttachment("logo.png", new File("src/main/resources/static/images/spring.png"));
            Template t = config.getTemplate("email_template_password.ftl");
            Map<String, Object> model = new HashMap<>();
            model.put("Name", "ELAMMARI Soufiane");
            model.put("location", "Casablanca,Morocco");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);

            helper.setTo("example@gmail.com");
            helper.setText(html, true);
            helper.setSubject(Subject);
            sender.send(message);

            response.setMessage("mail send to : " + mailTo);
            response.setStatus(Boolean.TRUE);

        } catch (MessagingException | IOException | TemplateException e) {
            response.setMessage("Mail Sending failure : "+e.getMessage());
            response.setStatus(Boolean.FALSE);
        }

        return response;
    }
}