Data being added as new instead of updating firebase firestore - java

I'm trying to make the data get update in firestore with the method updatedata but for some reason instead of the data being updated, a new user gets created with the data I'm supposed to be updating, I don't get why, I've been stuck on it for hours now and any help will be appreciated, this is the class where I either save data or update it:
public class Admin_add extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mFullName, mEmail, mPassword, mPhone;
Button mAddBtn,leaveAdd;
FirebaseAuth fAuth;
ProgressBar progressBar;
FirebaseFirestore fStore;/*db*/
String UserID;
Button showall;
private String uName,uEmail,uPhone,uPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add);
mFullName = findViewById(R.id.fullName1);
mEmail = findViewById(R.id.Email1);
mPassword = findViewById(R.id.password1);
mPhone = findViewById(R.id.phone1);
mAddBtn = findViewById(R.id.adduserbtn);
leaveAdd=findViewById(R.id.leaveadd);
showall=findViewById(R.id.showallbtn);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
fStore = FirebaseFirestore.getInstance();
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
mAddBtn.setText("update");
uName=bundle.getString("uName");
uEmail=bundle.getString("uEmail");
uPhone=bundle.getString("uPhone");
uPassword=bundle.getString("uPassword");
mFullName.setText(uName);
mPhone.setText(uPhone);
mEmail.setText(uEmail);
mPassword.setText(uPassword);
}else{
mAddBtn.setText("save");
}
leaveAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),AdminAct.class));
finish();
}
});
showall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Crud_users.class));
}
});
mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
final String password = mPassword.getText().toString().trim();
final String fullname = mFullName.getText().toString();
final String phone = mPhone.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email Is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password Is Required.");
return;
}
if (password.length() < 8) {
mPassword.setError("Password must be>=8 characters");
}
progressBar.setVisibility(View.VISIBLE);
Bundle bundle1=getIntent().getExtras();
if(bundle1!=null){
String id=UserID;
updateToFireStore(fullname,email,password,phone);
}else{
fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Admin_add.this, "user created", Toast.LENGTH_SHORT).show();
UserID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(UserID);
Map<String, Object> user = new HashMap<>();
user.put("fName", fullname);
user.put("email", email);
user.put("phone", phone);
user.put("Password", password);
//specify if user is admin
user.put("isUser", "1");
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "OnSuccess: user profile is created for" + UserID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "Failure" + e.toString());
}
});
progressBar.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(Admin_add.this, "ERROR" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//register to firebase
}
});
}
private void updateToFireStore(String fullname, String email, String password, String phone) {
UserID = fAuth.getCurrentUser().getUid();
fStore.collection("users").document(UserID).update("email",email,"Password",password,"fName",fullname,"phone",phone)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Admin_add.this, "data updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Admin_add.this, "Error"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Admin_add.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
i think there is a problem somewhere in updatetofirestore method, this is my adapater class:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.MyViewHolder> {
private Crud_users activity;
private List<usersmodel> mList;
public UsersAdapter(Crud_users activity,List<usersmodel> mList){
this.activity=activity;
this.mList=mList;
}
public void updateData(int position){
usersmodel item=mList.get(position);
Bundle bundle=new Bundle();
bundle.putString("uName",item.getfName());
bundle.putString("uEmail",item.getEmail());
bundle.putString("uPhone",item.getPhone());
bundle.putString("uPassword",item.getPassword());
Intent intent=new Intent(activity,Admin_add.class);
intent.putExtras(bundle);
activity.startActivity(intent);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(activity).inflate(R.layout.list_item_single,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.name.setText(mList.get(position).getfName());
holder.email.setText(mList.get(position).getEmail());
holder.phone.setText(mList.get(position).getPhone());
holder.isuser.setText(mList.get(position).getIsUser());
}
#Override
public int getItemCount() {
return mList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView name,email,phone,isuser;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.list_name);
email=itemView.findViewById(R.id.list_email);
phone=itemView.findViewById(R.id.list_phone);
isuser=itemView.findViewById(R.id.list_isuser);
}
}
}
I really have no clue i've tried everything i can.

