尝试将图像从Firebase数据库获取到存储时发生StorageException

时间:2020-06-02 12:33:14

标签: java android firebase-realtime-database firebase-storage

我正在尝试将图像存储到FireBase数据库中,我很确定所有代码在获取imagelink方面都工作正常,因为它不再像以前那样显示错误。但是,现在,当我上传图像时,出现了一个新问题。与存储异常有关,我猜测从存储中实际撤出imagelink并将其插入数据库存在问题。这是我认为发生问题的代码:

private StorageReference PostsImagesReference;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;
//private String downloadUrl;


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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

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

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

如果需要,这是我的全部代码:

 private Toolbar mToolbar;
private ProgressDialog loadingBar;

private ImageButton SelectPostImage;
private Button AddPostButton;
private EditText PostDescription;

private static final int Gallery_Pick = 1;
private Uri ImageUri;


private StorageReference PostsImagesReference;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;
//private String downloadUrl;


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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

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

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
    AddPostButton = (Button) findViewById(R.id.add_post);
    PostDescription = (EditText) findViewById(R.id.post_description);
    loadingBar = new ProgressDialog(this);


    mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Update Post");


    SelectPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            OpenGallery();

        }
    });

    AddPostButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            ValidatePostInfo();
        }
    });

}

private void ValidatePostInfo()
{
    Description = PostDescription.getText().toString();

    if(ImageUri == null)
    {
        Toast.makeText(this, "Please select image", Toast.LENGTH_SHORT).show();
    }
    else if(TextUtils.isEmpty(Description))
    {
        Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Post Uploading");
        loadingBar.setMessage("Please Wait");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

        StoringImageToFirebaseStorage();

    }
}

private void StoringTextToFirebaseStorage(Uri downloadUrl)
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;


    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", downloadUrl.toString());

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });


}


private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;


    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {
                        StoringTextToFirebaseStorage(uri);


                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();


            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}




private void OpenGallery()
{
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, Gallery_Pick);
}






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

    if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        SendUserToMainActivity();
    }

    return super.onOptionsItemSelected(item);
}



private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
    startActivity(mainIntent);
}

}

错误消息:

2020-06-02 13:54:22.594 3466-5776/com.example.app E/StorageException: StorageException has occurred.
Object does not exist at location.
 Code: -13010 HttpResult: 404

2020-06-02 13:54:22.594 3466-5776 / com.example.app E / StorageException:{“错误”:{“代码”:404,“消息”:“未找到。无法获取对象“,”状态“:” GET_OBJECT“}} java.io.IOException:{“错误”:{“代码”:404,“消息”:“未找到。无法获取对象”,“状态”:“ GET_OBJECT”}} com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage @@ 17.0.0:455) com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage @@ 17.0.0:435) 在com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage @@ 17.0.0:426) com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage @@ 17.0.0:280) com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage @@ 17.0.0:294) 在com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage @@ 17.0.0:70) 在com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage @@ 17.0.0:62) com.google.firebase.storage.GetDownloadUrlTask​​.run(com.google.firebase:firebase-storage @@ 17.0.0:74) 在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:641) 在java.lang.Thread.run(Thread.java:919) 2020-06-02 13:54:22.602 3466-3466 / com.example.app E / RecyclerView:未连接布局管理器;跳过布局

1 个答案:

答案 0 :(得分:0)

您正在尝试获取''文件夹的下载URL,这是不可能的:

PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(...

您需要在调用getDownloadUrl()的{​​{1}}上调用StorageReference

putFile