0

I know you guys can help me on this. Been going through every related topic on SOF and also referred to Firebase docs, but still need some help.

Just like the docs are pointing out I am trying to get url through getDownloadUrl() with success completion. But it still returns a task which looks like 'com.google.android.gms.tasks.zzu@f470008'.

UPDATE:

In this fragment, i am trying to upload a Post object to Firebase Database. Everything works fine except the image url and just like the Docs are pointing out, taskSnapshot.getDownloadUrl() no longer works. The method getDownloadUrl() needs to be attached to a success completion. But in my case firebase still returns a task instead of url.

I've gone through all the related questions but my problem seems more different.

Here's the whole code from my Fragment;

public class PostFragment extends Fragment implements SelectPhotoDialog.OnPhotoSelectedListener{


    private static final String TAG = "PostFragment";
    private FrameLayout parentFrameLayout;
    private FirebaseFirestore firebaseFirestore;

    ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance

    @Override
    public void getImagePath(Uri imagePath) {
        Log.d(TAG, "getImagePath: setting the image to imageview");
        Glide.with(this).load(imagePath.toString()).into(mPostImage);
        //imageLoader.displayImage("", mPostImage);
        mSelectedBitmap = null;
        mSelectedUri = imagePath;

    }

    @Override
    public void getImageBitmap(Bitmap bitmap) {
        Log.d(TAG, "getImageBitmap: setting the image to imageview");
        mPostImage.setImageBitmap(bitmap);
        mSelectedUri = null;
        mSelectedBitmap = bitmap;

    }

    //widgets
    private ImageView mPostImage;
    private EditText mTitle, mDescription, mPrice, mCountry, mStateProvince, mCity, mContactEmail;
    private Button mPost;
    private ProgressBar mProgressBar;

    //vars

    private Bitmap mSelectedBitmap;
    private Uri mSelectedUri;
    private double mProgress = 0;
    private byte[] mUploadBytes;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_post, container, false);
        mPostImage = view.findViewById(R.id.post_image);
        mTitle = view.findViewById(R.id.input_title);
        mDescription = view.findViewById(R.id.input_description);
        mPrice = view.findViewById(R.id.input_price);
        mCountry = view.findViewById(R.id.input_country);
        mStateProvince = view.findViewById(R.id.input_state_province);
        mCity = view.findViewById(R.id.input_city);
        mContactEmail = view.findViewById(R.id.input_email);
        mPost = view.findViewById(R.id.btn_post);
        mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);

        parentFrameLayout = getActivity().findViewById(R.id.activity_register);

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        init();

        return view;
    }

    public void init(){

        mPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: opening dialog to choose new photo");
                SelectPhotoDialog dialog = new SelectPhotoDialog();
                dialog.show(getParentFragmentManager(), getString(R.string.dialog_select_photo));
                dialog.setTargetFragment(PostFragment.this, 1);

            }
        });

        mPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "attempting to post");
                if (!isEmpty(mTitle.getText().toString())
                        && !isEmpty(mDescription.getText().toString())
                        && !isEmpty(mPrice.getText().toString())
                        && !isEmpty(mCountry.getText().toString())
                        && !isEmpty(mStateProvince.getText().toString())
                        && !isEmpty(mCity.getText().toString())){
                    if (mSelectedBitmap != null && mSelectedUri == null ){
                        uploadNewPhoto(mSelectedBitmap);
                    }
                    else if (mSelectedBitmap == null && mSelectedUri != null){
                        uploadNewPhoto(mSelectedUri);
                    }
                }else {
                    Toast.makeText(getActivity(), "Bütün Boşlukları Doldurmanız Gerekiyor!", Toast.LENGTH_LONG).show();
                }

            }
        });
    }

    private void uploadNewPhoto(Bitmap bitmap){
        Log.d(TAG, "uploadNewPhoto: uploading a new image bitmap to storage ");
        BackgroundImageResize resize = new BackgroundImageResize(bitmap);
        Uri uri = null;
        resize.execute(uri);
    }

    private void uploadNewPhoto(Uri imagePath){
        Log.d(TAG, "uploadNewPhoto: uploading a new image uri to storage");
        BackgroundImageResize resize = new BackgroundImageResize(null);
        resize.execute(imagePath);
    }

    public class BackgroundImageResize extends AsyncTask<Uri, Integer, byte[]> {
        Bitmap mBitmap;

        public BackgroundImageResize(Bitmap bitmap){
            if (bitmap != null){
                this.mBitmap = bitmap;
            }
        }
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            Toast.makeText(getActivity(), "Fotoğraf işleniyor", Toast.LENGTH_SHORT).show();
            showProgressBar();
        }

        @Override
        protected byte[] doInBackground(Uri... params){
            Log.d(TAG, "doInBackground: başladı");
            if (mBitmap == null) {
                try {
                    //RotateBitmap rotateBitmap = new RotateBitmap();
                    mBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), params[0]);
                    ///mBitmap = rotateBitmap.HandleSamplingAndRotationBitmap(getActivity(), params[0]);
                }catch (IOException e){
                    Log.e(TAG, "doInBackground: IOException:" + e.getMessage());
                }
            }
            byte[] bytes = null;
            Log.d(TAG, "doInBackground: megabytes before compression: " + mBitmap.getByteCount() / 1000000 );
            bytes = getBytesFromBitmap(mBitmap, 100);
            Log.d(TAG, "doInBackground: megabytes before compression: " + bytes.length / 1000000 );
            return bytes;

        }
        @Override
        protected void onPostExecute(byte[] bytes){
            super.onPostExecute(bytes);
            mUploadBytes = bytes;
            hideProgressBar();
            executeUploadTask();
        }
    }

    private void executeUploadTask() {
        Toast.makeText(getActivity(), "Fotoğraf Yükleniyor", Toast.LENGTH_LONG).show();

        final String postId = FirebaseDatabase.getInstance().getReference().push().getKey();

        final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
                .child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
                        "/" + postId + "/post_image");




        UploadTask uploadTask = storageReference.putBytes(mUploadBytes);
        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {



            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(getActivity(), "İlanınız Onay Sürecine Alınmıştır", Toast.LENGTH_LONG).show();

                ///Insert the donload uri into the firebase database.

                DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

                StorageReference storageRef = FirebaseStorage.getInstance().getReference();
                StorageReference dateRef = storageRef.child("posts/users/");
                dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri downloadUrl)
                    {
                        //do something with downloadurl
                        Uri firebaseUri = downloadUrl;

                        Post post = new Post();
                        post.setImage(downloadUrl.toString());
                        post.setCity(mCity.getText().toString());
                        post.setDescription(mDescription.getText().toString());
                        post.setPost_id(postId);
                        post.setPrice(mPrice.getText().toString());
                        post.setTitle(mTitle.getText().toString());
                        post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());

                        reference.child(getString(R.string.node_posts))
                                .child(postId)
                                .setValue(post);

                        resetFields();


                    }
                });



            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getActivity(), "Fotoğraf Yüklenemedi", Toast.LENGTH_LONG).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                if ( currentProgress > (mProgress + 15)){
                    mProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    Log.d(TAG, "onProgress: upload is " + "& done");
                    Toast.makeText(getActivity(), mProgress + "%", Toast.LENGTH_LONG).show();
                }
            }

        });

    }