I think you should change the way you pass values to update() method of firebase.
fStore.collection("users").document(UserID).update("email",email,"Password",password,"fName",fullname,"phone",phone)
The correct way is to pass a map<String, Object>. Below is the example:
Map<String, Object> data = new HashMap<String, Object>();
data.put("email", email);
data.put("Password", password);
data.put("fName", fullname);
data.put("phone", phone);
fStore.collection("users").document(UserID).update(data);
You can use set() method of Firebase with SetOptions.merge() as an alternative which is better than update() because update() will update a field only if it exists where set() with SetOptions.merge() will update the existing field and create if it doesn't exist.
Read more about it here.
Map<String, Object> data = new HashMap<String, Object>();
data.put("email", email);
data.put("Password", password);
data.put("fName", fullname);
data.put("phone", phone);
fStore.collection("users").document(UserID).set(data, SetOptions.merge());

Related

How to fetch user profile image from firebase storage

I'm new to android development and I have used firebase inside the project and tried all the ways to show the user profile picture inside the image view but none of the solutions works for me. Uploading profile image to firebase is working fine whenever I click on the save button the profile image and cover image uploaded successfully but it's not showing inside the imageview
public class Profile extends AppCompatActivity {
public static final int CAMERA_PERMISSION_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
public static final int PICK_IMAGE_REQUEST = 111;
private Uri uri;
private Uri coverUri;
EditText fullName, email, phone;
Button saveProfileBtn, logoutProfileBtn;
ImageView userProfileImage, userCoverImage;
ImageButton cameraBtn, userCoverBtn;
FirebaseStorage storage;
StorageReference storageReference;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
FirebaseUser fUser;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3498DB"));
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Profile Settings </font>"));
fullName = findViewById(R.id.userNameProfile);
email = findViewById(R.id.emailUserProfile);
phone = findViewById(R.id.phoneNoProfile);
saveProfileBtn = findViewById(R.id.saveBtnProfile);
logoutProfileBtn = findViewById(R.id.logoutBtn);
userProfileImage = findViewById(R.id.proImgProfile);
cameraBtn = findViewById(R.id.cameraBtnProfile);
userCoverImage = findViewById(R.id.coverPhotoPS);
userCoverBtn = findViewById(R.id.coverImageUpload);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(10);
// uploadImage();
}
});
userCoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImagePicker.with(Profile.this)
.crop() //Crop image(Optional), Check Customization for more option
.compress(512) //Final image size will be less than 1 MB(Optional)
.maxResultSize(512, 512) //Final image resolution will be less than
// 512 x 512(Optional)
.start(20);
}
});
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
fullName.setText(value.getString("fname"));
email.setText(value.getString("email"));
phone.setText(value.getString("phone"));
}
});
saveProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadImage(); //Calling function to upload profile image
coverUploadImage(); //Calling function to upload cover image
String fname = fullName.getText().toString();
String femail = email.getText().toString();
String fphone = phone.getText().toString();
if (TextUtils.isEmpty(fname)) {
fullName.setError("Please Enter Your Full Name");
return;
}
if (TextUtils.isEmpty(femail)) {
email.setError("Please Enter Your Email Address");
return;
}
if (fphone.length() < 10) {
phone.setError("Phone Number Shouble Be 10 Digit");
return;
}
if (TextUtils.isEmpty(fphone)) {
phone.setError("Please Enter Your Phone Number");
return;
}
DocumentReference documentReference =
FirebaseFirestore.getInstance().collection("users").document(userID);
Map<String, Object> user = new HashMap<>();
user.put("fname", fname);
user.put("email", femail);
user.put("phone", fphone);
documentReference.update(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(Profile.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Profile.this, "Failed to Update the Profile", Toast.LENGTH_SHORT).show();
}
});
}
});
logoutProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), login.class));
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10) {
uri = data.getData();
userProfileImage.setImageURI(uri);
}
if (requestCode == 20)
{
coverUri = data.getData();
userCoverImage.setImageURI(coverUri);
}
}
private void showUploadedImage() {
Uri uri = fUser.getPhotoUrl();
Glide.with(this).load(uri).into(userProfileImage);
}
// Function to upload profile image
private void uploadImage() {
if (uri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Profile Image");
progressDialog.show();
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Profile Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Uploaded Profile Picture"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
// Function to upload cover image
private void coverUploadImage() {
if (coverUri != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading Cover Picture");
progressDialog.show();
StorageReference ref =
storageReference.child("userCoverImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
ref.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Cover Picture Uploaded Successfully",
Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this,
"Failed to Upload Cover Picture"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0*snapshot.getBytesTransferred()/snapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
public void saveDocument(View view) {
}
}
You are saying that the uploading is working successfully, so try another way to get the image URL from storage and put the link in the hashmap with the user's phone, name, and email after uploading the image.
So try this:
StorageReference ref = storageReference.child("userProfileImages/" + FirebaseAuth.getInstance().getCurrentUser().getUid());
// Use add on progress like this.
ref.putFile(uri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
}
}).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return ref.getDownloadUrl();
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String photoUrl = uri.toString();
// This is the uri that you want to use after to put in the user's hashmap
Glide.with(MainActivity.this).load(photoUrl).into(userProfileImage);
}
});

