Peter Haddad
Peter Haddad

Reputation: 80914

Upload profile image for a user Firebase

I am trying to add an image to the user information in the real time database(firebase) for android. I have uploaded the image on the firebase storage but how will I be able to add the image in the database for that user?

Code Below:

//inside onCreate() method

img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(Intent.ACTION_PICK);
            i.setType("image/*");
            startActivityForResult(i,request_code);
        }
    });

Here I am clicking on the imageview, so I will be able to change it and get an image from the gallery.

Here I authenticate the user and send data to the database:

 auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(StudentSignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(StudentSignUpActivity.this, HomeActivity.class));
                                finish();
                            }
                        }
                    });

mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
            DatabaseReference newStudent=mDatabase.push();
            newStudent.child("email").setValue(email);
            newStudent.child("password").setValue(password);
            newStudent.child("name").setValue(name);
            newStudent.child("date").setValue(dates);
            newStudent.child("phone").setValue(number);
            newStudent.child("uid").setValue(mCurrentUser.getUid());


//outside of onCreate()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }
        });
    }
}

In the above code I have uploaded the image to the firebase storage. Now how will i be able to add that image as a child for a specific user.

I think I need to do something like this:

 newStudent.child("image").setValue(uri_here);

But I am unable to figure how to get the uri of the image and how to add that uri in the setValue() since its in another method.

Upvotes: 4

Views: 13773

Answers (2)

Leonardo Rick
Leonardo Rick

Reputation: 788

Just to update because I spent sometime to find this answer, getDownloadUrl() is NOT a function of taskSnapshot anymore. So in order to get the image URL from Firebase Storage you need to add a listener to taskSnapshot.getMetadata().getReference().getDownloadUrl()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                taskSnapshot.getMetadata().getReference().getDownloadUrl()
                    .addOnSuccessListener(new OnSuccessListener<Uri>() {

                    @Override
                    public void onSuccess(Uri uri) {
                        newStudent.child("image").setValue(uri);

                    }
                });
            }
        });
    }
}

Now it's safe to use uri to whatever you want

Upvotes: 3

Jen Person
Jen Person

Reputation: 7546

You can use the method getDownloadUrl() in the success listener to access the download URL:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri downloadUrl = taskSnapshot.getDownloadUrl();
                newStudent.child("image").setValue(downloadUrl);
            }
        });
    }
}

As an aside, instead of using push(), I recommend storing the user's data with the uid as the key. This will make your data easier to find.

private DatabaseReference newStudent;

mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
            newStudent=mDatabase.child(mCurrentUser.getUid());
            newStudent.child("email").setValue(email);
            // etc

Upvotes: 3

Related Questions