Checkboxes not working correctly in RecyclerView - java

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.

Related

nothing happen when i select the song to upload from my android app to firebase realtime database

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

Data being added as new instead of updating firebase firestore

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());

Arraylist Seems Empty

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());
}
});
}
}
}
}
});
}
}

First and last switch button getting triggred in recycler view

Hi I have switch button (switchTaskFinished) on my recycler view,when I am clicking any button, the last button is getting selected. Also when I press button it updates the data to firebase. And changes the button status accordingly. But even though buttons value is true it only updates last button status not others.
public class MyAdaptorUser extends RecyclerView.Adapter<MyAdaptorUser.myViewHolder> {
private Context context;
private ArrayList<TaskModel> taskLists;
private Switch switchTaskFinished;
private OnTaskClickListner mTaskListner;
private AlertDialog dialog;
private AlertDialog.Builder builder;
private TaskConfirmationSender taskConfirmationSender;
public MyAdaptorUser(Context c, ArrayList<TaskModel> t, OnTaskClickListner onTaskClickListner) {
context = c;
taskLists = t;
this.mTaskListner = onTaskClickListner;
}
#NonNull
#Override
public MyAdaptorUser.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
builder = new AlertDialog.Builder(parent.getContext());
builder.setTitle("Please Wait").setView(R.layout.my_progress_view).setCancelable(false);
dialog = builder.create();
return new MyAdaptorUser.myViewHolder(LayoutInflater.from(context).inflate(R.layout.task_preview, parent, false), mTaskListner);
}
#Override
public void onBindViewHolder(#NonNull MyAdaptorUser.myViewHolder holder, final int position) {
//Set title and description to task preview textviews
holder.title.setText(taskLists.get(position).getTaskTitle());
holder.dueDate.setText(taskLists.get(position).getDueDate());
holder.description.setText(taskLists.get(position).getTaskDescription());
//Sets the path of database to taskAwatingConfirmation/task_title/UserEmail
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
try {
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
email = removeSpecialCharacter(email);
final DatabaseReference taskConfirmationRef = dbRef
.child("taskAwatingConfirmation")
.child(taskLists.get(position).getTaskTitle())
.child(email);
taskConfirmationRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Fetching switchButton Status (Task finished) from database
switchTaskFinished.setChecked(false);
String buttonStatus = (String) dataSnapshot.child("buttonStatus").getValue();
if (buttonStatus != null) {
Log.d("taskerror", buttonStatus);
if (buttonStatus.equals("true")) {
switchTaskFinished.setChecked(true);
} else if (buttonStatus.equals("false")) {
switchTaskFinished.setChecked(false);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
switchTaskFinished.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
//dialog = builder.show();
taskConfirmationSender = new TaskConfirmationSender();
//When Task Finished button is clicked send data to database
sendConfirmationToAdmin(new FirebaseCallBack() {
#Override
public void Callback(TaskConfirmationSender taskConfirmationSender) {
taskConfirmationSender.setButtonStatus(String.valueOf(buttonView.isChecked()));
taskConfirmationSender.setTaskDueDate(taskLists.get(position).getDueDate());
if (buttonView.isChecked()) {
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}
}
});
}
});
} catch (NullPointerException ignored) {
dialog.dismiss();
}
}
private String removeSpecialCharacter(String email) {
StringBuffer sbf = new StringBuffer(email);
email = String.valueOf(sbf.reverse());
int length = email.length();
email = email.substring(4, length);
StringBuffer stringBuffer = new StringBuffer(email);
email = String.valueOf(stringBuffer.reverse());
return email.replace("#", "_");
}
private void sendConfirmationToAdmin(final FirebaseCallBack firebaseCallBack) {
DatabaseReference volunteerRef = FirebaseDatabase.getInstance().getReference()
.child("Volunteer").child("Member")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
taskConfirmationSender = new TaskConfirmationSender();
try {
//Fetching details of users (full name, email) from database and setting their value to taskConfirmation Object
volunteerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("fullName").getValue().toString();
String userEmail = dataSnapshot.child("email").getValue().toString();
String userId = dataSnapshot.getKey();
//TODO: Fetch UID of user and set it to taskConfirmation OBject
taskConfirmationSender.setUserEmail(userEmail);
taskConfirmationSender.setUserName(userName);
taskConfirmationSender.setId(userId);
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
String submissionDate = day + "/" + month + "/" + year;
taskConfirmationSender.setSubmissionDate(submissionDate);
firebaseCallBack.Callback(taskConfirmationSender);
/**/
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} catch (NullPointerException ee) {
}
}
private interface FirebaseCallBack {
void Callback(TaskConfirmationSender taskConfirmationSender);
}
#Override
public int getItemCount() {
return taskLists.size();
}
class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, dueDate, description;
OnTaskClickListner onTaskClickListner;
public myViewHolder(#NonNull View itemView, OnTaskClickListner onTaskClickListner) {
super(itemView);
title = itemView.findViewById(R.id.taskTitle);
dueDate = itemView.findViewById(R.id.taskDueDate);
description = itemView.findViewById(R.id.taskDescription);
switchTaskFinished = itemView.findViewById(R.id.switchTaskFinished);
this.onTaskClickListner = onTaskClickListner;
ConstraintLayout taskBar = itemView.findViewById(R.id.linearLayoutTaskBar);
itemView.setOnClickListener(this);
//hides delete task button
taskBar.setVisibility(View.GONE);
}
#Override
public void onClick(View v) {
onTaskClickListner.onTaskClick(getAdapterPosition());
}
}
public interface OnTaskClickListner {
void onTaskClick(int position);
}
}
Maybe its because of the valueEventListener that stays attached:
Instead of this:
taskConfirmationRef.addValueEventListener(new ValueEventListener() {.........
Do this:
taskConfirmationRef.addListenerForSingleValueEvent(new ValueEventListener() {......
And set the switch to checked or unchecked when you turn on or off:
if (buttonView.isChecked()) {
//here
switchTaskFinished.setChecked(true);
taskConfirmationRef.setValue(taskConfirmationSender).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
});
}else{
//here
switchTaskFinished.setChecked(false);
...................

How to display data in a recyclerview using FirebaseUI?

I am new to firebase and I am in love with this real-time database thing.
However, I am not sure how to display nested data in a recycled view.
Following is my database structure :-
I want to display the data at 0,1,2...The data consist of information about different books.
This is what I have tried so far:-
private void getSelectedBooks() {
FirebaseRecyclerAdapter<BooksInfo, BooksViewHolder> adapter = new FirebaseRecyclerAdapter<BooksInfo, BooksViewHolder>(
BooksInfo.class,
R.layout.book_list,
BooksViewHolder.class,
nextOrder.child(String.valueOf(index))
) {
#Override
protected void populateViewHolder(BooksViewHolder viewHolder, final BooksInfo model, final int position) {
Log.d("BOOKDETAILS",model.getTitle());
// viewHolder.setTitle(model.getTitle());
// viewHolder.setISBN(model.getISBN());
// viewHolder.setDiscount(model.get());
// viewHolder.setQty(model.getQuantity());
// viewHolder.setPrice(model.getPrice());
// viewHolder.setGrossValue(model.get);
// viewHolder.setNetValue(model.get);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseReference ref = getRef(position);
String key = ref.getKey();
Toast.makeText(AddOrderActivity.this, key, Toast.LENGTH_SHORT).show();
// getRetailerInfo(key);
}
});
}
};
selectedBookRecyclerView.setAdapter(adapter);
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(String.valueOf(index)).exists()) {
// run some code
// DisableProgress();
} else {
// DisableProgress();
// Toast.makeText(RetailerActivity.this, "No retailers to display", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Here DatabaseReference nextOrder = mDatabase.child(userId).child("order_details").child(String.valueOf(index));
Any help or suggestion is appreciated.Thank you.

Categories

Resources