Authorized user condition that opens another DialogFragment

Made registration using Firebase. I need that when clicking on the same CardView different DialogFragment opens and the condition is whether the user is logged in or not, i.e. by clicking on the CardView, DialogFragment1 opens in which the user logs in, if everything is successful DialogFragment1 is closed and when the CardView is pressed again, DialogFragment2 is opened, how to do this?
My dialog through which the user logs in
public class FragmentDialogLogin extends Fragment {
public static CardView close_dl, login_LG;
public static boolean isRememberUserLogin;
CardView registration;
public static EditText User_Name_LG;
public static EditText User_Password_LG;
public static String name;
public static String surname;
public static String email;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#SuppressLint("StaticFieldLeak")
public static LinearLayout Ll_LG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dialog_login, container, false);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
close_dl = view.findViewById(R.id.close_dl);
close_dl.setOnClickListener(v -> {
closeDialog();
});
registration = view.findViewById(R.id.registration);
registration.setOnClickListener(v -> {
int current = DialogAuthorization.VP_dialog_authorization.getCurrentItem();
int totalItems = DialogAuthorization.VP_dialog_authorization.getAdapter().getCount();
if (current < totalItems - 1) {
DialogAuthorization.VP_dialog_authorization.setCurrentItem(current + 1, true);
}
});
User_Name_LG = view.findViewById(R.id.User_Name_LG);
User_Password_LG = view.findViewById(R.id.User_Password_LG);
login_LG = view.findViewById(R.id.login_LG);
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = User_Name_LG.getText().toString().trim();
String password = User_Password_LG.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
User_Name_LG.setError("Email is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
User_Password_LG.setError(getText(R.string.Rink));
return;
}
if (password.length() < 6) {
User_Password_LG.setError("Password Must be >= 6 Characters");
return;
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void closeDialog() {
Fragment prev = requireActivity().getSupportFragmentManager().findFragmentByTag("DialogAuthorization");
if (prev != null) {
DialogAuthorization df = (DialogAuthorization) prev;
df.dismiss();
}
}
}
The simplest way to check whether user logged in or not is to call getCurrentUser();
private DatabaseReference rootReference;
private DatabaseReference usersRef;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
...
rootReference = FirebaseDatabase.getInstance().getReference();
usersRef = rootReference.child("Users");
...
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// User already logged in
if (firebaseAuth.getCurrentUser() != null) {
// Todo: close dialog fragment 1 and open dialog fragment 2
return;
}
// user did not log in
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Store that user logged in with email
String currentUserId = firebaseAuth.getCurrentUser().getUid();
rootReference.child("Users").child(currentUserId).setValue("email");
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
You can add the int at the class as increment. You can do something like this.
At the class.
public static String surname;
public static String email;
private int counter = 1; //Add this one.
And then at the method onComplete()
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
if (counter >1){
//DialogFragment2
}else{
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
counter++; //increment
}
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}

how to upload image Url Uploaded to Fire Storage and Save it in fireStore at the Same time Using Java

