I want to check the nickname is already taken or not data comes from firestorm and adds to the list but before if the statement the list seems empty and I can't control nickname is already taken or not here is my code I have no idea why does it seem empty.
Here is my Code
public class NickName extends AppCompatActivity {
private String userid;
private FirebaseAuth mAuth;
private FirebaseFirestore firestore;
EditText nickText;
String email;
private ArrayList<String> nicklist;
String nickforcheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nick_name);
mAuth=FirebaseAuth.getInstance();
nicklist=new ArrayList<>();
firestore=FirebaseFirestore.getInstance();
nickText=findViewById(R.id.nicktext);
Intent intent=getIntent();
email = intent.getStringExtra("email");
}
public void kayıt(View view){
CollectionReference collectionReference=firestore.collection("Kullanıcılar ve Skorlar");
collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if(error!=null){
Log.e("tag",error.getLocalizedMessage());
}
if(value!=null){
for(DocumentSnapshot snapshot:value.getDocuments()){
Map<String,Object> userdata=snapshot.getData();
nickforcheck=(String) userdata.get("nick");
nicklist.add(nickforcheck);
}
}
}
});
String nick=nickText.getText().toString();
userid=mAuth.getCurrentUser().getUid();
DocumentReference documentReference=firestore.collection("Kullanıcılar ve Skorlar").document(userid);
Map<String,Object> userdata=new HashMap<>();
System.out.println(nicklist);
if(nicklist.contains(nick)) {
Toast.makeText(this, "Bu Kullanıcı İsmi Zaten Mevcut", Toast.LENGTH_SHORT).show();
}else{
userdata.put("nick",nick);
userdata.put("email",email);
userdata.put("skor",0);
documentReference.set(userdata).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.d("Tag","Veri alındı"+userid);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("Tag","işlem başarısız"+e.toString());
}
});
Intent intent=new Intent(NickName.this,Secimekrani.class);
startActivity(intent);
finish();
}
}
}
You got empty nickList because ,all code outside addSnapshotListener will be executed before get the snapshot from firestore .so do all work ,once you successfully get snapshot.
public void kayıt(View view){
CollectionReference collectionReference=firestore.collection("Kullanıcılar ve Skorlar");
collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if(error!=null){
Log.e("tag",error.getLocalizedMessage());
}
if(value!=null){
for(DocumentSnapshot snapshot:value.getDocuments()){
Map<String,Object> userdata=snapshot.getData();
nickforcheck=(String) userdata.get("nick");
nicklist.add(nickforcheck);
String nick=nickText.getText().toString();
userid=mAuth.getCurrentUser().getUid();
DocumentReference documentReference=firestore.collection("Kullanıcılar ve Skorlar").document(userid);
Map<String,Object> userdata=new HashMap<>();
System.out.println(nicklist);
if(nicklist.contains(nick)) {
Toast.makeText(this, "Bu Kullanıcı İsmi Zaten Mevcut", Toast.LENGTH_SHORT).show();
}else{
userdata.put("nick",nick);
userdata.put("email",email);
userdata.put("skor",0);
documentReference.set(userdata).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Log.d("Tag","Veri alındı"+userid);
//once user data added in firestore ,finish your activity .
Intent intent=new Intent(NickName.this,Secimekrani.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("Tag","işlem başarısız"+e.toString());
}
});
}
}
}
}
});
}
}
Related
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);
}
});
I was creating an app for my semester project to upload songs from mobile storage to firebase's realtime database. app run correctly but when i select the songs to upload nothing happens and the app also does not crash. my main activity code is:
public class MainActivity extends AppCompatActivity {
private boolean checkPermission = false;
Uri uri;
String songName, songUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Create 2 function
//onCreate option menu to initialize menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.custom_menu , menu);
return super.onCreateOptionsMenu(menu);
}
//2nd function is onoption item selected (button sy reloated sari coding yaha hogi
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==R.id.nav_upload){
if (validatePermission()){
picksongs();
}
}
return super.onOptionsItemSelected(item);
}
private void picksongs() {
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload , 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 1){
if (requestCode==RESULT_OK){
uri = data.getData();
Cursor mcursor = getApplicationContext().getContentResolver().query(uri , null, null, null , null);
int indexName = mcursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
songName = mcursor.getString(indexName);
mcursor.close();
uploadSong();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadSong() {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Songs").child(uri.getLastPathSegment());
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
//upload files to firebase
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isComplete());
Uri urlSong =uriTask.getResult();
songUrl = urlSong.toString();
uploadtoDataBase();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot tasksnapshot) {
double progress = (100.0*tasksnapshot.getBytesTransferred())/tasksnapshot.getTotalByteCount();
int currentProgress = (int)progress;
progressDialog.setMessage("Uploaded "+ currentProgress+"%");
}
});
}
private void uploadtoDataBase(){
Song songobj = new Song(songName , songUrl);
FirebaseDatabase.getInstance().getReference("Songs").push().setValue(songobj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this, "Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private boolean validatePermission(){
Dexter.withActivity(this)
//Dexter.withActivity(MainActivity.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
checkPermission=true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
checkPermission=false;
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
return checkPermission;
}
}
please help me to find where i made a mistake. but their is 1 problem startActivityForResult(android.content.Intent, int)' is deprecated is that cause the problem? if yes then how can i solve this
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());
This question already has answers here:
How to return a DocumentSnapShot as a result of a method?
(2 answers)
Closed 9 months ago.
Here is my code. I use this array list in my adapater for showing in listview
public ArrayList<String> loadFromFirebase() {
ArrayList<String> arrayList = new ArrayList<>();
db.collection("notite").whereEqualTo("User email", user.getEmail())
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful() && !task.getResult().isEmpty()) {
DocumentSnapshot documentSnapshot = task.getResult().getDocuments().get(0);
String documentId = documentSnapshot.getId();
db.collection("notite").document(documentId).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()) {
String notita = documentSnapshot.getString("Detalii");
arrayList.add(notita);
} else {
Toast.makeText(getContext(), "Notes does not exist",
Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Failure retrieving",
Toast.LENGTH_LONG).show();
Log.d("Retrieve", e.toString());
}
});
} else {
Toast.makeText(getContext(), "Does not exist"
, Toast.LENGTH_LONG).show();
}
}
});
right here
return arrayList;
}
Before the return, my arraylist is empty. can you guys help me?
I'm not sure how to resolve your empty list but you can populate your
adapter after you add the item in the list, instead of returning your
list, like:
public void loadFromFirebase() {
ArrayList<String> arrayList = new ArrayList<>();
db.collection("notite").whereEqualTo("User email", user.getEmail())
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful() && !task.getResult().isEmpty()) {
DocumentSnapshot documentSnapshot = task.getResult().getDocuments().get(0);
String documentId = documentSnapshot.getId();
db.collection("notite").document(documentId).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()) {
String notita = documentSnapshot.getString("Detalii");
arrayList.add(notita);
arrayAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,
arrayList);
listView.setAdapter(arrayAdapter);
} else {
Toast.makeText(getContext(), "Notes does not exist",
Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Failure retrieving",
Toast.LENGTH_LONG).show();
Log.d("Retrieve", e.toString());
}
});
} else {
Toast.makeText(getContext(), "Does not exist"
, Toast.LENGTH_LONG).show();
}
}
});
}
I am using a RecyclerView to display a list of activities saved in my Firebase database. I have added a checkbox to the layout of the activity view so that the user can select whether they want to add this activity to their audit profile.
When the user clicks the checkbox to select the activity, I want to add this activity to their profile (which is stored in a separate table) and update a field in the original activity table to say that it is now included in the audit profile. When they uncheck the box, it is removed from their profile and the original activity is updated to reflect this.
However, when I try doing this, my checkboxes start behaving incorrectly (such as a checkbox being checked that definitely hasn't been clicked by the user, checkboxes not staying ticked). This only happens when I have both the code to add the activity to the profile and to update the original activity.
Any ideas? I think it might be something to do with state, but I'm not sure how to go about doing this.
My code is as follows
auditAdapter = new FirestoreRecyclerAdapter<Activity, AuditBuilder.AuditViewHolder>(auditBuilder) {
#Override
protected void onBindViewHolder(#NonNull final AuditBuilder.AuditViewHolder auditViewHolder, int i, #NonNull final Activity activity) {
auditViewHolder.aAuditActivityName.setText(activity.getActivity_Name());
auditViewHolder.aAuditActivityType.setText(activity.getActivity_Type());
auditViewHolder.aAuditActivityDate.setText(activity.getActivity_Date());
final String docId = auditAdapter.getSnapshots().getSnapshot(i).getId();
auditViewHolder.auditCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
//ADD DOCUMENT ID TO DATABASE
DocumentReference documentReference = fStore.collection("audits")
.document(user.getUid())
.collection("myAuditActivities")
.document(docId);
Map<String, Object> audit = new HashMap<>();
audit.put("Activity_ID", docId);
audit.put("Activity_Name", activity.getActivity_Name());
audit.put("Activity_Description", activity.getActivity_Description());
audit.put("Activity_Type", activity.getActivity_Type());
audit.put("Activity_Date", activity.getActivity_Date());
audit.put("Activity_Hours", activity.getActivity_Hours());
audit.put("Activity_Mins", activity.getActivity_Mins());
audit.put("Activity_Ref1", activity.getActivity_Ref1());
audit.put("Activity_Ref2", activity.getActivity_Ref2());
audit.put("Activity_Ref3", activity.getActivity_Ref3());
audit.put("Activity_Ref4", activity.getActivity_Ref4());
audit.put("Image_URL", activity.getImage_URL());
audit.put("In_Audit", true);
documentReference.set(audit).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "Activity successfully added to audit");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AuditBuilder.this, "Error, try again", Toast.LENGTH_SHORT).show();
}
});
//UPDATE BOOLEAN IN_AUDIT IN CPD ACTIVITIES LOCATION IN DATABASE TO TRUE
DocumentReference updateActivity = fStore.collection("cpdActivities")
.document(user.getUid())
.collection("myCPD")
.document(docId);
Map<String, Object> updateBoolean = new HashMap<>();
updateBoolean.put("In_Audit", true);
updateActivity.update(updateBoolean).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "In_Audit successfully updated");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("TAG", "In_Audit update failed");
}
});
} else {
//CHECKBOX UNCHECKED, DELETES FROM AUDIT TABLE
DocumentReference docRef = fStore.collection("audits")
.document(user.getUid())
.collection("myAuditActivities")
.document(docId);
docRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "Activity successfully removed from audit");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AuditBuilder.this, "Error, try again", Toast.LENGTH_SHORT).show();
}
});
//UPDATE BOOLEAN IN_AUDIT IN CPD ACTIVITIES LOCATION IN DATABASE BACK TO FALSE
DocumentReference updateActivity = fStore.collection("cpdActivities")
.document(user.getUid())
.collection("myCPD")
.document(docId);
Map<String, Object> updateBoolean = new HashMap<>();
updateBoolean.put("In_Audit", false);
updateActivity.update(updateBoolean).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "In_Audit successfully updated");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("TAG", "In_Audit update failed");
}
});
}
}
});
auditViewHolder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), ActivityDetails.class);
//DISPLAYS ALL THE ATTRIBUTES OF THE ACTIVITY
i.putExtra("Activity_Name", activity.getActivity_Name());
i.putExtra("Activity_Description", activity.getActivity_Description());
i.putExtra("Activity_Type", activity.getActivity_Type());
i.putExtra("Activity_Date", activity.getActivity_Date());
i.putExtra("Activity_Hours", activity.getActivity_Hours());
i.putExtra("Activity_Mins", activity.getActivity_Mins());
i.putExtra("Activity_Ref1", activity.getActivity_Ref1());
i.putExtra("Activity_Ref2", activity.getActivity_Ref2());
i.putExtra("Activity_Ref3", activity.getActivity_Ref3());
i.putExtra("Activity_Ref4", activity.getActivity_Ref4());
i.putExtra("Image_URL", activity.getImage_URL());
i.putExtra("Activity_ID", docId);
v.getContext().startActivity(i);
}
});
}
#NonNull
#Override
public AuditBuilder.AuditViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.auditbuilder_view_layout, parent,false);
return new AuditViewHolder(view);
}
};
To try fixing this problem, I have added a boolean (In_Audit) to my model as follows:
public class Activity {
private String Activity_Name;
etc
private boolean In_Audit;
public Activity(String name, String date, String hours, String minutes, String description, String ref1, String ref2, String ref3, String ref4, String type, String image_URL, boolean In_Audit){
this.Activity_Name = Activity_Name;
this.Activity_Date = Activity_Date;
this.Activity_Hours = Activity_Hours;
this.Activity_Mins = Activity_Mins;
this.Activity_Description = Activity_Description;
this.Activity_Ref1 = Activity_Ref1;
this.Activity_Ref2 = Activity_Ref2;
this.Activity_Ref3 = Activity_Ref3;
this.Activity_Ref4 = Activity_Ref4;
this.Activity_Type = Activity_Type;
this.Image_URL = Image_URL;
this.In_Audit = false;
}
public boolean isIn_Audit() {
return In_Audit;
}
public void setIn_Audit(boolean in_Audit) {
In_Audit = in_Audit;
}
}
I have then referenced this in my onBindViewHolder like this
auditAdapter = new FirestoreRecyclerAdapter<Activity, AuditBuilder.AuditViewHolder>(auditBuilder) {
#Override
protected void onBindViewHolder(#NonNull final AuditBuilder.AuditViewHolder auditViewHolder, int i, #NonNull final Activity activity) {
auditViewHolder.aAuditActivityName.setText(activity.getActivity_Name());
auditViewHolder.aAuditActivityType.setText(activity.getActivity_Type());
auditViewHolder.aAuditActivityDate.setText(activity.getActivity_Date());
auditViewHolder.auditCheckBox.setSelected(activity.isIn_Audit());
final String docId = auditAdapter.getSnapshots().getSnapshot(i).getId();
auditViewHolder.auditCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
activity.setIn_Audit(true);
} else {
activity.setIn_Audit(false);}});
But I am still having errors with my check boxes, such as without scrolling, my checking my first checkbox and it not staying clicked. I'm not 100% sure I have applied the above logic correctly however.