0

I am following a series of videos on youtube from the channel CodingInFlow. They are a bit Outdated, 2017 is long time ago. The Video Series is great and I followed up the 4th video no problem, except one deprecated function that was easy enough to resolve. The file uploads to the Firebase Storage, but it doesn't show up in the Real Time Database

Main Class

public class MainActivity extends AppCompatActivity {

private static final int PICK_IMAGE_REQUEST = 1;
Button mButtonChooseImage;
Button mButtonUpload;
TextView mTextViewShowUploads;
EditText mEditTextFileName;
ImageView mImageView;
ProgressBar mProgressBar;

Uri mImageUri;

StorageReference mStorageRef;
DatabaseReference mDatabaseRef;


StorageTask mUploadTask;

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

    mButtonChooseImage = findViewById(R.id.button_choose_image);
    mButtonUpload = findViewById(R.id.button_upload);
    mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
    mEditTextFileName = findViewById(R.id.edit_text_file_name);
    mImageView = findViewById(R.id.image_view);
    mProgressBar = findViewById(R.id.progress_bar);

    mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");

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

    mButtonUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mUploadTask != null && mUploadTask.isInProgress()) {
                Toast.makeText(MainActivity.this, "Upload in Progress", Toast.LENGTH_SHORT).show();
            } else {
                uploadFile();
            }

        }
    });

    mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

}

private void openFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null) {
        mImageUri = data.getData();

        Picasso.get().load(mImageUri).into(mImageView);
    }
}

private String getFileExtension(Uri uri) {
    ContentResolver cR = getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cR.getType(uri));
}

private void uploadFile() {
    if (mImageUri != null) {
        StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(mImageUri));

        mUploadTask = fileReference.putFile(mImageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mProgressBar.setProgress(0);
                            }
                        }, 500);

                        Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show();
                        Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
                                taskSnapshot.getStorage().getDownloadUrl().toString());
                        String uploadId = mDatabaseRef.push().getKey();
                        //assert uploadId != null;
                        mDatabaseRef.child(uploadId).setValue(upload);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                        mProgressBar.setProgress((int) progress);
                    }
                });


    } else {
        Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
    }

}
}

My question is, is it my mistake that I missed something (I followed the video exactly, and checked the code on the channel's website), or is it that the functionality shifted and something needs to be added? The reason I ask is that the app works in the video, including the function that the checks for duplicate uploads, but in my reproduction, that function only works while the picture actually uploads, so there has been some shifting, but I don't even know where to start research, so I'm starting here.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
DJ. Aduvanchik
  • 332
  • 5
  • 17
  • `getDownloadUrl()` no longer directly returns the download URL, but nowadays (since May 2018) returns a `Task` which then returns the download URL as its result. So you need to do something like `getDownloadUrl().onSuccessListener` or `getDownloadUrl().onCompletion` listener to get the actual URL. See https://stackoverflow.com/questions/51056397/how-to-use-getdownloadurl-in-recent-versions/51064689#51064689 – Frank van Puffelen Feb 22 '20 at 22:37
  • @FrankvanPuffelen, I already fixed that, That's why I'm posting the question. ` taskSnapshot.getStorage().getDownloadUrl().toString());` and another solution I used `mStorageRef..getDownloadUrl().toString());`and I found others as well. I can post the upload to FireBase, but the RealTime Database remains null. – DJ. Aduvanchik Feb 22 '20 at 23:24
  • The `taskSnapshot.getStorage().getDownloadUrl().toString())` that you posted does not work on SDK versions since May 2018, nor does `mStorageRef.getDownloadUrl().toString())`. If you check your `upload` you'll see that it's a `Task...` instead of `https://...`. Aside from that: is *anything* from `.setValue(upload)` written to the database, or does nothing from `upload` show up? If nothing shows up, check your logcat output for a permission denied error, as that is the most common cause of failed database writes. – Frank van Puffelen Feb 23 '20 at 00:19
  • @FrankvanPuffelen, I found out what happened. I didn't change the rules in Firebase to allow read write for realtime database. I did it in cloud firestore and I assumed it was the same for Realtime beacuse they are on the same page. Then I started looking for answers on the moon. There is still an issue that needs resolving, but it's out of scope for this question and it isn't breaking the app. The app works otherwise. – DJ. Aduvanchik Feb 23 '20 at 00:38

1 Answers1

1

This is how I did mine. This code saves the image to the storage and to the firebase realtime database under the child "profile image" as a link.

public class Registration3 extends AppCompatActivity {

    Button elFin;
    CircleImageView ProfileImage;
    private DatabaseReference UsersRef;
    private FirebaseAuth mAuth;
    private StorageReference UserProfileImageRef;
    String currentUserID;
    final static int Gallery_Pick = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration3);

        mAuth = FirebaseAuth.getInstance();
       currentUserID = mAuth.getCurrentUser().getUid();
        elFin = findViewById(R.id.btn_dd);
        ProfileImage = findViewById(R.id.profile_imageUp);
       UsersRef = FirebaseDatabase.getInstance().getReference().child("DriversInformation").child(currentUserID);
       UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
        ProfileImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, Gallery_Pick);
            }
        });

        elFin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Registration3.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();

            CropImage.activity()
                    .setGuidelines(CropImageView.Guidelines.ON)
                    .setAspectRatio(1,1)
                    .start(this);


        }


        if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
        {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                Uri resultUri = result.getUri();

                StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");

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

                            Toast.makeText(Registration3.this, "Image Uplaoded", Toast.LENGTH_SHORT).show();

                            Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();

                            result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    final String downloadUrl = uri.toString();

                                    UsersRef.child("profileimage").setValue(downloadUrl)
                                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                                @Override
                                                public void onComplete(@NonNull Task<Void> task) {
                                                    if (task.isSuccessful()) {
                                                        Intent selfIntent = new Intent(Registration3.this, Registration3.class);
                                                        startActivity(selfIntent);

                                                        Toast.makeText(Registration3.this, "Image Uploaded", Toast.LENGTH_SHORT).show();

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

                                                    }
                                                }
                                            });
                                }
                            });
                        }
                    }
                });
            }
            else {
                Toast.makeText(Registration3.this, "Error: ", Toast.LENGTH_SHORT).show();

            }
        }
    }
}
Stradtdog
  • 1,490
  • 2
  • 7
  • 13