【问题标题】:onActivityResult returns null for image pickeronActivityResult 为图像选择器返回 null
【发布时间】:2017-02-27 11:06:50
【问题描述】:

我正在使用 Firebase 存储从 Android 应用上传图片。所以当我点击photoBtn按钮时,image_picker会打开,但是当我选择一张图片时,URI仍然是空的。

这是我的代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        StorageReference photoRef=mEventPhotoReference.child(selectedImageUri.getLastPathSegment());

        photoRef.putFile(selectedImageUri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // When the image has successfully uploaded, we get its download URL
                        downloadUrl = taskSnapshot.getDownloadUrl();
                        Toast.makeText(MainActivity.this,"got the uri",Toast.LENGTH_LONG).show();
                    }

                });

    }


}

//DISPLAY INPUT DIALOG
private void displayInputDialog()
{
    Dialog d=new Dialog(this);
    d.setTitle("Save To Firebase");
    d.setContentView(R.layout.input_dialog);

    nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);
    grpTxt= (EditText) d.findViewById(R.id.propellantEditText);
    descTxt= (EditText) d.findViewById(R.id.descEditText);
    Button saveBtn= (Button) d.findViewById(R.id.saveBtn);
    Button photoBtn=(Button)d.findViewById(R.id.photoBtn);
    linkTxt = (EditText) d.findViewById(R.id.linkEditText);



    photoBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);

        }
    });


    //SAVE
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //GET DATA
            String name=nameEditTxt.getText().toString();
            String propellant=grpTxt.getText().toString();
            String desc=descTxt.getText().toString();
            String link=linkTxt.getText().toString();
            Long tsLong = System.currentTimeMillis()/1000;
            String ts = tsLong.toString();


            //SET DATA
            Spacecraft s=new Spacecraft();

            if(downloadUrl==null){
                Toast.makeText(MainActivity.this,"Photo is necessary to add an Event",Toast.LENGTH_SHORT).show();
            }else {
                s.setName(name);
                s.setPropellant(propellant);
                s.setDescription(desc);
                s.setLink(link);
                s.setImageUrl(downloadUrl.toString());
                s.setTimestamp(ts);
            }
            //SIMPLE VALIDATION
            if(name != null && name.length()>0)
            {
                //THEN SAVE
                if(helper.save(s))
                {
                    //IF SAVED CLEAR EDITXT
                    nameEditTxt.setText("");
                    grpTxt.setText("");
                    descTxt.setText("");
                    linkTxt.setText("");
                    downloadUrl=null;



                    adapter=new MyAdapter(MainActivity.this,helper.retrieve());
                    rv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                }
            }else
            {
                Toast.makeText(MainActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
            }

        }
    });

    d.show();
}

有人能帮我解释一下为什么onSuccess 方法永远不会执行,而downloadUrl 总是为空吗?

【问题讨论】:

    标签: android firebase null firebase-storage onactivityresult


    【解决方案1】:

    您可以考虑实现一个 onFailureListener 来查看它失败的原因。如果没有成功,那是因为它不成功。这就是失败监听器的用武之地。

    Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
    StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
    uploadTask = riversRef.putFile(file);
    
    // Register observers to listen for when the download is done or if it fails
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle unsuccessful uploads
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
            Uri downloadUrl = taskSnapshot.getDownloadUrl();
        }
    });
    

    https://firebase.google.com/docs/storage/android/upload-files

    【讨论】:

    • 我找到了答案,实际上是阻止图片上传的规则,你改变了规则,现在一切正常
    • 好的,但是您可以通过检查失败异常来找到它。你是怎么找到答案的?
    • 奇怪的是 android studio 出了点问题,它没有在日志消息中显示 firebase 异常日志,我重新启动了 android studio,然后它显示了异常消息
    【解决方案2】:

    查看我的回答 here 。我提供了一个简单的包装器来获取图像并正确接收它们

    【讨论】:

    • 我刚刚意识到我的意图返回数据但在 onActivityResult 中 addOnSuccessListener 没有执行,你能告诉我可能是什么问题
    • 如果您检查了我的答案,您会发现您必须将 requestCode == RC_PHOTO_PICKER 更改为 (requestCode &amp; 0xffff) == RC_PHOTO_PICKER 才能获得正确的十六进制值。
    • 不幸的是它不起作用,行 photoRef.putFile(selectedImageUri) .addOnSuccessListener 仍然没有执行
    • 它真的到达那部分了吗?尝试在那里放置一个日志,看看它是否真的进入了你的 if 语句
    • 我一定是在自责我的代码运行良好,原因是它没有执行 onSuccess 方法是我忘记公开我的 firebase 规则,无论如何感谢您的帮助,问题已解决
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多