java – Item Doesn't seem to upload to Firebase Realtime Database while using Android-ThrowExceptions

Exception or error:

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.

How to solve:

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

            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *