How to change switch conditions using Toggle button? - android

I have a program which creates a list of to-dos that allows the user to set a date/time for the app to notify them about it. There's a checkbox that says 'Notify me' which is supposed to schedule the notification. But, in the main RecyclerView of the list, there is also a toggle switch that allows the user to turn off/on the notification after they've saved it. Problem is, the toggle switch doesn't seem to be changing the notification state.
holder.notifSwitch.setChecked(journalModel.isNotify());
if(journalModel.getJournalDateNotify().getTime() > System.currentTimeMillis())
{
holder.notifSwitch.setVisibility(View.VISIBLE);
} else {
holder.notifSwitch.setVisibility(View.INVISIBLE);
}
holder.notifSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!journalModel.isNotify())
{
createJournalFunction.updateJournal(realm, journalModel.getRealmJournalNo(),true);
} else
{
createJournalFunction.updateJournal(realm, journalModel.getRealmJournalNo(), false);
}
}
});
And here is the code for updating the Realm object:
public boolean updateJournal (Realm realm, final int realmJournalNo, final boolean isNotify){
success = false;
try{
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
final TblJournal tblJournal = realm.where(TblJournal.class).equalTo("realmJournalNo", realmJournalNo).findFirst();
tblJournal.setNotify(isNotify);
success = true;
}
});
}catch (RealmException e){
Log.i("INFO","update Retail Exception: "+e.toString());
success = false;
}finally {
return success;
}
}

As per your code your are not updating journalModel.isNotify= true or false in on click. journalModel.setIsNotify(true):/journalModel.setIsNotify(false):

holder.notifSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// status="true"; //edit here
switch_btn.setChecked(true);
} else {
// status="false"; //edit here
switch_btn.setChecked(false);
}
}
});

Everything looks fine, you just need to modify your onClick method.
holder.notifSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox checkbox = (CheckBox)v;
createJournalFunction.updateJournal(realm, journalModel.getRealmJournalNo(),checkbox.isChecked());
}
});

Related

switch button works on the second click - Android

I added a switch button to my app and created a setOnCheckChangeListener the will pop up toast message..
But it works only after the second click.
Any ideas?
MainActivity:
public void checkSwitch (View view)
{
addBeeps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
beeps = true;
Toast.makeText(MainActivity.this,"beeps is True",Toast.LENGTH_LONG).show();
}else
{
beeps = false;
Toast.makeText(MainActivity.this,"beeps is False",Toast.LENGTH_LONG).show();
}
}
});
}
I think in xml file which contains addBeeps switch you are using this code.
<Switch
android:id="#+id/addBeeps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="checkSwitch"/>
Root cause: For the first time when you check the switch, a listener will be set on it and do nothing, the second time when you check the switch again the listener is triggered and the Toast showed.
Solution: Here is a solution for you.
Remove onClick from the switch in xml file
<Switch
android:id="#+id/addBeeps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Delete or comment-out checkSwitch method from MainActivity and move set listener block code to onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBeeps = findViewById(R.id.addBeeps);
// TODO: Put set listener block code here
addBeeps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
beeps = true;
Toast.makeText(MainActivity.this, "beeps is True", Toast.LENGTH_LONG).show();
} else {
beeps = false;
Toast.makeText(MainActivity.this, "beeps is False", Toast.LENGTH_LONG).show();
}
}
});
}
// TODO: Delete or comment-out this method
// public void checkSwitch(View view) {
// addBeeps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// #Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
// beeps = true;
// Toast.makeText(MainActivity.this, "beeps is True", Toast.LENGTH_LONG).show();
// } else {
// beeps = false;
// Toast.makeText(MainActivity.this, "beeps is False", Toast.LENGTH_LONG).show();
// }
// }
// });
// }

How to set checkbox to a custom text in string and save into database?

