I have an Android application, which has user authorization via Google+(or Gmail) and I want for each new user to save its Google+ avatar to Firebase Storage in order to use its somewhere in the app.
I can get the Uri of the avatar from GoogleSignInAccount
by calling personPhoto = account.getPhotoUrl();
.
After, I want to upload the avatar to Firebase Storage, so I can save a link to that avatar in my Firebase Database for users(one of the fields in this database will hold users' avatar).
I've been reading this guide on how to upload file to Firebase Storage. I've realized that users' avatar does not exist on the phone "for real", but I only have its Uri somewhere in my code.
One possible solution is to download the avatar to some folder on phone, and then use the guide I mentioned above.
However, I don't know how to download, and I think it is not the best solution to this problem.
What are the options here?
Here is the code of my onStart
method in MainActivity
, which does not work, since the avatar is not downloaded on phone.
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
databaseUsers = FirebaseDatabase.getInstance().getReference("users");
if (account == null) {
username.setText("Need to sign in");
email.setText("");
avatar.setImageResource(android.R.color.transparent);
}
else {
personName = account.getDisplayName();
personGivenName = account.getGivenName();
personFamilyName = account.getFamilyName();
personEmail = account.getEmail();
personId = account.getId();
personPhoto = account.getPhotoUrl();
username.setText(account.getDisplayName());
email.setText(account.getEmail());
final String cleanEmail = email.getText().toString().replaceAll("\\.", ",");
databaseUsers.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
if (!snapshot.child(cleanEmail).exists()) {
mProgress.setMessage("LUL");
mProgress.show();
mStorage = FirebaseStorage.getInstance().getReference();
InputStream stream = null;
try {
stream = new FileInputStream("some path here");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StorageReference filePath = mStorage.child("Avatar").child(personPhoto.getPath());
UploadTask uploadTask = filePath.putStream(stream);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mProgress.dismiss();
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(account.getPhotoUrl() != null){
Picasso.with(this).load(account.getPhotoUrl()).into(avatar);
}
else {
avatar.setImageResource(R.drawable.userdefault);
}
}
}