0

I want to upload my picture into my image into my database and save it as a url and then call it to my circle image view as a profile picture. But it's not being saved as a url and it's not showing up as a profile.

I have tried switching my code up. Invalidating and restarting android studio. Cleaning and rebuilding the project countless amounts of times. Wiped the data from my phone and my emulator. And I watched a bunch of videos and read answers here and elsewhere.

private Button UpdateAccountSettings;
private EditText userName, userStatus;
private CircleImageView userProfileImage;

private String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference RootRef;

private  static final int GalleryPick = 1;
private StorageReference UserProfileImagesRef;
private ProgressDialog loadingBar;

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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    RootRef = FirebaseDatabase.getInstance().getReference();
    UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");

    InitializeFields();

    userName.setVisibility(View.INVISIBLE);

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

            UpdateSettings();
        }
    });

    RetrieveUserInfo();

    userProfileImage.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, GalleryPick);

        }
    });
}

private void InitializeFields() {

    userName = (EditText) findViewById(R.id.set_user_name);
    userStatus = (EditText) findViewById(R.id.set_profile_status);
    userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
    loadingBar = new ProgressDialog(this);
    UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == GalleryPick  &&   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){

            loadingBar.setTitle("Set Profile Image");
            loadingBar.setMessage("Please wait your profile image is updating...");
            loadingBar.setCanceledOnTouchOutside(false);
            loadingBar.show();

            final Uri resultUri = result.getUri();

            StorageReference filePath = UserProfileImagesRef.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(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();

                        String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();

                        RootRef.child("Users").child(currentUserID).child("image")
                                .setValue(downloadUrl)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {

                                        if(task.isSuccessful()){

                                            Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        } else {

                                            String message = task.getException().toString();
                                            Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }
                                    }
                                });

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

                    }
                }
            });
        }
    }
}

private void UpdateSettings() {

    String setUserName = userName.getText().toString();
    String setStatus = userStatus.getText().toString();

    if(TextUtils.isEmpty(setUserName)){

        Toast.makeText(this, "Please enter your user name...", Toast.LENGTH_SHORT).show();
    }
    if(TextUtils.isEmpty(setStatus)){

        Toast.makeText(this, "Please write your status...", Toast.LENGTH_SHORT).show();
    }
    else {

        HashMap<String, Object> profileMap = new HashMap<>();
        profileMap.put("uid", currentUserID);
        profileMap.put("name", setUserName);
        profileMap.put("status", setStatus);

        RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if(task.isSuccessful()){

                            SendUserToMainActivity();
                            Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();

                        } else{

                            String message = task.getException().toString();
                            Toast.makeText(SettingsActivity.this, "Error:", Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }
}

private void RetrieveUserInfo() {

    RootRef.child("Users").child(currentUserID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image"))))
                    {

                        String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                        String retrieveStatus = dataSnapshot.child("status").getValue().toString();
                        String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

                        userName.setText(retrieveUserName);
                        userStatus.setText(retrieveStatus);
                        Picasso.get().load(retrieveProfileImage).into(userProfileImage);

                    }

                    else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
                    {

                        String retrieveUserName = dataSnapshot.child("name").getValue().toString();
                        String retrieveStatus = dataSnapshot.child("status").getValue().toString();

                        userName.setText(retrieveUserName);
                        userStatus.setText(retrieveStatus);
                    }

                    else {

                        userName.setVisibility(View.VISIBLE);
                        Toast.makeText(SettingsActivity.this, "Update your info", Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
}

private void SendUserToMainActivity() {

    Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(mainIntent);
    finish();
}

I want to upload the image into my Firebase database using an image URL and then display it in my circle image view as a profile picture.

EDIT !!

I uploaded that code and imported continuation but this is what I see now.

Code2

2 Answers2

0
   private void uploadImage() {

    if(filePath != null)
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();
        progressDialog.setCancelable(false);

        final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Toast.makeText(AdminPanel.this, "Uploaded", Toast.LENGTH_SHORT).show();
                       // Upload upload=new Upload( databaseReference.child(cat_spinner.getSelectedItem().toString()).child(databaseReference.push().getKey()).setValue(taskSnapshot.))

                        ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {

                              DatabaseReference url=  databaseReference.child(cat_spinner.getSelectedItem().toString()).child(databaseReference.push().getKey());

                                Upload upload=new Upload( uri.toString());
                                url.setValue(upload);
                                Intent Refresh=new Intent(AdminPanel.this, AdminPanel.class);
                                startActivity(Refresh);
                                finish();
                            }
                        });



                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(AdminPanel.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                .getTotalByteCount());

                        progressDialog.setMessage("Uploaded "+(int)progress+"%");

                    }
                });
    }
}
0

I think the update should be like this:

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

    filePath.putFile(resultUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
        @Override
        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
            if (!task.isSuccessful()) {
                throw task.getException();
            }

            // Continue with the task to get the download URL
            return filePath.getDownloadUrl();
        }}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

            if(task.isSuccessful())
            {

                Toast.makeText(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();

                String downloadUrl = task.getResult().toString();

                RootRef.child("Users").child(currentUserID).child("image")
                        .setValue(downloadUrl)
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                if(task.isSuccessful()){

                                    Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                } else {

                                    String message = task.getException().toString();
                                    Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                    loadingBar.dismiss();
                                }
                            }
                        });

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

            }
        }
    });
Luciano
  • 2,691
  • 4
  • 38
  • 64
  • I updated my question. I'm only seeing those two errors –  Apr 28 '19 at 19:28
  • Probably because you're missing an import import com.google.android.gms.tasks.Continuation; – Luciano Apr 28 '19 at 19:35
  • Here is a sample code from google: https://firebase.google.com/docs/storage/android/upload-files#get_a_download_url – Luciano Apr 28 '19 at 19:35
  • No I have it here `import com.google.android.gms.tasks.Continuation;` –  Apr 28 '19 at 19:38
  • Class 'Anonymous class derived from Continuation' must either be declared abstract or implement abstract method 'then(Task)' in 'Continuation –  Apr 28 '19 at 19:48
  • Which line of code saves it to the database as a url ? –  Apr 28 '19 at 20:13
  • putFile returns a task that upload the file, after that you do request to get the url by calling getDownloadUrl() in the continueWith block. And when both of the tasks are finished, onComplete will get called. – Luciano Apr 28 '19 at 20:42
  • I don't see where it's failing at all –  Apr 28 '19 at 20:45