I am working on android. I have a checkbox in my app and I want to save a custom text against my checkbox when it is checked or not.
CheckBox atbSealedCheckBox;
String selectedAtbSealedValue ="";
atbSealedCheckBox = (CheckBox) view.findViewById(R.id.atbCheckBox);
Now, If I checked the checkbox then I want to store Yes otherwise No. Also, I want to store it in my DB. For this I have already created get and set methods in my Model
private String atbSealed;
public String getAtbSealed(){return atbSealed;}
public void setAtbSealed(String atbSealed){this.atbSealed=atbSealed;}
Update 1
As per suggestion, I have tried below
atbSealedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(isatbSealedChecked)
{
selectedAtbSealedValue = "Yes";
ctQuantitySpinner.setEnabled(false);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = true;
}
else
{
selectedAtbSealedValue = "No";
ctQuantitySpinner.setEnabled(true);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = false;
}
}
});
But It doesn't help me out. Also, the ctQuantitySpinner is not disabled on atbSealedCheckbox checked. Also if checked the boolean value of the checkbox is not changed to true. Although in log I do see the selectedAtbSealedValue but it's not set in the app. In my SaveDataLocal() function I have set the value like below
survey.setAtbSealed(this.selectedAtbSealedValue);
SurveyManager dbHelper = new SurveyManager(getActivity());
dbHelper.addSurvey(survey);
I have also tried the below code
atbSealedCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(((CheckBox)v).isChecked())
{
ctQuantitySpinner.setEnabled(false);
ctQuantitySpinner.setSelection(0);
selectedAtbSealedValue = "Yes";
isatbSealedChecked = true;
//atbCheckBoxEdittext.setText(selectedAtbCheckBox);
}
else {
ctQuantitySpinner.setEnabled(true);
ctQuantitySpinner.setSelection(0);
selectedAtbSealedValue = "No";
isatbSealedChecked = false;
//atbCheckBoxEdittext.setText(selectedAtbCheckBox);
}
}
});
This code shows me the selected checkbox value, disabled the spinner and set the spinner value to null. but again the checkbox value is not saved.
How can I save custom text in a string?
Try this, it work for me:
atbSealedCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked ) {
if (isChecked) {
selectedAtbSealedValue = "yes";
} else {
selectedAtbSealedValue = "no";
}
}
} );
After that, you can store selectedAtbSealedValue into DB;
Update: Your fixed code:
atbSealedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b)
{
selectedAtbSealedValue = "Yes";
ctQuantitySpinner.setEnabled(false);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = true;
}
else
{
selectedAtbSealedValue = "No";
ctQuantitySpinner.setEnabled(true);
ctQuantitySpinner.setSelection(0);
isatbSealedChecked = false;
}
}
});
As long as I understand your question, you want to change this variable String selectedAtbSealedValue =""; when user checked your checkbox.
To achieve this statement, you can use onCheckedListener that is triggered as soon as users checked or removed the check from your checkbox.
atbSealedCheckBox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged( CompoundButton buttonView, boolean isChecked ) {
// Todo something.
}
} );
This will help you.
At submit button get the current value of checkbox.
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
control_of_vectors_value = control_of_vectors_checkbox.isChecked() == true ? "yes" : "no"; }}

Recyclerview items with checkbox gets distorted

I have a RecyclerView with items and all of them have a checkbox. The point is that you can only set one checkbox as checked (something like favourite). Everything works fine until there are enough items that you need to scroll the RecyclerView. But, when there's enough items to scroll, then some of the item's names disappear and none of the checkboxes work except one and it is all stuck. Also, I get the following exception:
"Cannot call this method while RecyclerView is computing a layout or scrolling"
This is what I am doing:
holder.getBinder().cbIsFavourite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (mListener == null) {
return;
}
if (isChecked) {
for (Peem peemTmp : mPeemList) {
if (peemTmp.isFavourite()) {
peemTmp.setFavourite(false);
}
}
peem.setFavourite(true);
PeemAdapter.this.notifyDataSetChanged();
} else {
peem.setFavourite(false);
removeFavouriteShops(peem);
}
mListener.onFavouriteChecked(peem);
}
});
The error occurs on this line PeemAdapter.this.notifyDataSetChanged();
If I remove that line it is all okay, but multiple checkboxes can be selected which is not the idea.
Why not use RadioButton and RadioGroup ?
Else try to call notifyDataSetChanged() in a post Runnable, it will be called after layout computing. Something like this:
myView.post(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
EDITED:
holder.getBinder().cbIsFavourite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (mListener == null) {
return;
}
if (isChecked) {
for (Peem peemTmp : mPeemList) {
if (peemTmp.isFavourite()) {
peemTmp.setFavourite(false);
}
}
peem.setFavourite(true);
holder.getBinder().cbIsFavourite.post(new Runnable() {
#Override
public void run() {
PeemAdapter.this.notifyDataSetChanged();
}
});
} else {
peem.setFavourite(false);
removeFavouriteShops(peem);
}
mListener.onFavouriteChecked(peem);
}
});