Dinotic
  • 3
  • 4
  • If this marked duplicate doesn't help, please ask a new question that more clearly illustrates what the problem is. Since your code doesn't log or print anything that we can clearly see, it's not possible to tell what you're doing wrong. Use the `downloadUrl` in your code to find the actual download URL of the file. – Doug Stevenson May 29 '20 at 15:44
  • My bad. I'll take a look at it. – Dinotic May 29 '20 at 15:48
  • @DougStevenson At first glance this code looks to be doing the correct thing: `post.setImage(downloadUrl.toString())`, with `downloadUrl` being the `public void onSuccess(Uri downloadUrl)`. So I don't think this is a duplicate (even though many similar questions indeed are). – Frank van Puffelen May 29 '20 at 15:55
  • @FrankvanPuffelen Unfortunately, the question doesn't say what is being examined here, and we don't have a guarantee that it's `downloadUrl` at all. The observed output is the toString of a Task object, which we also can't see. – Doug Stevenson May 29 '20 at 15:57
  • @DougStevenson just updated the question with more details. The duplicate you've marked examines a new way to get the url from Firebase because the question features a deprecated method. I am already following the docs Firebase provided. And still nothing changes. Any help would greatly be appreciated. – Dinotic May 29 '20 at 17:11
  • There is nothing deprecated about the accepted answer in that other question. The answer was written by the Firebase engineer that built the SDK. Use the getDownloadUrl method on the StorageReference that points to the object in storage. – Doug Stevenson May 29 '20 at 17:12
  • I didn't complain about accepted answer. Just take closer look at my code, I've tried his way and still something wrong. Can you just open the question back and let the users help please? – Dinotic May 29 '20 at 17:34
  • Hey Dinotic. Doug is partially correct: the `com.google.android.gms.tasks.zzu@f470008` you mention almost certainly comes from something like `uploadTask.getDownloadURL().toString`. Can you point out in the code where this happens "in my case firebase still returns a task instead of url"? – Frank van Puffelen May 29 '20 at 22:18

0 Answers0