I am still learning hashmaps and database structures so please forgive me if this is a basic question. I've tried to research but nothing seems to work. I have a method in the same activity where I capture an image which is pushed to Firebase Storage. The image successfully goes to Firebase Storage, but I cannot figure out how to add the image to my hashmap to go to the Firebase Database. My hashmap is below and currently works.
Thank you for your help.
String title = title_edit_text.getText().toString();
String first_name = firstname.getText().toString();
String last_name = lastname.getText().toString();
if (TextUtils.isEmpty(title)) {
title_edit_text.setError("Input is required!");
} else {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
String creation_date= dateFormat.format(date);
DateFormat date_format_for_time = new SimpleDateFormat("hh:mm:ss a");
Date time = new Date();
String creation_time= date_format_for_time.format(time);
HashMap userMap = new HashMap();
userMap.put("title", title);
userMap.put("creation_date", creation_date);
userMap.put("creation_time", creation_time);
userMap.put("first_name", first_name);
userMap.put("last_name", last_name);
String upload = UsersReference2.push().getKey();
UsersReference2.child(upload).setValue(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
sendBackActivity();
Toast.makeText(Adding_Activity.this, "Successfully Save.", Toast.LENGTH_LONG).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(AddingActivity.this, "Error. Did Not Save: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
image_uri = data.getData();
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(3, 2)
.start(this);
}
// when pressing the crop button//
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
StorageReference filePath = CoverPostReference.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(Adding_Activity.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UsersReference2.child("cover_image").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(Adding_Activity.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Adding_Activity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
} else {
Toast.makeText(Adding_Activity.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();
}
}
}
You shouldn't/wouldn't store the image bitmap data into the hashmap, instead you should store the location to the bitmap (URI) to the hashmap (and database) and then use that to access the image.
Storing
Map<String, Uri> bitmapUriMap = new HashMap<String,Uri>();
bitmapUriMap.put("MyLocalBitmapName", UriOfBitmap);
Accessing
Then when you have the URI you just decode it
Uri uri = bitmapUriMap.get("MyLocalBitmapName);
Bitmap decodedUri = BitmapFactory.decodeFile(new File(uri.getPath()));
This is what you would store in the database. For instance if you want the image of a user, then you would store the image uri within your firebase database and then you would access it this way. Storing a bitmap in a database is not ideal and not recommended.
Related
I'm so new in coding and now I'm trying to write a socialnetwork app but i faced an error and I couldn't find any answer for that.
I could save my profile picture to firebase storage successfully but it I have to connect it to database so that I can use it later.
here is my code:
public class SetUpActivity extends AppCompatActivity
{
private EditText UserName, FullName , CountryName;
private Button SaveInfoButton;
private CircleImageView UserProfileImage;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
private DatabaseReference UserRef;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_up);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profile Image");
//storing profile image
UserName = (EditText) findViewById(R.id.setup_user_name);
FullName = (EditText) findViewById(R.id.setup_user_full_name);
CountryName = (EditText) findViewById(R.id.setup_user_country);
SaveInfoButton = (Button) findViewById(R.id.setup_information_button);
UserProfileImage = (CircleImageView) findViewById(R.id.set_up_profile_image);
loadingBar = new ProgressDialog( this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SaveAccountSetupInformation();
}
});
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,Gallery_Pick);
}
});
UserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
if(snapshot.exists()) {
if (snapshot.hasChild("profileimage"))
{
String image = snapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(UserProfileImage);
}
else
{
Toast.makeText(SetUpActivity.this, "Plese Select Profile Image First...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// some conditions for the picture
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
// crop the image
CropImage.activity(ImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
// Get the cropped image
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{ // store the cropped image into result
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we updating your profile image...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
//StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UserRef.child("profileimage").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(SetUpActivity.this, "Image Stored", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
});
}
});
}
else
{
Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
private void SaveAccountSetupInformation()
{
String username = UserName.getText().toString();
String userfullname = FullName.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(username))
{
Toast.makeText(this,"Please Write Your UserName", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(userfullname))
{
Toast.makeText(this,"Please Write Your Full Name", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country))
{
Toast.makeText(this,"Please Write Your Country", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Saving Information...");
loadingBar.setMessage("Please wait for a while...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
HashMap userMap = new HashMap();
userMap.put("username", username);
userMap.put("fullname", userfullname);
userMap.put("country", country);
userMap.put("status","Hey there, I am Using Pingoo");
userMap.put("gender", "none");
userMap.put("dob","None");
userMap.put("relationshipstatus","none");
UserRef.setValue(userMap).addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(SetUpActivity.this,"Your Account Has Been Created Successfully :) Enjoy!", Toast.LENGTH_LONG).show();
SendUserToMainActivity();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetUpActivity.this, "Oops!Something Went Wrong:(",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SetUpActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
I would appreciate if anyone could give me solution cause it's my school project and I really need to do it.
I've tried to find answer but i couldn't find it anywhere :(((
thank you in advance.
I am trying to display my image that stores successfully in Firebase. But whenever I try and display the image it returns a blank image and not the image stored. I think that the image name is wrong when being stored in Firebase. I also did research to try use Glide in my code but don't know how to implement it. I am using the latest dependencies for Firebase.
Code
#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();
UserProfileImageRef = 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 UpdateSettings() {
String setUserName = userName.getText().toString();
String setUserStatus = userStatus.getText().toString();
if (TextUtils.isEmpty(setUserName)) {
Toast.makeText(this, "Please write your user name first....", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setUserStatus)) {
Toast.makeText(this, "Please write your status....", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUserID);
profileMap.put("name", setUserName);
profileMap.put("status", setUserStatus);
profileMap.put("image", photoUrl);
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 successfully", 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() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image")))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();
photoUrl = retrieveProfileImage;
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
//Picasso.get().load(retrieveProfileImage).into(userProfileImage);
Picasso.get().load(retrieveProfileImage).resize(100,100).centerCrop().into(userProfileImage);
//Glide.with(SettingsActivity.this).load(retrieveProfileImage).into(userProfileImage);
}
else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name"))) {
String retrieveUserName = dataSnapshot.child("name").getValue().toString();
String retrieveUserStatus = dataSnapshot.child("status").getValue().toString();
userName.setText(retrieveUserName);
userStatus.setText(retrieveUserStatus);
}
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 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);
}
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();
}
#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(SettingsActivity.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 = 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(SettingsActivity.this, "Profile Image Uploaded Successfully", 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();
//Glide.with(SettingsActivity.this).load(downloadedUrl).into(userProfileImage);
}
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();
}
}
});
}
}
}
}
Realtime Database before
Realtime Database before - Watch User Warren
Realtime Database after
Realtime Database after - Watch User Warren
Storage before
Storage before adding image
Storage after
Storage after image added
I'm trying to make a chatting app in which I want users to upload images, and I'm using Firebase RealTime Database to store user's data. taskSnapshot.downloadUrl() method is deprecated, as I've used a different approach to upload images to Firebase as shown in documentation
https://firebase.google.com/docs/storage/android/upload-files
and this StackOverflow
post:taskSnapshot.getDownloadUrl() is deprecated
But still, image is not uploading to the database.
And I've also tried things like clean project, rebuild project, Invalidate and Restart.
This is the code I'm using to upload images to Firebase RealTime Database:
// ImagePickerButton shows an image picker to upload an image for a
message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
and then in onActivityResults method :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Toast.makeText(MainActivity.this, "Signed-In",
Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Signed-In Cancel",
Toast.LENGTH_SHORT).show();
finish();
} else if (requestCode == RC_PHOTO_PICKER && resultCode ==
RESULT_OK) {
Uri selectedUri = data.getData();
final StorageReference storageReference = mChatPhotosStorageReference.
child(selectedUri.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(selectedUri);
Task<Uri> uriTask = uploadTask.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 storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUrl = task.getResult();
FriendlyMessage message = new FriendlyMessage(null, mUsername, downloadUrl.toString());
mMessageDatabaseReference.push().setValue(message);
}
}
});
This is the Github link for full project: https://github.com/harshabhadra/FriendlyChat
Use this to upload photo to Firebase Storage in byte
private void uploadImage(byte[] data) {
submitButton.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
final String userId = DatabaseContants.getCurrentUser().getUid();
photo_description_edit_text.setVisibility(View.GONE);
StorageMetadata metadata = new StorageMetadata.Builder()
.setContentType("image/webp")
.build();
final String photoName = System.currentTimeMillis() + "_byUser_" + userId;
StorageReference imageRef = StorageConstants.getImageRef(photoName + ".webp");
UploadTask uploadTask = imageRef.putBytes(data, metadata);
final Resources res = getResources();
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = 100.0 * (taskSnapshot.getBytesTransferred() /
taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size,
// content-type, and download URL.
Log.d(LOG_TAG, "Image is successfully uploaded: " + taskSnapshot.getMetadata());
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Analytics.registerUpload(activity, userId);
PhotoModel photoModel = new PhotoModel(userId, photoDescription, "none",
0, 0, rotation, photoName + ".webp");
DatabaseContants.getPhotoRef().child(photoName).setValue(photoModel);
Utils.photosUploadedCounter++;
if (Utils.photosUploadedCounter % 2 == 0) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
NotificatonConstants.sendNotification(activity,
res.getString(R.string.failure_title),
res.getString(R.string.failure_message),
NotificatonConstants.UPLOAD_ID);
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
NotificatonConstants.sendNotification(activity,
res.getString(R.string.success_title),
res.getString(R.string.success_message),
NotificatonConstants.UPLOAD_ID);
}
});
}
Trying to get the downloadUrl link and put it into the "profile/imageURL" node on database.
I'm new to firebase and android development, so i was reading through release notes etc on storage and noticed in the notes and found information on downloadUrl. I understand there are plenty of questions on this topic but it's hard to apply it to this code.
"Deprecated the getDownloadUrl() and getDownloadUrls() methods of the StorageMetadata class. Use StorageReference.getDownloadUrl() instead."
But i'm trying to pull the downloadUrl link not from the metadata stored in firebase storage
I can successfully upload the picture to firebase storage but when i put the downloadUrl into firebase DB into the node i want. it inputs "com.google.android.gms.tasks.zzu#xxxxx"
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
I have tried the following 2 codes, This code outputs the uri com.google.xxxx
protected void onActivityResult( int requestCode, int resultCode, 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(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we are uploading image...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
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(ProfileActivity.this, "Profile Image stored Successfully to the the storage...", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Intent selfIntent = new Intent(ProfileActivity.this, ProfileActivity.class);
startActivity(selfIntent);
Toast.makeText(ProfileActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.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();
}
}
}
This second code was tried with the help of other users questions and trying to solve it that way. Although i get an error on .setValue(downloadUrl)
protected void onActivityResult( int requestCode, int resultCode, 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(resultCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait, while we are uploading image...");
loadingBar.setCanceledOnTouchOutside(true);
loadingBar.show();
Uri resultUri = result.getUri();
final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
}
});
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Intent selfIntent = new Intent(ProfileActivity.this, ProfileActivity.class);
startActivity(selfIntent);
Toast.makeText(ProfileActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.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();
}
}
}
Calling getDownloadUrl() returns a Task that asynchronously gets the download URL from the server. When it has retrieved the download URL, it calls onComplete/onSuccess. This means the download URL value is only available inside the onComplete/onSuccess method. Any code that needs the download URL needs to be inside onComplete/onSuccess.
So something like:
filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final String downloadUrl = uri.toString();
UserProfileRef.child("profile").child("imageURL").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
loadingBar.dismiss();
if(task.isSuccessful()) {
Intent selfIntent = new Intent(ProfileActivity.this, ProfileActivity.class);
startActivity(selfIntent);
Toast.makeText(ProfileActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
}
else {
String message = task.getException().getMessage();
Toast.makeText(ProfileActivity.this, "Error Occured..." + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
Now having the code inside the onSuccess is of course not going to be very reusable. So you may consider creating a custom callback interface as shown here. But the interface will be quite similar to the Task<Uri> interface in the example above, so I'm not sure it is worth the effort.
For an example of how to still keep the code separate from the onComplete by having your own custom callback interface, see getContactsFromFirebase() method return an empty list.
I have been looking through the Firebase documentation, as well as searches on stackoverflow, google, and YouTube for the following:
Creating a user registration that allows for email, password, and profile photo.
I am able to successfully add a user with their email and password but I can't seem to get the other information in(most importantly the profile photo). All the tutorials and documentation show how someone who is ALREADY a (logged in) User can upload a photo to firebase, but not for someone that's registering. Can someone help out here, how can I get the profile photo and first/lastname uploaded with the new users?
I am using FirebaseAuth to add the users.
This is what I have so far:
checkmarkImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.createUserWithEmailAndPassword(emailET.getText().toString(), passwordET.getText().toString())
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
Toast.makeText(RegisterActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
//progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(RegisterActivity.this, HomeActivity.class));
finish();
}
}
});
}
});
uploadProfilePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleChooseImage(view);
}
});
}
//END OF onCreate
//Separate methods
//Actually opens the CameraRoll
public void handleChooseImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE); //then goes to onActivityResult
}
public void handleInsertData(View v) {
}
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if(requestCode == RESULT_OK) {
Log.i("RegisterActivity", "case 0");
}
break;
case 1:
if(resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Log.i("RegisterActivity", "selected image = " + selectedImage);
}
break;
}
}
}
You need to signup first and then upload user image in storage this is standard way.
because as per firebase storage default rule user != null so must user auth state not null or else you can change firebase rule into public (it's not preferable)
i hope this will help you.
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
aDialog.show();
} else {
final String uid = task.getResult().getUser().getUid();
StorageReference filepath = mStorage.child("user_profile").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
if (progress == 100) {
hideProgressDialog();
//upload();
}
System.out.println("Upload is " + progress + "% done");
}
}).addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
System.out.println("Upload is paused");
}
}).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) {
/** Get Image Download Path**/
Uri downloadUri = taskSnapshot.getDownloadUrl();
/** Converting Image Uri In String **/
if (downloadUri != null) {
imagerls = downloadUri.toString();
}
//Add user data and image URL to firebase database
}
});
}
}
});
you can upload image regardless of the registration of the user on the firebase,
however, you would need the user reference to save the image to get it again when the user signs in, and you can't have that user's reference if the user is not already registered.
makes sense? :)
It may be a little late, but for anyone else coming here for a reliable answer, I'll show you how I achieved exactly that.
I have a POJO class CreatedUserDetail, with email and photo fields.
I also created a User class:
public class User{
private String uid;
private String password;
private String email;
private String photo;
public User( String email, String photo, String password ){
this.email = email;
this.photo = photo;
this.password = password;
}
public void saveToFirebase(){
CreatedUserDetail userDetail = new CreatedUserDetail();
userDetail.setEmail( email );
userDetail.setImage( photo );
FirebaseDatabase.getInstance()
.getReference()
.child( "Users" )
.child( uid ).setValue( userDetail );
}
private void uploadProfileImage(){
final StorageReference mStorageReference = FirebaseStorage.getInstance()
.getReference()
.child( "pics" +
uid +
photo.substring( photo.lastIndexOf( "." ) ) );
UploadTask uploadTask = mStorageReference.putFile( Uri.fromFile( new File( photo ) ) );
uploadTask.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 mStorageReference.getDownloadUrl();
}
} ).addOnCompleteListener( new OnCompleteListener< Uri >(){
#Override
public void onComplete( #NonNull Task< Uri > task ){
if( task.isSuccessful() ){
photo = task.getResult().toString();
FirebaseDatabase.getInstance().getReference( "Users" )
.child( uid )
.child( "image" )
.setValue( photo );
}
}
} );
}
public void RegisterUser( final OnUserRegistrationCallback onUserRegistrationCallback ){
FirebaseAuth.getInstance()
.createUserWithEmailAndPassword( email, password )
.addOnSuccessListener( new OnSuccessListener< AuthResult >(){
#Override
public void onSuccess( AuthResult authResult ){
uid = authResult.getUser().getUid();
saveToFirebase();
uploadProfileImage();
}
} )
.addOnFailureListener( new OnFailureListener(){
#Override
public void onFailure( #NonNull Exception e ){
}
} );
}
}
As you can see, it has a RegisterUser function, which first creates a user in Firebase Authentication with given email and password. Once it has been registered, I create a user in Firebase Database with email and LOCAL PATH to photo. Meanwhile, it also uploads the photo to Firebase Storage. And finally, on completion of the upload, I update the Firebase Database node with the downloadUrl of the recently uploaded photograph.
And in the activity, I just do this:
mUserWithEmailAndPassword = new User( mEmailToVerify, mLocalPath, mPass );
mUserWithEmailAndPassword.RegisterUser();
And that's all. You can include a callback to show a Toast or a redirect to another activity.