Android setOnCheckedChangeListener runs twice

This is my code. What can ba a cause?
holder.favorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
addFavorite(famous);
} else {
deleteFavorite(famous);
}
}
});
When isChecked=true, firstly is run addFavorite() and after that deleteFavorite().
When isChecked=false, firstly is run deleteFavorite() and after that addFavorite().
Don't know why...
EDIT: When I scroll down/up my ListView it calls these methods too... Weird...
private void deleteFavorite(final FamousTop40Ranking famous) {
DeleteFavoriteData data = new DeleteFavoriteData(famous.getId());
FavoriteDeleteApi.Factory.getInstance().deleteFavorite(data.getData())
.enqueue(new Callback<StatusInfoModel>() {
#Override
public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
showToast(mActivity, "Famous deleted from your Favorites list.");
famous.setFollowersCountry(famous.getFollowersCountry() - 1);
famous.setFollowersWorld(famous.getFollowersWorld() - 1);
notifyDataSetChanged();
}
#Override
public void onFailure(Call<StatusInfoModel> call, Throwable t) {
Log.d("deleteFavorite", mActivity.getString(R.string.something_went_wrong) + t.getMessage());
}
});
}
private void addFavorite(final FamousTop40Ranking famous) {
FavoriteCountApi.Factory.getInstance().countFavorites()
.enqueue(new Callback<CountFavoriteModel>() {
#Override
public void onResponse(Call<CountFavoriteModel> call, Response<CountFavoriteModel> response) {
if (response.isSuccessful()) {
if (response.body().getCount() < 20) {
FavoriteAddApi.Factory.getInstance().addFavorite(String.valueOf(famous.getId()))
.enqueue(new Callback<StatusInfoModel>() {
#Override
public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
showToast(mActivity, "Famous added from your Favorites list.");
famous.setFollowersCountry(famous.getFollowersCountry() + 1);
famous.setFollowersWorld(famous.getFollowersWorld() + 1);
notifyDataSetChanged();
}
#Override
public void onFailure(Call<StatusInfoModel> call, Throwable t) {
Log.d("addFavorite", mActivity.getString(R.string.something_went_wrong) + t.getMessage());
}
});
} else {
showToast(mActivity, mActivity.getString(R.string.reached_max_favorites));
}
}
}
#Override
public void onFailure(Call<CountFavoriteModel> call, Throwable t) {
Log.d("countFavorite", mActivity.getString(R.string.something_went_wrong) + t.getMessage());
}
});
}
getView() method:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_view_ranking_famous_single_item, parent, false);
}
final FamousTop40Ranking famous = famousModelList.get(position);
holder = new ViewHolder(convertView);
holder.name.setText(famous.getName());
if (mTab == 0) { // RankingFamousMainFragment.TAB_FAMOUS
holder.followers.setText(String.valueOf(famous.getFollowersWorld()));
} else {
holder.followers.setText(String.valueOf(famous.getFollowersCountry()));
}
if (famous.getIsFavorite().get(0).getFavorite().equals("1")) {
holder.favorite.setChecked(true);
} else {
holder.favorite.setChecked(false);
}
Glide
.with(mActivity)
.load(famous.getPhoto())
.fallback(R.drawable.bg_gradient)
.error(R.drawable.bg_gradient)
.centerCrop()
.crossFade()
.into(holder.photo);
holder.favorite.setOnCheckedChangeListener(null);
holder.favorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
addFavorite(famous);
} else {
deleteFavorite(famous);
}
}
});
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToast(mActivity, mActivity.getString(R.string.famous_clicked, position));
}
});
return convertView;
}
In getView. Move setonCHecked(null) before the if/else.
The reason this is hapening is getView might get called alot of times, in this case i think it is called because when you change state(check/uncheck) it redraws the button. And in your getView you are calling setChecked which triggers the listener. Setting the listener to null before calling holder.favorite.setChecked(true/false) wont double trigger it.
About up/down issue- It is the same, when the view is of the screen it is deleted. When it appears again it calls getView whichi triggers everything due to holder.favorite.setChecked(true) activating the onCheckChangedLIstener
As an example:
holder.favorite.setOnCheckedChangeListener(null);
holder.favorite.setChecked(true);
holder.favourite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// handle your logic
}
});
I may be late for the party!.. but this is how I fix a double trigger on radio Buttons, in my case I have a RadioGroup, that helps with the behavior of a group of radio buttons.
When you click on a specific radio button you expect to trigger lambda expression in "setOnCheckedChangeListener", which is normal.
But when you "reset" the group and need that no radio button be selected, you usually call either:
radioGroup.clearCheck()
or
radioGroup.check(-1)
But when you do that, the listener receives 2 calls, the first is for the radio button that is going to be "unchecked",
the second call with the radio button id equals -1.
so what ai have done, and work to me is:
radioGroup.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->
//If not -1, means that is a radio button that was been clicked (don't know yet is checked or not)
if (checkedId > 0) {
//Get radio button element
val radio: RadioButton = group.findViewById(checkedId)
// Preguntar por si esta checked == true ?
if (radio.isChecked) {
when (checkedId) {
R.id.rb_1 -> {
viewModel.onSetPv(1)
}
R.id.rb_2 -> {
viewModel.onSetPv(2)
}
else -> false
}
}
}
})
Best regards!
Actually, it's not an issue! Why? Imagine you have a radio-group, and you select one of the options; if you rotate the device, the selected option should be stay selected. (It save the state. In fact, it works just like view-model)
But, when it could be a problem? At first state, when you didn't choose any option. How to solve it? Just add if (checkedId > 0) before you check the ids:
radioGroup.setOnCheckedChangeListener((radioGroup, checkedId) -> {
if (checkedId > 0) {
// here check the ids
}
});
The other situation that you can face a problem is, when you use a same radio-group for multitasks (like quiz app). In this situation, what I did was using view-model. I let the view-model take care of saving state and right after I check the Ids, I add radioGroup.check(-1); example:
radioGroup.setOnCheckedChangeListener((radioGroup, checkedId) -> {
if (checkedId > 0) {
// here check the ids
// use viewModel
radioGroup.check(-1);
}
});

