I am trying to utilise an image cropper (from ArthurHub GitHub) getting an error when typing getDownloadURL() i have put getStorage() in front using the getStorage() gets rid of the red line under getDownloadUrl however when I press crop I get the error message I have coded down the very end of this piece of code 'image cannot be cropped'. Does anyone know how to fix this
/*...*/ {
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable 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(requestCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait while we are 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 stored successfully to firebase storage", 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 occurred:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
}
else
{
Toast.makeText(this, "Error Occurred: Image can't be cropped try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
Related
I tried to share the image in my chat application. But was not able to successfully share it. It's selecting the image from the gallery but not appearing in the Userchat screen and not getting upload in the firebase also.
I am not able to find the solution for it. I would very much appreciate if someone can help me out.
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]
{
"Image", "Documents"
};
AlertDialog.Builder builder = new AlertDialog.Builder(UserChatActivity.this);
builder.setTitle("Select File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
if (i == 1)
{
checker = "pdf";
}
}
});
builder.show();
}
});
StorageReference
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && requestCode == RESULT_OK && data != null && data.getData() != null)
{
fileUri = data.getData();
if (!checker.equals("image"))
{
}
else if (checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files").child(fAuth.getUid());;
}
else
{
Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
}
}
}
Store that image URL in your chat.
You can do something like this, I am giving you an example for firebase realtime database:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// you should show some progress dialog or progress bar here for better user experience.
progressDialog.show()
fileUri = data.getData();
if (checker.equals("image")) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image files");
final String messgSenderRef = "Messages/" + mAuth.getCurrentUser().getUid() + "/" + userId;
final String messgReceiverRf = "Messages/" + userId + "/" + mAuth.getCurrentUser().getUid();
DatabaseReference messageRef = databaseReference.child("Messages").child(mAuth.getCurrentUser().getUid()).child(userId).push();
final String messagePushId = messageRef.getKey();
final StorageReference filepath = storageReference.child(messagePushId + "." + "jpg");
filepath.putFile(fileUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
// you can show progress of upload here, let suppose you have a progressDialog then:-
double p = ((double) 100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p + "%" + " Uploading....");
}
}).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()) {
progressDialog.dismiss();
// Now you have Uri of your image
downloadUri = task.getResult().toString();
Map<String, Object> messageTextBody = new HashMap<>();
messageTextBody.put("message", downloadUri);
messageTextBody.put("name", fileUri.getLastPathSegment());
messageTextBody.put("type", fileStatus);
messageTextBody.put("from", mAuth.getCurrentUser().getUid());
messageTextBody.put("to", userId);
messageTextBody.put("messageId", messagePushId);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map<String, Object> messageBodydetails = new HashMap<>();
// add message to sender and receiver's
messageBodydetails.put(messgSenderRef + "/" + messagePushId, messageTextBody);
messageBodydetails.put(messgReceiverRf + "/" + messagePushId, messageTextBody);
databaseReference.updateChildren(messageBodydetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
editText.setText("");
}
}
});
} else {
Toast.makeText(ChatActivity.this, "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
} else {
}
}
}
Then in the chat you can check for the changes in the database in realtime and update your chat's recycler view in realtime. Just specify the chat message type to identify and display the view accordingly. If the chat type is text, show the text message. If the chat type is an image, load an image from the URL you have stored.
I'm creating an application were users get to upload two type of image which is their profile picture and their profile cover picture. But I'm having issues defining the different process without interference from each other as I'm unable to call two onActivityResult.
this is the code I'm currently using to upload profile picture to firebase storage
coverbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICKER);
}
});
mImagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
mPdialog = new ProgressDialog(SettingsActivity.this);
mPdialog.setTitle("Uploading");
mPdialog.setMessage("please wait....");
mPdialog.show();
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.setMinCropWindowSize(500,500)
.start(SettingsActivity.this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
File file_thumb = new File(resultUri.getPath());
String current_uid = mCurrentuser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(file_thumb);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filepath = mImageReference.child("profile_images").child(current_uid + ".jpg");
final StorageReference thumb_path = mImageReference.child("profile_images").child("thumbs").child(current_uid + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
final String download_url = task.getResult().getDownloadUrl().toString();
UploadTask uploadTask = thumb_path.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
String thumb_downloadurl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()){
Map update_hashmap = new HashMap();
update_hashmap.put("image",download_url);
update_hashmap.put("thumb_image", thumb_downloadurl);
mDatabase.updateChildren(update_hashmap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
mPdialog.dismiss();
Toast.makeText(SettingsActivity.this,"success",Toast.LENGTH_LONG).show();
}
}
});
}else {
Toast.makeText(SettingsActivity.this,"failed",Toast.LENGTH_LONG).show();
mPdialog.dismiss();
}
}
});
}else {
Toast.makeText(SettingsActivity.this,"failed",Toast.LENGTH_LONG).show();
mPdialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
Try this
Move startActivityForResult & intent outside
Set intent requestCode according to which button was clicked
Intent galleryIntent = new Intent();
coverbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
}
});
mImagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
}
});
}
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICKER);
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 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();
}
}
});