即使遵循Firebase代码示例,我也没有在Firebase数据库中获得图像链接

问题描述 投票:0回答:1

该链接可以很好地保存在存储中,但根本不会以任何格式保存在数据库中。

  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)
                    {


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

                StoringTextToFirebaseStorage();

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

这是我应该在其中保存链接的代码,我正在使用https://firebase.google.com/docs/storage/android/download-files#download_data_via_url中的代码

我相信问题可能是postimagesreference也负责为存储中的图像生成随机ID,但是我不确定,因为我制作了一个称为postimagesreference 1的引用副本,但它仍然无法正常工作。要正确保存到数据库,我缺少什么吗?我应该在其他位置插入代码吗?

如果需要,这是我的完整代码:

公共类PostActivity扩展了AppCompatActivity {

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 StorageReference PostsImagesReference1;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

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

@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();
    //PostsImagesReference1 = 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()
{

    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", PostsImagesReference);

    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)
                    {


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

                StoringTextToFirebaseStorage();

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

}

java android firebase firebase-realtime-database firebase-storage
1个回答
1
投票

内部

 @Override

            public void onSuccess(Uri uri)
            {
                     String downloadUrl = uri.toString();
                     DatabaseReference db = FirebaseDatabase.getInstance().getReference();
                     db.child("users").child("pics").setValue(downloadUrl);

            }

uri.toString();将是您的下载URL :)

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();
            }
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.