How I can change state of widget switch from check to uncheck?

I want to recieve data from thingspeak and change automatically state of switch from checked to unchecked or vice versa.
This is my code, but it doesn't work, just can set text but can't change state.
Please help me!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
myswitch1 = (Switch) findViewById(R.id.switch1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
postdata2();
}
});
t.start();
now_da1.setText(get_da1);
if(get_dk1 == "1") {
myswitch1.setChecked(False);
}
else if (get_dk1 =="0") {
myswitch1.setChecked(True);
}
}
});
myswitch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
t1 = "1";
} else {
t1 = "0";
}
}
});
public void postdata2() {
HttpRequest mReq = new HttpRequest();
get_t1 = mReq.sendGet("https://thingspeak.com/channels/106453/field/1/last");
get_da1 = get_t1.substring(0, 2);
get_dk1 = get_t1.substring(3, 3);
Log.d(myGet, get_dk1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
use this myswitch1.setChecked(false); to uncheck and myswitch1.setChecked(true); to make it checked.
Happy Coding :)
When comparing the value of two Strings always use the equals() method which compares the values instead of using == which compares the object references.
For example:
String first = "1";
String second = "1";
first == second will return false because they are not referencing to the same object. However, first.equals(second) will return true because the value of the two Strings are identical.
You can try replacing the conditions with this:
if (get_dk1.equals("1")) {
myswitch1.setChecked(false);
} else if (get_dk1.equals("0")) {
myswitch1.setChecked(true);
}

Categories

Resources