I have created a checkbox that can only select one checkbox at a time. I am then storing the data of the checkbox in a string which i then use in a different method. the checkbox is used in a recyclerview and it is displayed using a firebase recycler adapter. my app requires the checkbox to remain checked at all times even when app is closed as I am launching the app with a foreground service and it uses the data that is checked in the checkbox for an intent in a different class. What i want to know is how to get the checkbox and the data that is stored using this checkbox to save even if my app is closed . I have done some digging and seen that you can use a shared preference but I cant seem to work out how to implement it in my application. here is the code I am currently using to implement the checkbox: firebase recycler adapter
adapter1 = new FirebaseRecyclerAdapter<contact, contactAdapter>(options1) {
@Override
protected void onBindViewHolder(@NonNull final contactAdapter holder, final int position, @NonNull contact model) {
holder.contactName.setText(model.getContactName());
holder.contactPhone.setText(model.getContactPhone());
if(lastCheckedPos == position){
holder.chk.setChecked(true);
}
else{
holder.chk.setChecked(false);
}
holder.chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (position == lastCheckedPos) {
holder.chk.setChecked(false);
lastCheckedPos = -1;
}else {
lastCheckedPos = position;
for (int i = 0; i < adapter1.getItemCount(); i++) {
if (adapter1.getItem(i).isSelected(true)) {
number = ((TextView) holder.itemView.findViewById(R.id.contactPhone)).getText().toString();
Toast.makeText(getActivity(), "Data Inserted....." + number, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
contactsView.post(new Runnable()
{
@Override
public void run() {
adapter1.notifyDataSetChanged();
}
});
}
}
});
}
@NonNull
@Override
public contactAdapter onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new contactAdapter(LayoutInflater.from(getActivity()).inflate(R.layout.item_contacts, parent, false));
}
};
Adapter class
public class contactAdapter extends RecyclerView.ViewHolder{
public TextView contactName, contactPhone;
CheckBox chk;
AdapterView.OnItemClickListener itemClickListener;
public contactAdapter(@NonNull View itemView) {
super(itemView);
contactName = itemView.findViewById(R.id.contactName);
contactPhone = itemView.findViewById(R.id.contactPhone);
chk = itemView.findViewById(R.id.myCheckBox);
this.setIsRecyclable(false);
}
}
Any suggestions?
Aucun commentaire:
Enregistrer un commentaire