I cannot upload the profile image on firebase storage.
I'm getting printed the error from the toast.
Why is this happening? I cannot figure the problem out, I reviewed my code so many times.
What could the problem be and how can I adjust my code in order to make this work?
Thank you in advance to everyone.
public class ProfiloUtenteActivity extends AppCompatActivity {
private ImageView mImageBtn;
private ImageView mSettingsBtn, mPersonalReviewsBtn, mShowFriendsBtn;
private CircleImageView mProfileImage;
private TextView mMailAcc, mUsernameAcc;
private static final int GALLERY_PICK = 1;
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private ProgressDialog mProgress;
private StorageReference mImageStorage;
private String myUri = "";
private Uri imageUri;
FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profilo_utente);
mShowFriendsBtn = findViewById(R.id.imageShowFriends);
mPersonalReviewsBtn = findViewById(R.id.imagePersonalReviews);
mSettingsBtn = (ImageView) findViewById(R.id.imageViewSettings);
mImageBtn = (ImageView) findViewById(R.id.change_image_btn);
mProfileImage = (CircleImageView) findViewById(R.id.profile_image);
mMailAcc = (TextView) findViewById(R.id.textViewMailAcc);
mUsernameAcc = (TextView) findViewById(R.id.textView7);
auth = FirebaseAuth.getInstance();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("utenti").child(current_uid);
mImageStorage = FirebaseStorage.getInstance().getReference();
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, "Seleziona una foto"), GALLERY_PICK);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
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);
Uri resultUri = result.getUri();
StorageReference filepath = mImageStorage.child("profile_images").child("1wq");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(ProfiloUtenteActivity.this, "Funziona", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ProfiloUtenteActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
When a Task fails, it contains an exception that has more information about the failure. Logging that allows you to find out the cause of the problem:
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
Toast.makeText(ProfiloUtenteActivity.this, "Funziona", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ProfiloUtenteActivity.this, "Error", Toast.LENGTH_SHORT).show();
Log.e("Upload", "Upload failed", task.getException());
}
}
Once you get the error message, I recommend searching for it was likely somebody has dealt with it before.
Related
This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
Closed 3 years ago.
I am following a series of videos on youtube from the channel CodingInFlow. They are a bit Outdated, 2017 is long time ago. The Video Series is great and I followed up the 4th video no problem, except one deprecated function that was easy enough to resolve. The file uploads to the Firebase Storage, but it doesn't show up in the Real Time Database
Main Class
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST = 1;
Button mButtonChooseImage;
Button mButtonUpload;
TextView mTextViewShowUploads;
EditText mEditTextFileName;
ImageView mImageView;
ProgressBar mProgressBar;
Uri mImageUri;
StorageReference mStorageRef;
DatabaseReference mDatabaseRef;
StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonUpload = findViewById(R.id.button_upload);
mTextViewShowUploads = findViewById(R.id.text_view_show_uploads);
mEditTextFileName = findViewById(R.id.edit_text_file_name);
mImageView = findViewById(R.id.image_view);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress()) {
Toast.makeText(MainActivity.this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else {
uploadFile();
}
}
});
mTextViewShowUploads.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile() {
if (mImageUri != null) {
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(MainActivity.this, "Upload Successful", Toast.LENGTH_SHORT).show();
Upload upload = new Upload(mEditTextFileName.getText().toString().trim(),
taskSnapshot.getStorage().getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
//assert uploadId != null;
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show();
}
}
}
My question is, is it my mistake that I missed something (I followed the video exactly, and checked the code on the channel's website), or is it that the functionality shifted and something needs to be added?
The reason I ask is that the app works in the video, including the function that the checks for duplicate uploads, but in my reproduction, that function only works while the picture actually uploads, so there has been some shifting, but I don't even know where to start research, so I'm starting here.
This is how I did mine. This code saves the image to the storage and to the firebase realtime database under the child "profile image" as a link.
public class Registration3 extends AppCompatActivity {
Button elFin;
CircleImageView ProfileImage;
private DatabaseReference UsersRef;
private FirebaseAuth mAuth;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration3);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
elFin = findViewById(R.id.btn_dd);
ProfileImage = findViewById(R.id.profile_imageUp);
UsersRef = FirebaseDatabase.getInstance().getReference().child("DriversInformation").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileimage");
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, Gallery_Pick);
}
});
elFin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Registration3.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
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) {
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(Registration3.this, "Image Uplaoded", 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();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent selfIntent = new Intent(Registration3.this, Registration3.class);
startActivity(selfIntent);
Toast.makeText(Registration3.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
} else {
String message = task.getException().getMessage();
Toast.makeText(Registration3.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
}
else {
Toast.makeText(Registration3.this, "Error: ", Toast.LENGTH_SHORT).show();
}
}
}
}
Error show in image.Please Click here for view Image
When User Want to change his profile picture.and upload new image . Firebase get uri of new image ad replaced with old uri value. That work is done with .setValue(). Now i am unbale to use that method. Please Any one tell me Solution, how i cando it easily.
enter code here
` package junaidandusman.newchatapp;
public class SettingActivity extends AppCompatActivity {
private CircleImageView SettingDisplayprofileImage;
private TextView SettingDisplayName;
private TextView SettingDisplayStatus;
private Button SettingChangeprofileImage;
private Button SettingChangeStatus;
private DatabaseReference Reference;
private FirebaseAuth mAuth;
private final static int Gallery_Pick=1;
private StorageReference Storagereference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
SettingDisplayprofileImage=(CircleImageView)
findViewById(R.id.setting_profile_image);
SettingDisplayName=(TextView)
findViewById(R.id.setting_username);
SettingDisplayStatus=(TextView)
findViewById(R.id.setting_userstatus);
SettingChangeprofileImage=(Button)
findViewById(R.id.setting_change_profile_image);
SettingChangeStatus=(Button)
findViewById(R.id.setting_change_profile_status);
Storagereference=FirebaseStorage.getInstance().getReference().child("profile_images");
mAuth=FirebaseAuth.getInstance();
String online_user_id=mAuth.getCurrentUser().getUid();
Reference=FirebaseDatabase.getInstance().getReference().child("users").child(online_user_id);
Reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name=dataSnapshot.child("user_name").getValue().toString();
String status=dataSnapshot.child("user_status").getValue().toString();
String image=dataSnapshot.child("user_image").getValue().toString();
String thumb_image=dataSnapshot.child("user_thumb_image").getValue().toString();
SettingDisplayName.setText(name);
SettingDisplayStatus.setText(status);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
SettingChangeprofileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gallery_intent=new Intent();
gallery_intent.setAction(Intent.ACTION_GET_CONTENT);
gallery_intent.setType("image/*");
startActivityForResult(gallery_intent,Gallery_Pick);
}
});
}
#Override
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) {
Uri resultUri = result.getUri();
String user_id=mAuth.getCurrentUser().getUid();
StorageReference FilePath=Storagereference.child(user_id+".jpg");
FilePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(SettingActivity.this,"Saving your profile image to Firebase Storag",Toast.LENGTH_LONG).show();;
String downloadurl=task.getResult().getStorage().getDownloadUrl().toString();
Storagereference.child("user_image").setValue(downloadurl);
}
else
{
Toast.makeText(SettingActivity.this,"Error occured,while uploading your profile image",Toast.LENGTH_SHORT).show();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
How I can store downloaduri value to Storagereference using .setValue or any other method that can do this?
i am working on the a social app where the user can upload their image on their feeds but when the user is picking up the image ,the image less than 2 mb are getting picked up and are successfully uploaded to the firebase but when the user uploads the image more than 2mb the app crashes. what can be done to compress the image ..
postactivity.java
private Toolbar mToolbar;
private ImageButton SelectPostImage;
private Button UpdatePostButton;
private ProgressDialog loadingBar;
private EditText PostDescription;
private static final int Gallery_pick = 1;
private Uri ImageUri;
private String Description;
private StorageReference PostsImagesReference;
private DatabaseReference usersRef, PostsRef;
private FirebaseAuth mAuth;
private String saveCurrentDate, saveCurrentTime,current_user_id, postRandomName, downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth = FirebaseAuth.getInstance();
current_user_id = mAuth.getCurrentUser().getUid();
PostsImagesReference = FirebaseStorage.getInstance().getReference();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
SelectPostImage = (ImageButton)findViewById(R.id.select_post_image);
UpdatePostButton = (Button) findViewById(R.id.update_post_button);
PostDescription = (EditText)findViewById(R.id.post_description);
loadingBar = new ProgressDialog(this);
mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Update Post");
SelectPostImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
UpdatePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ValidatePostInfo();
}
});
}
private void ValidatePostInfo() {
Description = PostDescription.getText().toString();
if (ImageUri == null){
Toast.makeText(this, "Please select the image", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(Description)){
Toast.makeText(this,"Please write something here",Toast.LENGTH_SHORT).show();
}else {
loadingBar.setTitle(" Add New Post");
loadingBar.setMessage("Please wait, while we updating your new post");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
StoringImageToFirebaseStorage();
}
}
private void StoringImageToFirebaseStorage() {
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH: mm");
saveCurrentTime = currentTime.format(calForDate.getTime());
postRandomName = saveCurrentDate + saveCurrentTime;
StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
downloadUrl = task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this,"Image is sucessfully uploaded to storage",Toast.LENGTH_LONG).show();
SavingPostInformationToDatabase();
}else{
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this,"Error Occured:" + message,Toast.LENGTH_SHORT).show();
}
}
});
}
private void SavingPostInformationToDatabase() {
usersRef.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String userfullname = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
HashMap postsMap = new HashMap();
postsMap.put("uid",current_user_id);
postsMap.put("date",saveCurrentDate);
postsMap.put("time",saveCurrentTime);
postsMap.put("description",Description);
postsMap.put("postimage",downloadUrl);
postsMap.put("profileimage",userProfileImage);
postsMap.put("fullname",userfullname);
PostsRef.child(current_user_id + postRandomName).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(PostActivity.this,"Your New Post is Updated Sucessfully",Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}else{
Toast.makeText(PostActivity.this,"Error Occured while updating your post .please try again ",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void OpenGallery() {
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, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_pick && resultCode == RESULT_OK && data != null){
ImageUri = data.getData();
SelectPostImage.setImageURI(ImageUri);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home){
SendUserToMainActivity();
}
return super.onOptionsItemSelected(item);
}
private void SendUserToMainActivity() {
Intent mainintent = new Intent(PostActivity.this,MainActivity.class);
startActivity(mainintent);
}
}
byte[] thumb_byte_data;
Uri resultUri = ImageUri;
//getting imageUri and store in file. and compress to bitmap
File file_path = new File(resultUri.getPath());
try {
Bitmap thumb_bitmap = new Compressor(this)
.setMaxHeight(200)
.setMaxWidth(200)
.setQuality(75)
.compressToBitmap(file_path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
thumb_byte_data = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
You can then upload to firebase with the this code:
final UploadTask uploadTask = bytepath.putBytes(thumb_byte_data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
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();
}
// Continue with the task to get the download URL
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
You can create bitmap with captured image as below:
Bitmap bitmap = Bitmap.createScaledBitmap(yourimageuri, width, height, true);// the uri you got from onactivityresults
You can also view this thirdparty lib to compress your image Click Here
//declear local variable first
Bitmap bitmap;
Uri imageUri;
//button action to call Image picker method
companyImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Pick Comapany Image"),GALLERY_REQ_CODE);
}
});
//get bitmap from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageURI(imageUri);
}
}
//compress image first then upload to firebase
public void postImage() {
StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
databaseReference =
FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);
Uri uri = Uri.parse(path);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
final String downloadUrl = task.getResult().toString();
if (task.isSuccessful()){
Map<String, Object> update_hashMap = new HashMap<>();
//assign download url in hashmap to upadate database reference
update_hashMap.put("Image",downloadUrl);
//update database children here
databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
//do what you want
}else {
//show exception
}
}
});
}else{
//show exception
}
}
});
}
});
}
Link To Data Base structer I recently added a feature in my app where it allows the user to upload a profile picture and that image is stored in firebase and then displayed to the user in the app. The image successfully gets stored in the firebase but when the image is going to be displayed it just removes the default display image and displays nothing.
public class SettingsActivity extends AppCompatActivity {
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
//Android Layout
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private ProgressDialog mProgressDialog;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mStatusBtn = (Button) findViewById(R.id.settings_status_btn);
mImageBtn = (Button) findViewById(R.id.settings_image_btn);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String image = dataSnapshot.child("image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if (!image.equals("default")) {
Picasso.with(SettingsActivity.this).load(image).into(mDisplayImage);
} else {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.goodgolden).into(mDisplayImage);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
mImageBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gallaryIntent = new Intent();
gallaryIntent.setType("image/*");
gallaryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallaryIntent, "Select Image"), GALLERY_PICK);
/*
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(SettingsActivity.this);
*/
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
String imageUri = data.getDataString();
CropImage.activity(Uri.parse(imageUri))
.setAspectRatio(1, 1)
.start(this);
// Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_SHORT).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog((SettingsActivity.this));
mProgressDialog.setTitle("Uploading");
mProgressDialog.setMessage("Pleas Stand By");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
String current_user_id = mCurrentUser.getUid();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + (".jpeg"));
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
String download_url = task.getResult().getStorage().getDownloadUrl().toString();
// dont know if this solution will work at 6:15 video
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Succesful Upload", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error Up Loading", Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
07-11 20:15:12.147 30329-30329/com.example.android.lapitchat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.lapitchat, PID: 30329
java.lang.IllegalStateException: Center crop requires calling resize with positive width and height.
at com.squareup.picasso.Request$Builder.build(Request.java:496)
at com.squareup.picasso.RequestCreator.createRequest(RequestCreator.java:758)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:709)
at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
at com.example.android.lapitchat.SettingsActivity$1.onDataChange(SettingsActivity.java:84)
at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Use latest version of Picasso as -
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load(url).resize(100,100).centerCrop().into(imageView);
Try Replacing the code by this !!!
public class SettingsActivity extends AppCompatActivity {
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;
private static final int GALLERY_PICK = 1;
// Storage Firebase
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mStatusBtn = (Button) findViewById(R.id.settings_status_btn);
mImageBtn = (Button) findViewById(R.id.settings_image_btn);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mImageStorage = FirebaseStorage.getInstance().getReference();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if(!image.equals("default")) {
//Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.default_avatar).into(mDisplayImage);
Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.default_avatar).into(mDisplayImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.default_avatar).into(mDisplayImage);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mStatusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String status_value = mStatus.getText().toString();
Intent status_intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_intent.putExtra("status_value", status_value);
startActivity(status_intent);
}
});
mImageBtn.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_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setAspectRatio(1, 1)
.setMinCropWindowSize(500, 500)
.start(this);
//Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(SettingsActivity.this);
mProgressDialog.setTitle("Uploading Image...");
mProgressDialog.setMessage("Please wait while we upload and process the image.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
File thumb_filePath = new File(resultUri.getPath());
String current_user_id = mCurrentUser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(thumb_filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".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().getStorage().getDownloadUrl().toString();
UploadTask uploadTask = thumb_filepath.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().getStorage().getDownloadUrl().toString();
if(thumb_task.isSuccessful()){
Map update_hashMap = new HashMap();
update_hashMap.put("image", download_url);
update_hashMap.put("thumb_image", thumb_downloadUrl);
mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in uploading thumbnail.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in uploading.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
I am trying to get the current logged in user from the google firestore database
and i saw this same problem in stackoverflow of a user and i used that same method but showing blank in place user details.
Please help me Thanks.
I am earlier using querysnapshot as it gives all the users.
image description here
the image for database is
enter image description here
The code is:
public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
if(getSupportActionBar()!=null ){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
DatabaseReference DBRef = Database.child("users");
auth = FirebaseAuth.getInstance();
UserId = auth.getCurrentUser().getUid();
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
StorageReference mStorage = FirebaseStorage.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
photoview = (ImageView)findViewById(R.id.photoview);
Photo = (ImageButton)findViewById(R.id.Photoedit);
name = (TextView)findViewById(R.id.username);
email = (TextView)findViewById(R.id.useremail);
password = (TextView)findViewById(R.id.password1);
phone = (TextView)findViewById(R.id.userPhone);
mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String Name = documentSnapshot.getString("Name");
String Email = documentSnapshot.getString("Email");
String Password = documentSnapshot.getString("Password");
String Phone = documentSnapshot.getString("Phone Number");
name.setText(Name);
email.setText(Email);
password.setText(Password);
phone.setText(Phone);
}
});
Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_INTENT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
photoview.setImageBitmap(photo);
} else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
photoview.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent i = new Intent(UserProfile.this,category.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
My database structure is
Ramiki(my app name)
So here it is
Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).
Well sorry i am not able to give screenshort because i am not allowed by stack overflow 10 points needed.
And my code for writing data in firestore is
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
mFirebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build();
mFirebaseFirestore.setFirestoreSettings(settings);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, account.class);
startActivity(i);
finish();
}
});
//if the user is already logged in we will directly start the category activity
if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, category.class));
finish();
return;
}
findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("Name", Name);
user.put("Email", Email);
user.put("Password", Password);
user.put("Phone Number", Phone_Number);
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if(Password.length() < 7){
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else {
// Add a new document with a generated ID
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
registerUser();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
}
});
initViews();
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
}
}
private void registerUser() {
final String Name = textInputEditTextName.getText().toString().trim();
final String Email = textInputEditTextEmail.getText().toString().trim();
final String Password = textInputEditTextPassword.getText().toString().trim();
final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
return;
}
if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
return;
}
if(Password.length() < 7 ) {
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
return;
}
if (TextUtils.isEmpty(ConfirmPassword)) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
sendEmailVerification();
}
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
else if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(LoginActivity.this, account.class));
finish();
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private void initViews() {
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}
protected void onStart(){
super.onStart();
auth.addAuthStateListener(authListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.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, "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
This unique id SiQEIDaQJfUBqZBBt1eo is generated when you are adding the user as a Map or when you are using a call to document() method without passing an argument.
In order to solve this, there are two ways. One would be to create a model class (UserModel), then create an object of that class and in the end get the uid of the user once it authenticated and add the object to the database like this:
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);
See, I have passed the uid as argument to the document() method.
The second approach would be to pass no argument to the document() method but to store that key into a variable like this:
String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);
Edit:
There also another method, which I recommend you use it. Instead of using this line of code:
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(/* ... */)
Use the following line of code:
mFirebaseFirestore.collection("users")
.document(uid)
.set(user)
.addOnSuccessListener(/* ... */)
Remove the old data, add fresh one and your problem will be solved.