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
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+"%");
}
});
}
}
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();
}
}
});
Related
I'm new to android development and I have used firebase inside the project and tried all the ways to show the user profile picture inside the image view but none of the solutions works for me. Uploading profile image to firebase is working fine whenever I click on the save button the profile image and cover image uploaded successfully but it's not showing inside the imageview
public class Profile extends AppCompatActivity {
public static final int CAMERA_PERMISSION_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
public static final int PICK_IMAGE_REQUEST = 111;
private Uri uri;
private Uri coverUri;
EditText fullName, email, phone;
Button saveProfileBtn, logoutProfileBtn;
ImageView userProfileImage, userCoverImage;
ImageButton cameraBtn, userCoverBtn;
FirebaseStorage storage;
StorageReference storageReference;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
FirebaseUser fUser;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3498DB"));
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Profile Settings </font>"));
fullName = findViewById(R.id.userNameProfile);
email = findViewById(R.id.emailUserProfile);
phone = findViewById(R.id.phoneNoProfile);
saveProfileBtn = findViewById(R.id.saveBtnProfile);
logoutProfileBtn = findViewById(R.id.logoutBtn);
userProfileImage = findViewById(R.id.proImgProfile);
cameraBtn = findViewById(R.id.cameraBtnProfile);
userCoverImage = findViewById(R.id.coverPhotoPS);
userCoverBtn = findViewById(R.id.coverImageUpload);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(10);
// uploadImage();
}
});
userCoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(20);
}
});
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
fullName.setText(value.getString("fname"));
email.setText(value.getString("email"));
phone.setText(value.getString("phone"));
}
});
saveProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage(); //Calling function to upload profile image
coverUploadImage(); //Calling function to upload cover image
String fname = fullName.getText().toString();
String femail = email.getText().toString();
String fphone = phone.getText().toString();
if (TextUtils.isEmpty(fname)) {
fullName.setError("Please Enter Your Full Name");
return;
}
if (TextUtils.isEmpty(femail)) {
email.setError("Please Enter Your Email Address");
return;
}
if (fphone.length() < 10) {
phone.setError("Phone Number Shouble Be 10 Digit");
return;
}
if (TextUtils.isEmpty(fphone)) {
phone.setError("Please Enter Your Phone Number");
return;
}
DocumentReference documentReference =
FirebaseFirestore.getInstance().collection("users").document(userID);
Map<String, Object> user = new HashMap<>();
user.put("fname", fname);
user.put("email", femail);
user.put("phone", fphone);
documentReference.update(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(Profile.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this, "Failed to Update the Profile", Toast.LENGTH_SHORT).show();
}
});
}
});
logoutProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), login.class));
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10) {
uri = data.getData();
userProfileImage.setImageURI(uri);
}
if (requestCode == 20)
{
coverUri = data.getData();
userCoverImage.setImageURI(coverUri);
}
}
private void showUploadedImage() {
Uri uri = fUser.getPhotoUrl();
Glide.with(this).load(uri).into(userProfileImage);
}
// Function to upload profile image
private void uploadImage() {
if (uri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Profile Image");
progressDialog.show();
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Profile Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Uploaded Profile Picture"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
// Function to upload cover image
private void coverUploadImage() {
if (coverUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Cover Picture");
progressDialog.show();
StorageReference ref =
storageReference.child("userCoverImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Cover Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Upload Cover Picture"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
public void saveDocument(View view) {
}
}
You are saying that the uploading is working successfully, so try another way to get the image URL from storage and put the link in the hashmap with the user's phone, name, and email after uploading the image.
So try this:
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
// Use add on progress like this.
ref.putFile(uri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
}
}).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();
}
return ref.getDownloadUrl();
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoUrl = uri.toString();
// This is the uri that you want to use after to put in the user's hashmap
Glide.with(MainActivity.this).load(photoUrl).into(userProfileImage);
}
});
After I save my profile image it says image updated but when I open settings again it does not show any image; instead, a white screen. It shows the status though.
Here is my code:
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 view) {
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() {
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
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);
}
#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();
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 Image Uploded succesfully...", Toast.LENGTH_SHORT).show();
final String downloadedUrl = task.getResult().getStorage().getDownloadUrl().toString();
Rootref.child("Users").child(currentUserID).child("image")
.setValue(downloadedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this,"Image saved in database Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this,"", 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 write your username first..", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(setStatus)){
Toast.makeText(this,"Please write your Status first..", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("Status", setStatus);
Rootref.child("Users").child(currentUserID).setValue( profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile Updated Succesfully...", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void RetrieveUserInfo()
{
Rootref.child("Users").child(currentUserID)
.addValueEventListener(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") ) &&(dataSnapshot.hasChild("image")))
{
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrievesStatus = dataSnapshot.child("Status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
Picasso.get().load(retrieveProfileImage).into(userProfileImage);
}
else if((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
{
String retrieveUserName = Objects.requireNonNull(dataSnapshot.child("name").getValue()).toString();
String retrievesStatus = Objects.requireNonNull(dataSnapshot.child("Status").getValue()).toString();
userName.setText(retrieveUserName);
userStatus.setText(retrievesStatus);
}
else{
userName.setVisibility(View.VISIBLE);
Toast.makeText(SettingsActivity.this, "Please set & update your profile information...", 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();
}
}
My logcat does not show any error, please help me.
I tried to resolve this with similar threads and answers here but completely failed.
My image is getting stored in firebase storage, and the database upload link is working but its always the wrong link. I get "com.google.android.gms.tasks.zzu#8045166" so the image is not displaying on the app
This is the overall code with the old version of GetDownloadUrl
private void InitializeFields()
{
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
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);
SettingsToolBar = (Toolbar) findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
#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();
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 Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
//--------------------------------------------->>
final String downloaedUrl = task.getResult().getDownloadUrl().toString(); **
//---------------------------------------------<<
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloaedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Image save in Database, Successfully...", 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();
}
}
});
}
}
}
i tried this
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if (task.isSuccessful())
{
//--- what i tried instead of: final String downloaedUrl = task.getResult().getDownloadUrl().toString();
final String downloadUrl = filePath.getDownloadUrl().toString();
Toast.makeText(SettingsActivity.this, "Profile Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
The method getDownloadUrl() is executed asynchronously. So you can't call toString() directly after. You will need to attach a callback. Also, getDownloadUrl() in UploadTask.TaskSnapshot is deprecated. So you can do this instead:
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();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
// retrieve your uri here
Uri downloadUri = task.getResult();
Log.d("TEST", "download uri: " + downloadUri.toString());
} else {
// load failed. Handle exception from task.getException()
}
}
});
If i give to the Picasso's load() method any photo url as parameter, the photo uploads, but when i give the load() method the parameter "image" as you can see in following code, the image is not displayed on the android device. The device displays the placeholder.
Also, the downloadUrl string form the onActivityResult() method is the same as the one from the image string.
Please help!
currentUserId = mAuth.getCurrentUser().getUid();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
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, galleryPick);
}
});
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if(dataSnapshot.hasChild("profileimage")){
String image = dataSnapshot.child("profileimage").getValue().toString();
//Glide.with(SetupActivity.this).load(image).placeholder(R.drawable.profile).into(profileImage);
Picasso.get().load(image).placeholder(R.drawable.profile).into(profileImage);
} else {
Toast.makeText(SetupActivity.this, "Please select profile image first...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#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(imageUri)
.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("Profile image");
loadingBar.setMessage("Please wait, while we're updating your profile image...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
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(SetupActivity.this, "Profile image successfully stored in Firebase database...", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().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(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
Toast.makeText(SetupActivity.this, "Profile image stored to Firebase database successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else{
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
} else {
Toast.makeText(this, "Error occured: Image can't be cropped. Try again!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
I want to save image url in real-time database but none of the solutions that I tried is solve the problem, the code that I wrote it saving the image in firebase storage but I want to save the image url in real-time database, so can anyone help?
this code just save the image in firebase storage
private Button btn_upload,btn_choose;
private ImageView imageView;
private Uri filepath;
private FirebaseStorage storage;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_choose= (Button) findViewById(R.id.btn_choose);
btn_upload= (Button) findViewById(R.id.btn_upload);
imageView= (ImageView) findViewById(R.id.myImage);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
btn_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadImage();
}
});
btn_choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
}
// choose image function code
private void uploadImage() {
if(filepath!=null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("images/" + UUID.randomUUID().toString());
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progres = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded"+(int)progres+"%");
}
}) ;
} }
I want to store image in real-time database
You can request download URL for the file after uploading finishes.
Then Add the URL to Real-time Database
reference.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Image uploaded", Toast.LENGTH_SHORT) .show();
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//You will get donwload URL in uri
Log.d(TAG, "Download URL = "+ uri.toString());
//Adding that URL to Realtime database
mDatabase.child("imageUrl").setValue(uri.toString());
}
});
}
})
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private void uploadImage() {
name = txtname.getText().toString();
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
StorageReference ref = storageReference.child("images/"+ name);
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.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+"%");
}
});
}
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}