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.
Related
I'm trying to make a database of users with profile pictures(stored in storage) related to their IDs.
I'm using Firebase auth,Realtime database and Realime storage.
The code work like this : In user registration process, they choose username and picture. The database is filled with Users -> userUUid -> username and URL of picture stored.
The storage stores the picture.
If I keep such name of the table (Users) code works fine, however if I try to manipulate the tables, for example if I want to make more categories like Users -> SpecialUsers / NormalUsers -> userUUid -> ... the app just crashes.. I tried debugging but saw no errors.
Is there any way how to catch these Firebase exceptions (if there is any) or any explanation why if I change the structure of the tables, the code doesn't work ?
These is the method responsible for the registration :
(this one works)
public void signUp(String email,String password,String userName)
{
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful())
{
dbReference.child("Users").child(auth.getUid()).child("userName").setValue(userName);
//if user choose some picture
if(imageControl)
{
UUID randomID = UUID.randomUUID(); //create random UUID for the picture
final String imageName = "images/"+randomID+".jpg";
storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageReference myStorageRef = firebaseStorage.getReference(imageName);
myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String filePath = uri.toString();
dbReference.child("Users").child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
else
{
dbReference.child("Users").child(auth.getUid()).child("image").setValue("null");
}
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
}
});
}
This doesn't work :
(As you can see the only thing changed is the structure of the tables from only 'Users' to 'superUsers' -> 'anotherCategory')
public void signUp(String email,String password,String userName)
{
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful())
{
dbReference.child("superUsers").child('anotherCategory').child(auth.getUid()).child("userName").setValue(userName);
//if user choose some picture
if(imageControl)
{
UUID randomID = UUID.randomUUID(); //create random UUID for the picture
final String imageName = "images/"+randomID+".jpg";
storageReference.child(imageName).putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageReference myStorageRef = firebaseStorage.getReference(imageName);
myStorageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String filePath = uri.toString();
dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue(filePath).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegistrationActivity.this, "Write to database is successful.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Write to database is not successful.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
else
{
dbReference.("superUsers").child('anotherCategory').child(auth.getUid()).child("image").setValue("null");
}
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(RegistrationActivity.this, "There is a problem.", Toast.LENGTH_SHORT).show();
}
});
}
I suspect that the errors occurs somewhere after imageControl check.
In the second example of the code, the tables superUsers -> anotherCategory tables are created in the database, however the reference to the picture UUids is empty (not even null is placed)
What could be the error if nothing relevant to the process of storing pictures is changed ?
I'm trying to upload a picture to firebase storage and the take picture is in the form of a bitmap. But I don't want any authentication at all so I have followed the Firebase tutorial on anonymous login. When running the app I don't get any errors but the picture won't upload. I don't really care if the picture taking part is perfect, right now I want to focus on the uploading onto Firebase.
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
ImageView imageView;
Button btnOpen;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
imageView = findViewById(R.id.image_view);
btnOpen = findViewById(R.id.btn_open);
textView = findViewById(R.id.textView);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.CAMERA
}, 100);
}
btnOpen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 100);
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
Log.e("USER", currentUser.toString());
}
public void signInAnonymously() {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInAnonymously:success");
FirebaseUser user = mAuth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInAnonymously:failure", task.getException());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
assert data != null;
Bitmap takenImage = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
signInAnonymously();
// saveImage(takenImage);
imageView.setImageBitmap(takenImage);
}
}
private void saveImage(Bitmap inBitmap) {
long tsLong = System.currentTimeMillis() / 1000;
String ts = Long.toString(tsLong);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://savephototest.appspot.com");
StorageReference mountainImagesRef = storageRef.child(ts + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inBitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainImagesRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getUploadSessionUri();
Log.d("downloadUrl-->", "" + downloadUrl);
}
});
}
}
You are starting the upload of the image before the sign-in (which happens asynchronously) completes. So if you have security rules on storage that the user is signed in before they can upload, that means the write will be rejected.
Since you're leaving onFailure empty, you won't see that error. So the first step to verify if this is happening is to not ignore the error, but surface it. For example with:
public void onFailure(#NonNull Exception exception) {
throw exception;
}
If this is indeed the cause of the problem, you'll need to ensure that the upload only starts after the sign-in has been completed.
A very quick way to do that is to move the call to saveImage into the method that signs in:
public void signInAnonymouslyAndUpload() {
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("TAG", "signInAnonymously:success");
FirebaseUser user = mAuth.getCurrentUser();
saveImage(takenImage);
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInAnonymously:failure", task.getException());
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
assert data != null;
Bitmap takenImage = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
signInAnonymouslyAndUpload();
imageView.setImageBitmap(takenImage);
}
}
Im trying to allow users to click on the image item and choose a picture from their galley. this picture should then be pushed to firebase and added to the image view automatically but it is showing up blank after I close the application. I have tried numerous methods but cant seem to get it working. here is where i implement everything:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ImageView imageView;
public static final int IMAGE_CODE = 1;
Uri imageUri;
private StorageReference storageReference;
private DatabaseReference databaseReference;
FirebaseUser user;
String userid;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) headerView.findViewById(R.id.profilepic);
user = FirebaseAuth.getInstance().getCurrentUser();
userid = user.getUid();
storageReference = FirebaseStorage.getInstance().getReference("Images");
databaseReference = FirebaseDatabase.getInstance().getReference("uploads").child(userid);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openimage();
}
});
profileImage();
}
private void profileImage(){
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void openimage() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGE_CODE);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
if (!Settings.canDrawOverlays(this)) {
// You don't have permission
checkPermission1();
} else {
// Do as per your logic
}
}
if (requestCode == IMAGE_CODE && resultCode == RESULT_OK && null != data && data.getData() != null) {
imageUri = data.getData();
Glide.with(this).load(imageUri).into(imageView);
fileUploader();
}
}
private String getFileExtension(Uri uri){
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
}
private void fileUploader(){
if(imageUri != null){
StorageReference reference = storageReference.child(userid + ".jpeg");
reference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload = new Upload(uri.toString());
databaseReference.setValue(upload).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
profileImage();
}
});
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
;;
}
});
}else{
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
}
Database Structure
Edit:
2020-05-03 15:55:51.232 25230-25407/com.example.carcrashdetection E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-05-03 15:55:51.235 25230-25407/com.example.carcrashdetection E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage##19.1.1:433)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage##19.1.1:450)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage##19.1.1:441)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage##19.1.1:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage##19.1.1:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage##19.1.1:76)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Also the image is in a navigation drawer and should be unique to each user. Can someone please tell me where I am going wrong?
You can do it like this:
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Upload upload = new Upload(uri.toString());
String uploadId = databaseReference.child(userid).push().getKey();
databaseReference.child(uploadId).setValue(upload);
}
});
Firebase Storage docs
And there is a problem in this line:
Glide.with(getApplicationContext()).load(upload).into(imageView);
upload is an object. You should use upload.getUploadUri()
if(dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
Upload upload = ds.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
}
You always see last uploaded image this way. If a user has an image you don't need to use uploadId.
Profile image:
Upload upload = new Upload(uri.toString());
databaseReference.setValue(upload);
and:
if(dataSnapshot.exists()) {
Upload upload = dataSnapshot.getValue(Upload.class);
Glide.with(getApplicationContext()).load(upload.getUplaodUri()).into(imageView);
}
more useful for you.
I'm trying to add an image to the Firebase storage, where each user can upload his profile picture from his files or camera, and it should be stored in his own folder that has his uid as name. I have the following code, however pressing on the ImageView doesn't do anything:
public class ProfileFragment extends Fragment {
CircleImageView profileImage;
TextView email;
public StorageReference storageRef;
FirebaseStorage storage;
public static ProfileFragment newInstance() {
ProfileFragment profileFragment = new ProfileFragment();
return profileFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
profileImage = view.findViewById(R.id.profile_image);
email = view.findViewById(R.id.email);
String user = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email.setText(user);
storageRef = storage.getReference();
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final String userUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final Uri contentURI = data.getData();
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(contentURI != null) {
StorageReference childRef = storageRef.child("/images/"+ userUid +".jpg");
UploadTask uploadTask = childRef.putFile(contentURI);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Upload Failed" + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(getActivity(), "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
}
From what I've read, onActivityResult doesn't work with fragments, however I can't think or find any topics of how it should be done to work. Could somebody please help me with making this work, and also, how do I fetch the profile picture of each user after I've uploaded it? I'm using the built in Firebase Authentication system with Email, Google and Facebook authentication, and I'm trying to make it work without storing users additionally in the database.
Thanks in advance!
Try this below snippet :
Step 1:- Add the firebase storage dependency in build.gradle (Module:app)file. Latest Dependency for firebase storage is:
implementation 'com.google.firebase:firebase-storage:19.1.0'
Step 2:-Setting up the activity_main.xml layout file
Step 3:-Setting up the MainActivity.java file
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReference();
private void uploadImage()
{
if (filePath != null) {
// Code for showing progressDialog while uploading
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
// Defining the child of storageReference
StorageReferenceref=storageReference.child("images/"+UUID.randomUUID().toString();
// adding listeners on upload
// or failure of image
ref.putFile(filePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
// Image uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Image Uploaded!!",
Toast.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
// Error, Image not uploaded
progressDialog.dismiss();
Toast
.makeText(MainActivity.this,
"Failed " + e.getMessage(),
Toast.LENGTH_SHORT)
.show();
}
})
.addOnProgressListener(
new OnProgressListener<UploadTask.TaskSnapshot>() {
// Progress Listener for loading
// percentage on the dialog box
#Override
public void onProgress(
UploadTask.TaskSnapshot taskSnapshot)
{
double progress
= (100.0
* taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage(
"Uploaded "
+ (int)progress + "%");
}
});
}
}
I am not able to pick a image from gallery when I use it in registration activity like as shown below and trying to send it to firebase real time database i failed, but when i create activity to insert only image and no user data to realtime database then i succeed but in registration activity i want to pick image with user data and also want to send it to firebase realtime database but i dont know how to do it
and here is my registrationActivity.java
public class RegistrationActivity extends AppCompatActivity{
private EditText userName, userPassword, userEmail, userAge;
private Button regButton;
private TextView userLogin;
private FirebaseAuth firebaseAuth;
private ImageView userProfilePic;
String email, name, age, password;
private FirebaseStorage firebaseStorage;
private static int PICK_IMAGE = 123;
Uri imagePath;
private StorageReference storageReference;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);
userProfilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setupUIViews();
firebaseAuth = FirebaseAuth.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference();
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("images/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE);
}
});
regButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(validate()){
//Upload data to the database
String user_email = userEmail.getText().toString().trim();
String user_password = userPassword.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//sendEmailVerification();
sendUserData();
firebaseAuth.signOut();
Toast.makeText(RegistrationActivity.this,"Successfully Registered, Upload complete!", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}else{
Toast.makeText(RegistrationActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}
});
}
private void setupUIViews(){
userName = (EditText)findViewById(R.id.etUserName);
userPassword = (EditText)findViewById(R.id.etUserPassword);
userEmail = (EditText)findViewById(R.id.etUserEmail);
regButton = (Button)findViewById(R.id.btnRegister);
userLogin = (TextView)findViewById(R.id.tvUserLogin);
userAge = (EditText)findViewById(R.id.etAge);
userProfilePic = (ImageView)findViewById(R.id.ivProfile);
}
private Boolean validate(){
Boolean result = false;
name = userName.getText().toString();
password = userPassword.getText().toString();
email = userEmail.getText().toString();
age = userAge.getText().toString();
if(name.isEmpty() || password.isEmpty() || email.isEmpty() || age.isEmpty() || imagePath == null){
Toast.makeText(this, "Please enter all the details", Toast.LENGTH_SHORT).show();
}else{
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser!=null)
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegistrationActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
finish();
startActivity(new Intent(RegistrationActivity.this, MainActivity.class));
}else{
Toast.makeText(RegistrationActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(firebaseAuth.getUid());
StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic"); //User id/Images/Profile Pic.jpg
UploadTask uploadTask = imageReference.putFile(imagePath);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegistrationActivity.this, "Upload failed!", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Toast.makeText(RegistrationActivity.this, "Upload successful!", Toast.LENGTH_SHORT).show();
}
});
UserProfile userProfile = new UserProfile(age, email, name);
myRef.setValue(userProfile);
}
}
It always gives me alert that please fill all the details as i am not able to pick image from gallery
I looked through your code and couldn't find an OnActivityResult class in it, so create a protected void onActivityResult(int requestCode, int resultCode, Intent data) {} this will help you get the result data after you pick any image from your gallary.