0

I have read other posts with the same issue but I really don't understand where to put the code and what to do. Any help is appreciated.

 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", downloadUrl);
    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(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;


    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();
                downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();

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

This is my code. downloadUrl is meant to be the link of the image and is meant to be in the "image" postsmap.put.

 downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();

For some reason it saves as com.google.android.gms.tasks.zzu@ and not as a link. I looked at https://firebase.google.com/docs/storage/android/download-files#download_data_via_url but I really don't understand what to do, so could someone please help me by telling me what to replace? Here is my whole code:

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, saveCurrentTime, postRandomName, downloadUrl, 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();

    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", downloadUrl);
    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(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;


    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();
                downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();

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

}

updated code:

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();
                //downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        // Got the download URL for 'users/me/profile.png'
                    }
                }).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();
            }
        }
    });
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Getting a download URL requires a call to the server, so `getDownloadUrl()` returns a `Task`. And since you do `downloadUrl = task.getResult().getStorage().getDownloadUrl().toString()`, you're converting the task to a string. You need to add a completion/success listener to the task as shown here: https://firebase.google.com/docs/storage/android/download-files#download_data_via_url and here: https://stackoverflow.com/questions/37374868/how-to-get-url-from-firebase-storage-getdownloadurl – Frank van Puffelen Jun 01 '20 at 14:48
  • Do i add that under my original line of code? that is what I am confused about – STEVEBILLYBOB Jun 01 '20 at 14:56
  • Also storageref doesnt work and shows as error, When I write storagereference than .child can't be used. – STEVEBILLYBOB Jun 01 '20 at 15:00
  • The `downloadUrl = task.getResult().getStorage().getDownloadUrl().toString()` needs to go. What you need is `task.getResult().getStorage().getDownloadUrl(). addOnSuccessListener(...`. You can also get a reference to the storage location from `taskSnapshot.getStorage()`, so that'd make `taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(...`. See my answer here: https://stackoverflow.com/questions/51056397/how-to-use-getdownloadurl-in-recent-versions and documentation here: https://firebase.google.com/docs/storage/android/upload-files#get_a_download_url – Frank van Puffelen Jun 01 '20 at 15:44
  • So do I just copy and paste the code from the documentation? Also, storageRef is an error – STEVEBILLYBOB Jun 01 '20 at 15:53
  • Sorry, I don't know how to be any clearer about this. At this point, it's probably best if you edit your question to include the **updated** code where you are calling `getDownloadUrl().addOnSuccessListener`, so we can have a look at that. Please make sure it's a [minimal-but-complete reproduction](http://stackoverflow.com/help/mcve), as it's likely you don't need all the code you now have to reproduce it. For example: whle the writing to Realtime Database is part of your use-case, you can reproduce the problem without it. – Frank van Puffelen Jun 01 '20 at 16:18
  • Ok, I replaced the original downloadUrl line of code with the code at https://firebase.google.com/docs/storage/android/download-files#download_data_via_url. The only problem left is how do I get a thing to put in the hashmap instead of downloadurl? – STEVEBILLYBOB Jun 01 '20 at 16:48
  • Instead of `PostsImagesReference.child("Post Images").getDownloadUrl()...`, you need `.getDownloadIUrl()...`. – Frank van Puffelen Jun 01 '20 at 18:20
  • Ok, I made the code the same as you edited it but now post info doesn't get saved at all. Could it be to do something with postimagereference also being responsible for generating a random post image name ? Or am I not meant to put postimagereference in the "image" postsmap – STEVEBILLYBOB Jun 01 '20 at 20:00
  • It's hard to say at this point, as we've been going about it. If you now put a breakpoint in `onSuccess`, do you get the correct value for the download URL of the image. If so, it might be time to post a new question to show the remaining problem. – Frank van Puffelen Jun 01 '20 at 20:18
  • What should I title the question? And thanks for staying with me to try and resolve the problem. – STEVEBILLYBOB Jun 01 '20 at 20:23

0 Answers0