Here's my code where i can retrieve the image Url in Toast message where it is unable to save it in firestore please tell me if there is another method to do it or is the problem where i store the URL:
public class register extends AppCompatActivity {
EditText emails;
EditText passwords;
EditText ages;
Button registers;
Button addImage;
EditText country;
FirebaseFirestore db;
FirebaseAuth auth;
FirebaseUser auth1;
private StorageTask task;
Uri url ;
Uri imageUri;
static final int IMAGE_REQUEST =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
auth = FirebaseAuth.getInstance();
registers = findViewById(R.id.button);
emails = findViewById(R.id.eamil);
passwords = findViewById(R.id.password);
ages=findViewById(R.id.age);
country=findViewById(R.id.country);
addImage = findViewById(R.id.button51);
db =FirebaseFirestore.getInstance();
registers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String v_email = emails.getText().toString();
String v_password = passwords.getText().toString();
if (TextUtils.isEmpty(v_email)||TextUtils.isEmpty(v_password)){
Toast.makeText(register.this,"Eempty Credentials",Toast.LENGTH_SHORT).show();
}else if(v_password.length()<6){
Toast.makeText(register.this,":password is short",Toast.LENGTH_SHORT).show();
}else{
upload();
registerUser(v_email, v_password);
}
}
});
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImage();
}
});
}
private void registerUser(final String email, final String password) {
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(register.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Map<String , Object> users = new HashMap<>();
users.put("Email", emails.getText().toString());
users.put("Password", passwords.getText().toString());
users.put("Country", country.getText().toString());
users.put("AGe", ages.getText().toString());
users.put("Image", url.toString());
auth1 = FirebaseAuth.getInstance().getCurrentUser();
db.collection("Users").document(auth1.getUid()).set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Toast.makeText(com.example.pleasework.register.this,"registeration was successful",Toast.LENGTH_SHORT).show();
}
});
// startActivity(new Intent(com.example.pleasework.register.this, MainActivity.class));
// finish();
}else{
Toast.makeText(com.example.pleasework.register.this,"Resgisteration fail",Toast.LENGTH_SHORT).show();
}
}
});
}
public String getFileExtension(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
public void upload (){
if (imageUri != null){
final StorageReference fileRef = FirebaseStorage.getInstance().getReference(System.currentTimeMillis()+getFileExtension(imageUri) );
fileRef.putFile(imageUri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
url = uri;
Toast.makeText(register.this,"Upload Sucess" + url.toString(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
public void openImage(){
Intent intent = new Intent();
intent.setType("image/");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
imageUri=data.getData();
}
}
}
});
}
}
and in fire store the field is always coming null but it is saved in the firestorage .
Wanted to add an image for FireStore but coludn't
Thanks.
This process is called AsyncTask, which is intended to perform a process before a process.
It works to upload the image and the data at the same time, so the image link does not store because it did not finish uploading the image, and this is in less than a split of a second.
You can use this method when the image is finished uploading, the data is stored in FireStore :
private void registerUser(final String email, final String password) {
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(register.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
upload ();
}
});
Here be sure to upload the image first and then add ImageUrl to the fireStore :
public void upload (){
if (imageUri != null){
final StorageReference fileRef = FirebaseStorage.getInstance().getReference(System.currentTimeMillis()+getFileExtension(imageUri) );
fileRef.putFile(imageUri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
fileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
url = uri;
Map<String , Object> users = new HashMap<>();
users.put("Email", emails.getText().toString());
users.put("Password", passwords.getText().toString());
users.put("Country", country.getText().toString());
users.put("AGe", ages.getText().toString());
users.put("Image", url.toString());
auth1 = FirebaseAuth.getInstance().getCurrentUser();
db.collection("Users").document(auth1.getUid()).set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(register.this,"Upload Sucess" + url.toString(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
});
}
}

authentication problem in fire base using android studio

I am working on a project which required firebase utilities so I did all those things required but my authentication is not taking place and thereby my data is not being uploaded in the firestore. I have tried many things and found that during the time of execution my onComplete listener is calling failure and thus a toast is popped authentication failure so I think the main problem lies in the onComplete listener but I couldn't fix it. My code is as follows-
*
private TextView username;
private TextView password;
private AutoCompleteTextView email;
private ProgressBar progress_bar;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username_account);
password = findViewById(R.id.password_account);
email = findViewById(R.id.email_account);
Button create_account = findViewById(R.id.create_acct_button);
progress_bar = findViewById(R.id.create_acct_progress);
firebaseAuth = FirebaseAuth.getInstance();
create_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(email.getText().toString())
&& !TextUtils.isEmpty(password.getText().toString())
&& !TextUtils.isEmpty(username.getText().toString())) {
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
String Username = username.getText().toString().trim();
createUserEmailAccount(Email, Password, Username);
} else {
Toast.makeText(CreateAccountActivity.this,
"Empty Fields Not Allowed",
Toast.LENGTH_LONG)
.show();
}
}
});
}
private void createUserEmailAccount(String email, String password, final String username) {
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
progress_bar.setVisibility((View.VISIBLE));
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( CreateAccountActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete( #NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Map<String, Object> userobj = new HashMap<>();
userobj.put("userId", "currentuserId");
userobj.put("username", username);
db.collection("journal")
.add(userobj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot successfully written!");
progress_bar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(CreateAccountActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progress_bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
}*

how can I get the products of the sellers

I have compared the others questions but they have different problems.
My question is, how can I display (on the user activity) all the products that the sellers have added on the firebase database?
The sellers have their own register and login activity before they add the products, meaning each seller will be having is own name or id.
You can check my database sample on the picture below.
**Sorry guys I have updated the code but now it is crashing the app every time I click the button to go to the add products activity**
public class SellerAddProductActivity extends AppCompatActivity {
private String saveCurrentDate;
private String saveCurrentTime;
private String CategoryName;
private String downloadImageUrl;
private String productRandomKey;
private String Description;
private String Price, Quantity, State;
private String Pname, Store;
private Button AddProductButton;
private EditText InputProductName;
private EditText InputProductPrice, InputStoreName;
private EditText InputProductDescription, InputProductQauntity, InputProductState;
private StorageReference ProductImageRef;
private Uri ImageUri;
private DatabaseReference ProductsRef, ProductsInfo;
private ProgressDialog loadingBar;
private static final int GalleryPick = 1;
private ImageView InputProductImage;
FirebaseUser currentUser;
FirebaseUser mAuth;
String userID = mAuth.getUid(); //--> Store each seller name with this ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_add_product);
ProductImageRef = FirebaseStorage.getInstance().getReference().child("Product Images");
CategoryName = getIntent().getExtras().get("category").toString();
ProductsRef = FirebaseDatabase.getInstance().getReference().child("Products");
ProductsInfo = FirebaseDatabase.getInstance().getReference().child("ProductsInfo");
mAuth = FirebaseAuth.getInstance().getCurrentUser();
AddProductButton = (Button) findViewById(R.id.add_product);
InputProductName = (EditText) findViewById(R.id.product_name);
InputProductImage = (ImageView) findViewById(R.id.product_image_select);
InputProductPrice = (EditText) findViewById(R.id.product_price);
InputProductQauntity = (EditText) findViewById(R.id.product_quantity);
InputProductState = (EditText) findViewById(R.id.product_state);
InputStoreName = (EditText) findViewById(R.id.store_name);
loadingBar = new ProgressDialog(this);
InputProductDescription = (EditText) findViewById(R.id.product_description);
InputProductImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
AddProductButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateProductData();
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
#Override
protected void onActivityResult
(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GalleryPick && resultCode == RESULT_OK && data != null) {
ImageUri = data.getData();
InputProductImage.setImageURI(ImageUri);
}
}
private void validateProductData() {
Description = InputProductDescription.getText().toString();
Price = InputProductPrice.getText().toString();
Pname = InputProductName.getText().toString();
Quantity = InputProductQauntity.getText().toString();
State = InputProductState.getText().toString();
Store = InputStoreName.getText().toString();
if (ImageUri == null) {
Toast.makeText(this, "Please Add Product Image!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Description)) {
Toast.makeText(this, "Please Enter the Product Description!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Price)) {
Toast.makeText(this, "Please Enter the Product Price!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Pname)) {
Toast.makeText(this, "Please Enter the Product Name!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Quantity)) {
Toast.makeText(this, "Enter Quantity in Number!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(State)) {
Toast.makeText(this, "Specify the State of your Product!", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(Store)) {
Toast.makeText(this, "Store Name is Mandatory!", Toast.LENGTH_SHORT).show();
} else {
StoreProductInfo();
}
}
private void StoreProductInfo() {
loadingBar.setTitle("Adding Product");
loadingBar.setMessage("Please wait!");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime = currentTime.format(calendar.getTime());
// Unique Random Key for the Products added by the admin
productRandomKey = saveCurrentDate + saveCurrentTime;
// Unique Random Key to store the image added by the admin
final StorageReference filePath = ProductImageRef.
child(ImageUri.getLastPathSegment() + productRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
//Displaying the Upload Error to the seller
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String message = e.toString();
Toast.makeText(SellerAddProductActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(SellerAddProductActivity.this, "Image Uploaded!", Toast.LENGTH_SHORT).show();
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();
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadImageUrl = task.getResult().toString();
Toast.makeText(SellerAddProductActivity.this, "Product Image Added",
Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
}
});
}
private void SaveProductInfoToDatabase() {
HashMap<String, Object> productMap = new HashMap<>();
productMap.put("pid", productRandomKey);
productMap.put("storename", Store);
productMap.put("date", saveCurrentDate);
productMap.put("time", saveCurrentTime);
productMap.put("description", Description);
productMap.put("image", downloadImageUrl);
productMap.put("Category", CategoryName);
productMap.put("state", State);
productMap.put("quantity", Quantity);
productMap.put("price", Price);
productMap.put("pname", Pname);
ProductsRef.child("Products").child(userID).child(productRandomKey);
ProductsInfo.child(productRandomKey).updateChildren(productMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(SellerAddProductActivity.this, SellerAddProductActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(SellerAddProductActivity.this, "Product
Added",Toast.LENGTH_SHORT).show();
} else {
loadingBar.dismiss();
String message = task.getException().toString();
Toast.makeText(SellerAddProductActivity.this,
"Error:"+message,Toast.LENGTH_SHORT).show();
}
}
});
} }
This how I'm displaying the products on the buyer/user activity
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private DatabaseReference productsRef;
private RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
productsRef = FirebaseDatabase.getInstance().getReference().child("Products");
recyclerView = findViewById(R.id.recycler_menu);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Products> options =
new FirebaseRecyclerOptions.Builder<Products>()
.setQuery(productsRef, Products.class).build();
FirebaseRecyclerAdapter<Products, ProductsViewHolder> adapter
= new FirebaseRecyclerAdapter<Products, ProductsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProductsViewHolder holder,int position,#NonNull final Products model){
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price " + model.getPrice() + "$");
Picasso.get().load(model.getImage()).into(holder.imageView);
//sending the product ID to the ProductDetailsActivity
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
});
}
#NonNull
#Override
public ProductsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_products,parent,false);
ProductsViewHolder holder = new ProductsViewHolder(view);
return holder;
}
};
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
adapter.startListening();
recyclerView.setAdapter(adapter);
}
As I understand, you want to bring up all the sellers information to the one logged in in your app.
To do that you can do a for loop inside products to get each seller id, and then querie each user to get the products.
But you will need to change your database structure to make it easier.
I recommend to you to store inside the nested child Products the id of that product to querie in another table. For example
Products
|
--- userID
|
--- Products
|
--- product_key1: true
|
--- product_key2: true
And then in another node have the information of that product
ProductsInfo
|
--- product_key1
| |
| --- productName: "Orange"
| |
| --- productPrice: 1
|
--- product_key2
|
--- productName: "Pineapple"
|
--- productPrice: 3
So now, we will just get each userID and get each user products
First, instead of hardcoded seller names you should use getUid() to get each seller unique UID.
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance().getCurrentUser();
String userID = mAuth.getUid(); //--> Store each seller name with this ID
Now we just loop inside Products to get each user ID
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
Log.d("SellersID", userKey);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now that you have all the sellers key you can loop inside products and get each product key for each seller, and with that you can now get the data from ProductsInfo node
Your problem is at your database reference productsRef
You should add more to your reference, based on what you want to get from your database:
productsRef = FirebaseDatabase.getInstance().getReference().child("Products").child("here you put seller name"); // in your case the seller name is "d"
Hope it helps. For more informations ask me

Categories

Resources