java - OnActivityResult : Uri and getData is a null object during capture a photo

标签 java android firebase android-camera firebase-storage

我对 Uri 对象有疑问。用户应拍照,然后将其发送到 Firebase 存储。但是 onActivityResult 有问题。

我阅读了很多主题(https://developer.android.com/training/camera/photobasics.html,StackOverFlow 也是),但此代码无效。

出现错误:

尝试在空对象引用上调用虚方法“java.lang.String android.net.Uri.getLastPathSegment()”

下面是一段代码:

 mUploadBtn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {

      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      if (intent.resolveActivity(getPackageManager()) != null) {  

           startActivityForResult(intent, CAMERA_REQUEST_CODE);
               }
             }
         });
    }

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


        if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {

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

            Uri uri = data.getData();

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


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

                    mProgress.dismiss();

                    Uri downloadUri = taskSnapshot.getDownloadUrl();

                    Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);

                    Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
                }
            });

        }
    }
}

正如我检查的那样,onActivityResult 中的数据(Intent)等于 NULL,因此 uri 也为 null。

那么,我该如何解决这个挑战并使其可用呢?我应该使用位图来访问照片吗?

有人可以帮我解决这个问题吗?

问候

最佳答案

我想通了我的问题。 它现在有效。

    private ProgressDialog mProgress;
    private Button mUploadBtn;
    private ImageView mImageView;
    Uri picUri;
    private StorageReference mStorage;

    private static final int CAMERA_REQUEST_CODE = 1;

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


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

        mUploadBtn = (Button) findViewById(R.id.uploadBtn);
        mImageView = (ImageView) findViewById(R.id.imageView);

        mProgress = new ProgressDialog(this);

        mUploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                File file=getOutputMediaFile(1);
                picUri = Uri.fromFile(file); // create
                i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file

                startActivityForResult(i, CAMERA_REQUEST_CODE);
            }
        });
    }

    /** Create a File for saving an image */
    private  File getOutputMediaFile(int type){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyApplication");

        /**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 onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


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

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


            Uri uri = picUri;

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


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

                    mProgress.dismiss();

                    Uri downloadUri = taskSnapshot.getDownloadUrl();

                    Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);

                    Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
                }
            });
        }
    }

关于java - OnActivityResult : Uri and getData is a null object during capture a photo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40149755/

相关文章:

angularjs - View 未更新 - Angular 、firebase

使用retrofit2上传图片时出现Java.io.FileNotFoundException

java - 如何在没有maven依赖的情况下使用Mockito

android - Ionic 3 产品发布构建问题与 com.google.gms :google-services:3. 2.0

android - Xamarin 表单 : How to open an app from another app?

javascript - listRef.listAll() 函数未定义(react-native-firebase)

java - Maven 3 构建扩展和 IntelliJ Idea

java - 如何序列化 antlr3 AST

android - AChartEnging XYMultipleSeriesRenderer y 标签填充

swift - 使用 UITableViewController 从 Firebase 获取当前子 ID